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 |
|---|---|---|---|---|---|---|---|---|---|
How to use merge in pandas | 39,286,344 | <p>Sorry guys, I know it is a very basic question, I'm just a beginner</p>
<pre><code>In [55]: df1
Out[55]:
x y
a 1 3
b 2 4
c 3 5
d 4 6
e 5 7
In [56]: df2
Out[56]:
y z
b 1 9
c 3 8
d 5 7
e 7 6
f 9 5
</code></pre>
<p>pd.merge(df1, df2) gives:</p>
<pre><code>In [56]: df2
Out[56]:
x y z... | 0 | 2016-09-02T07:11:07Z | 39,286,469 | <p>You get that due to defaults for <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.merge.html" rel="nofollow"><code>pd.merge</code></a>:</p>
<blockquote>
<pre><code>merge(left, right, how='inner', on=None, left_on=None, right_on=None,
left_index=False, right_index=False, sort=False, suffixes=('_... | 3 | 2016-09-02T07:18:05Z | [
"python",
"pandas"
] |
How to use merge in pandas | 39,286,344 | <p>Sorry guys, I know it is a very basic question, I'm just a beginner</p>
<pre><code>In [55]: df1
Out[55]:
x y
a 1 3
b 2 4
c 3 5
d 4 6
e 5 7
In [56]: df2
Out[56]:
y z
b 1 9
c 3 8
d 5 7
e 7 6
f 9 5
</code></pre>
<p>pd.merge(df1, df2) gives:</p>
<pre><code>In [56]: df2
Out[56]:
x y z... | 0 | 2016-09-02T07:11:07Z | 39,290,277 | <p>What pd.merge does is that it joins two dataframes similar to the way two relations are merged using a 'JOIN' statement in case of relational databases. </p>
<p>When you merge df1 and df2 using the code: pd.merge(df1, df2), you haven't specified the values of any other argument of the pd.merge function, so it takes... | 1 | 2016-09-02T10:33:19Z | [
"python",
"pandas"
] |
How can you just get the index of an already selected row in pandas? | 39,286,508 | <pre><code>In [60]: print(row.index)
Int64Index([15], dtype='int64')
</code></pre>
<p>I already know that the row number is 15, in this example. But I don't need to know it's type or anything else. The variable which stores it would do something based on what that number is. </p>
<p>There was something else about pan... | 1 | 2016-09-02T07:20:09Z | 39,286,732 | <p>If you write</p>
<pre><code>row.index[0]
</code></pre>
<p>then you will get, in your case, the integer 15.</p>
<hr>
<p>Note that if you check</p>
<pre><code>dir(pd.Int64Index)
</code></pre>
<p>You can see that it includes the list-like method <code>__getitem__</code>.</p>
| 1 | 2016-09-02T07:32:15Z | [
"python",
"pandas"
] |
Different marker symbols | 39,286,585 | <p>I am trying do multiple plots but I am not getting the specified marker symbols for the mass flow rate, total pressure and the static pressure as shown in the attached image.</p>
<hr>
<hr>
<p><a href="http://i.stack.imgur.com/uCMA5.png" rel="nofollow">Plot</a></p>
| -1 | 2016-09-02T07:24:14Z | 39,287,145 | <p>I expect you are using matplotlib you can use something like this:</p>
<pre><code>#Dont forget on import
import matplotlib.pyplot as plt
# red dashes, blue squares and green triangles
plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')
</code></pre>
<p>In the code <strong>'r--'</strong>, <strong>'bs'</strong> and... | 0 | 2016-09-02T07:53:56Z | [
"python"
] |
print current thread in python 3 | 39,286,610 | <p>I have this script:</p>
<pre><code>import threading, socket
for x in range(800)
send().start()
class send(threading.Thread):
def run(self):
while True:
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("www.google.it", 80))
... | 0 | 2016-09-02T07:25:36Z | 39,286,773 | <p>You could pass your counting number (<code>x</code>, in this case), as a variable in your send class. Keep in mind though that <code>x</code> will start at 0, not 1.</p>
<pre><code>for x in range(800)
send(x+1).start()
class send(threading.Thread):
def __init__(self, count):
self.count = count
... | 1 | 2016-09-02T07:33:36Z | [
"python",
"multithreading",
"sockets",
"python-3.x"
] |
print current thread in python 3 | 39,286,610 | <p>I have this script:</p>
<pre><code>import threading, socket
for x in range(800)
send().start()
class send(threading.Thread):
def run(self):
while True:
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("www.google.it", 80))
... | 0 | 2016-09-02T07:25:36Z | 39,286,792 | <p>The easiest way to do this is to use <code>setName</code> and <code>getName</code> to give names to your threads.</p>
<pre><code>import threading, socket
for x in range(800)
new_thread = send()
new_thread.setName("thread number %d" % x)
new_thread.start()
class send(threading.Thread):
def run(self... | 1 | 2016-09-02T07:34:44Z | [
"python",
"multithreading",
"sockets",
"python-3.x"
] |
GeoDjango distance query with srid 4326 returns 'SpatiaLite does not support distance queries on geometry fields with a geodetic coordinate system.' | 39,286,655 | <p>I'm trying to fetch nearby kitchens, within 4 km radius from a given lat/long.
My spatial backend is spatialite and settings are,</p>
<pre>
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django... | 1 | 2016-09-02T07:27:31Z | 39,332,764 | <p>Most likely your problem is the SRID. It seems like spatialite does not support this type of distance query on fields with unprojected coordinate systems.</p>
<p>So you are on the right track, but setting the srid to a different value will have no effect as long as you have <code>geography=True</code> enabled in yo... | 0 | 2016-09-05T14:28:56Z | [
"python",
"django",
"sqlite",
"geodjango",
"spatialite"
] |
How to avoid pickling errors when sharing objects between threads? | 39,286,665 | <p>I have a program in which I need to store a global variable into a file. I am doing this using the <code>pickle</code> module. </p>
<p>I have another <code>thread</code>(Daemon=<code>False</code>, from <code>threading</code> module) which sometimes changes the value of the global variable. The value is also modifie... | 0 | 2016-09-02T07:28:08Z | 39,306,303 | <p>As others have mentioned, you cannot pickle "volatile" entities (threads, connections, synchonization primitives etc.) because they don't make sense as persistent data.</p>
<p>Looks like what you're trying to do is be saving session variables for later continuation of said session. For that task, there's nothing yo... | 0 | 2016-09-03T11:17:47Z | [
"python",
"multithreading",
"pickle",
"locks"
] |
X.509 certificate serial number to hex conversion | 39,286,805 | <p>I'm trying to get the serial number for an X.509 certificate using Pythons OpenSSL library.</p>
<p>If I load my cert like this:</p>
<pre><code> x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_ASN1, cert)
</code></pre>
<p>Then print the serial number like this:</p>
<pre><code>print x509.get_serial_... | 2 | 2016-09-02T07:35:56Z | 39,292,733 | <pre><code>'%x' % cert.get_serial_number()
</code></pre>
<p><code>'%x' %</code> formats string like <code>'{0:x}'.format(cert.get_serial_number())</code></p>
| 0 | 2016-09-02T12:43:16Z | [
"python",
"pyopenssl"
] |
got frequency, need plot sinus wave in python | 39,286,859 | <p>I am just fighting with modulation of sinus wave.
I have got a frequency (from messured data - changing in time) and now I need to plot sinus wave with coresponding frequency.</p>
<p><img src="http://i.stack.imgur.com/MMfqh.png" alt="real data and sinus"></p>
<p>The blue line are just plotted points of real data a... | 0 | 2016-09-02T07:38:23Z | 39,295,119 | <p>You can try to match you function with something sine- or actually cosine-like, by extracting estimates for the frequency and the amplitude from your data. If I understood you correctly, your data are maximums and minimums and you want to have a trigonometric function that resembles that. If your data is saved in tw... | 0 | 2016-09-02T14:43:02Z | [
"python",
"sin",
"modulation"
] |
How to set only specific values for a parameter in docopt python? | 39,286,878 | <p>I am trying to use docopt for a python code. I actually need to set only specific values for a parameter. My usage is as below:</p>
<pre><code>"""
Usage:
test.py --list=(all|available)
Options:
list Choice to list devices (all / available)
"""
</code></pre>
<p>I've tried to run it as: <code>python test.py ... | 0 | 2016-09-02T07:39:06Z | 39,288,948 | <p>Here's an example to achieve what you want:</p>
<p><strong>test.py:</strong></p>
<pre><code>"""
Usage:
test.py list (all|available)
Options:
-h --help Show this screen.
--version Show version.
list Choice to list devices (all / available)
"""
from docopt import docopt
def list_devices(a... | 1 | 2016-09-02T09:26:48Z | [
"python",
"docopt"
] |
Model design for restaurant, meal and meal category | 39,286,917 | <p>I am planning to develop a food delivery app from local restaurants. I am thinking for the best design. I have designed a json too for modeling API.However i am confuse with menu part. Should meal be in the restaurant as a foreign key or restaurant be a foreignkey in the meal. </p>
<p>Simple concept of my app is </... | 0 | 2016-09-02T07:41:48Z | 39,287,050 | <p>Meal should has MealCategory as a ForeignKey. I think that Meal is a model which should be independent of restaurant. Think about add another model </p>
<pre><code>class RestaurantMeal(models.Model):
restaurant = models.ForeignKey(Restaurant)
meal = models.ForeignKey(Meal)
</code></pre>
<p>to store data a... | 0 | 2016-09-02T07:48:40Z | [
"python",
"json",
"django",
"api",
"django-models"
] |
Model design for restaurant, meal and meal category | 39,286,917 | <p>I am planning to develop a food delivery app from local restaurants. I am thinking for the best design. I have designed a json too for modeling API.However i am confuse with menu part. Should meal be in the restaurant as a foreign key or restaurant be a foreignkey in the meal. </p>
<p>Simple concept of my app is </... | 0 | 2016-09-02T07:41:48Z | 39,287,606 | <ol>
<li>Why do you have <code>restaurant = models.ForeignKey(User)</code> in <code>Meal</code> model when you should have <code>restaurant = models.ForeignKey('Restaurant')</code></li>
<li><code>MealCategory</code> should be independent, not belonging to <code>Meal</code>, on the contrary, <code>Meal</code> should bel... | 0 | 2016-09-02T08:21:16Z | [
"python",
"json",
"django",
"api",
"django-models"
] |
How to display a row based on specific columns and values | 39,287,534 | <p>Let's say I have this dataframe:</p>
<pre><code>Type | Killed
Dog 5
Cat 7
Dog 9
Dog 10
Dog 6
Cat 2
Cow 1
</code></pre>
<p>I would like to display the row where the number of dogs killed is more than 7.</p>
<p>My desired outcome woul... | -6 | 2016-09-02T08:17:25Z | 39,287,552 | <p>You can select within a column by:</p>
<pre><code>df.loc[(df['Killed'] > 7) & (df.index == 'Dog')]
</code></pre>
| 0 | 2016-09-02T08:18:13Z | [
"python",
"pandas"
] |
How to display a row based on specific columns and values | 39,287,534 | <p>Let's say I have this dataframe:</p>
<pre><code>Type | Killed
Dog 5
Cat 7
Dog 9
Dog 10
Dog 6
Cat 2
Cow 1
</code></pre>
<p>I would like to display the row where the number of dogs killed is more than 7.</p>
<p>My desired outcome woul... | -6 | 2016-09-02T08:17:25Z | 39,287,762 | <p>You can select data using:</p>
<pre><code>data[(data.Type == 'Dog') & (data.Killed > 7)]
</code></pre>
<p><strong>Example:</strong></p>
<pre><code>import pandas as pd
Type=['Dog','Cat','Dog','Dog','Dog','Cat','Cow']
Killed=[5,7,9,10,6,2,1]
dataset=zip(Type,Killed)
data=pd.DataFrame(dataset)
data.column... | 0 | 2016-09-02T08:29:37Z | [
"python",
"pandas"
] |
copy file with any extension | 39,287,542 | <p>I have only been attempting to code for a few days so please forgive me for any obvious mistakes that I make. I have searched around for a couple of days now and have not managed to find a solution to my problem, hence why I have decided to post here.</p>
<p>My issue: I have managed to create a piece of script wh... | 1 | 2016-09-02T08:17:44Z | 39,288,005 | <p>This is how i would start going about it. There are definitely things you have to be careful of like multiple files with same name and different extension, multiple dots in files and so on. I am pretty sure those two are taken into account by the script below. Take a look.</p>
<pre><code>import shutil
import os
imp... | 0 | 2016-09-02T08:41:56Z | [
"python",
"python-3.x"
] |
copy file with any extension | 39,287,542 | <p>I have only been attempting to code for a few days so please forgive me for any obvious mistakes that I make. I have searched around for a couple of days now and have not managed to find a solution to my problem, hence why I have decided to post here.</p>
<p>My issue: I have managed to create a piece of script wh... | 1 | 2016-09-02T08:17:44Z | 39,288,326 | <p>You need to make sure <code>FileName</code> either <em>equals</em> the file's name <em>or startswith</em> the file's name + a dot. Else you cannot exclude errors with possible files without extensions, or files with the same <em>partial</em> name.</p>
<p>Furthermore I'd suggest to use a conditional rather then <cod... | 0 | 2016-09-02T08:57:45Z | [
"python",
"python-3.x"
] |
Python Django REST call returning object number instead of object name | 39,287,577 | <p>I'm new to Python, and I guess I'm serializing it incorrectly.</p>
<p><strong>This is the REST call result:</strong>
<a href="http://i.stack.imgur.com/SXko7.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/SXko7.jpg" alt="enter image description here"></a></p>
<blockquote>
<p><strong>authors/models.py:</st... | 1 | 2016-09-02T08:19:29Z | 39,287,653 | <p>For Book model Author is just an id of that field in database, so that's why it's return an integer field.
Try to add an Author field in Book serializer</p>
<pre><code>class BookSerializer(serializers.ModelSerializer):
author = AuthorSerializer(read_only=True)
class Meta:
model = Book
field... | 1 | 2016-09-02T08:23:51Z | [
"python",
"django",
"django-rest-framework"
] |
Python Django REST call returning object number instead of object name | 39,287,577 | <p>I'm new to Python, and I guess I'm serializing it incorrectly.</p>
<p><strong>This is the REST call result:</strong>
<a href="http://i.stack.imgur.com/SXko7.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/SXko7.jpg" alt="enter image description here"></a></p>
<blockquote>
<p><strong>authors/models.py:</st... | 1 | 2016-09-02T08:19:29Z | 39,291,636 | <p>From my understanding you wish to get details of Authors in the api request not just their number??</p>
<p>The way to do that is to set the depth in your model serializer.</p>
<p><pre><code>
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = ('name', 'author')
... | 0 | 2016-09-02T11:45:21Z | [
"python",
"django",
"django-rest-framework"
] |
Unicode-escaped file processing error | 39,287,654 | <p>â Not quite. The post linked above contains the solution to a problem that showed up in the comments of this post while trying to solve it, and seems unrelated to the original problem.</p>
<p>I have a raw text file containing only the following line, and no newline:</p>
<pre><code>Q853 \u0410\u043D\u0434\u0440\u... | 5 | 2016-09-02T08:23:53Z | 39,289,924 | <p>It seems that the data read by the decoder is truncated at (after) character#72 (0-based character #71). That obviously is somehow related to the <a href="https://bugs.python.org/issue10344" rel="nofollow">this bug</a>.</p>
<p>The following code produces the same error as in your example:</p>
<pre><code>open("wiki... | 2 | 2016-09-02T10:14:17Z | [
"python",
"python-3.x",
"unicode",
"python-unicode"
] |
Handling ConnectionResetError | 39,287,669 | <p>I have a question on handling ConnectionResetError in Python3. This usually happens when I use the urllib.request.Request function. I would like to know if it is ok to redo the request if we come across such error. For example</p>
<pre><code>def get_html(url):
try:
request = Request(url)
respons... | 0 | 2016-09-02T08:24:42Z | 39,288,941 | <p>It really depends on the server, but you could do something like:</p>
<pre><code>def get_html(url, retry_count=0):
try:
request = Request(url)
response = urlopen(request)
html = response.read()
except ConectionResetError as e:
if retry_count == MAX_RETRIES:
raise ... | 0 | 2016-09-02T09:26:26Z | [
"python",
"urllib"
] |
How to specify property type when using Cloud Datastore API | 39,287,748 | <p>I have this python code snippet for adding a new entity from Google Compute Engine. But this code results in userId being created with an undefined type. How can I specify the type of the property when it is getting created from compute engine?</p>
<pre><code>kg = datastore.Entity(key)
try:
kg.update({
'userI... | 0 | 2016-09-02T08:28:45Z | 39,297,807 | <p><code>gloud-python</code> will infer the type of the property from the type of the value you place in the property map.</p>
<p><a href="https://github.com/GoogleCloudPlatform/gcloud-python/blob/master/gcloud/datastore/helpers.py#L303" rel="nofollow">https://github.com/GoogleCloudPlatform/gcloud-python/blob/master/g... | 2 | 2016-09-02T17:23:59Z | [
"python",
"google-cloud-datastore"
] |
Python - Counting blank lines in a text file | 39,287,853 | <p>Let's say I have a file with the following content(every even line is blank):<br></p>
<blockquote>
<p>Line 1 <br><br> Line 2 <br><br> Line 3 <br><br> ...</p>
</blockquote>
<p>I tried to read the file in 2 ways:<br></p>
<pre><code>count = 0
for line in open("myfile.txt"):
if line == '': #or ... | 1 | 2016-09-02T08:33:58Z | 39,288,023 | <p>When you use <code>readlines()</code> function, it doesn't automatically remove the EOL characters for you. So you either compare against the end of line, something like:</p>
<pre><code>if line == os.linesep:
count += 1
</code></pre>
<p>(you have to import <code>os</code> module of course), or you strip the li... | 2 | 2016-09-02T08:42:44Z | [
"python",
"file",
"lines"
] |
Python - Counting blank lines in a text file | 39,287,853 | <p>Let's say I have a file with the following content(every even line is blank):<br></p>
<blockquote>
<p>Line 1 <br><br> Line 2 <br><br> Line 3 <br><br> ...</p>
</blockquote>
<p>I tried to read the file in 2 ways:<br></p>
<pre><code>count = 0
for line in open("myfile.txt"):
if line == '': #or ... | 1 | 2016-09-02T08:33:58Z | 39,288,034 | <p>In a more simple and pythonic way:</p>
<pre><code>with open(filename) as fd:
count = sum(1 for line in fd if len(line.strip()) == 0)
</code></pre>
<p>This keep the linear complexity in time and a constant complexity in memory.
And, most of all, it get rid of the variable <code>count</code> as a manually increm... | 2 | 2016-09-02T08:43:21Z | [
"python",
"file",
"lines"
] |
Python - Counting blank lines in a text file | 39,287,853 | <p>Let's say I have a file with the following content(every even line is blank):<br></p>
<blockquote>
<p>Line 1 <br><br> Line 2 <br><br> Line 3 <br><br> ...</p>
</blockquote>
<p>I tried to read the file in 2 ways:<br></p>
<pre><code>count = 0
for line in open("myfile.txt"):
if line == '': #or ... | 1 | 2016-09-02T08:33:58Z | 39,288,038 | <p>Every line ends with a newline character <code>'\n'</code>. Note that it is only one character.</p>
<p>An easy workaround is to check wether the line equals <code>'\n'</code>, or wether its length is <strong>1</strong>, not 0.</p>
| 1 | 2016-09-02T08:43:45Z | [
"python",
"file",
"lines"
] |
Python - Counting blank lines in a text file | 39,287,853 | <p>Let's say I have a file with the following content(every even line is blank):<br></p>
<blockquote>
<p>Line 1 <br><br> Line 2 <br><br> Line 3 <br><br> ...</p>
</blockquote>
<p>I tried to read the file in 2 ways:<br></p>
<pre><code>count = 0
for line in open("myfile.txt"):
if line == '': #or ... | 1 | 2016-09-02T08:33:58Z | 39,288,348 | <p>You can use count from itertools, which returns iterator. Furthermore I used just strip instead of checking length.</p>
<pre><code>from itertools import count
counter = count()
with open('myfile.txt', 'r') as f:
for line in f.readlines():
if not line.strip():
counter.next()
print counter.... | 1 | 2016-09-02T08:58:46Z | [
"python",
"file",
"lines"
] |
Do not show certain fields in admin page | 39,287,991 | <p>In Django, you get the model editor for free in the <code>admin/</code> pages. This all works fine, but I have a few fields in my models that are generated and should never be touched by anybody through a form.</p>
<p>How can I exclude them from these <code>admin/.../change/</code> forms?</p>
<p>I added exclude to... | 1 | 2016-09-02T08:40:58Z | 39,288,158 | <blockquote>
<p>I have a few fields in my models that are
generated and should never be touched by anybody through a form.</p>
</blockquote>
<p>You may also use <a href="https://docs.djangoproject.com/en/1.10/ref/models/fields/#editable" rel="nofollow"><code>editable=False</code></a> on your model's field</p>
<bl... | 2 | 2016-09-02T08:50:20Z | [
"python",
"django"
] |
Do not show certain fields in admin page | 39,287,991 | <p>In Django, you get the model editor for free in the <code>admin/</code> pages. This all works fine, but I have a few fields in my models that are generated and should never be touched by anybody through a form.</p>
<p>How can I exclude them from these <code>admin/.../change/</code> forms?</p>
<p>I added exclude to... | 1 | 2016-09-02T08:40:58Z | 39,288,182 | <p>You have to <code>register</code> your <code>exampleAdmin</code> to take effect. In your <code>admin.py</code> add <code>admin.site.register(example, exampleAdmin)</code></p>
| 3 | 2016-09-02T08:51:22Z | [
"python",
"django"
] |
Convert date/time columns in Pandas dataframe | 39,288,013 | <p>I have data sets containing the date (Julian day, column 1), hour (HHMM, column 2) and seconds (column 3) in individual columns:</p>
<pre><code>1 253 2300 0 2.9 114.4 18.42 21.17
1 253 2300 10 3.27 111.2 18.48 21.12
1 253 2300 20 3.22 111.3 18.49 21.09
1 253 2300 30 3.84 106.4 18.52... | 5 | 2016-09-02T08:42:18Z | 39,288,643 | <p>Would something along these lines work? : </p>
<pre><code>def merge_date(df, year='Year', month='Month', day='Day', hours='Hours', seconds='Seconds'):
"""
* Function: merge_date
* Usage: merge_date(DataFrame, col_year, col_month, col_day) . . .
* -------------------------------
* This function ... | 1 | 2016-09-02T09:12:32Z | [
"python",
"pandas"
] |
Convert date/time columns in Pandas dataframe | 39,288,013 | <p>I have data sets containing the date (Julian day, column 1), hour (HHMM, column 2) and seconds (column 3) in individual columns:</p>
<pre><code>1 253 2300 0 2.9 114.4 18.42 21.17
1 253 2300 10 3.27 111.2 18.48 21.12
1 253 2300 20 3.22 111.3 18.49 21.09
1 253 2300 30 3.84 106.4 18.52... | 5 | 2016-09-02T08:42:18Z | 39,288,736 | <p>Not sure if I am missing something but this seems to work:</p>
<pre><code>import pandas as pd
import datetime
from io import StringIO
data_file = StringIO("""\
1 253 2300 0 2.9 114.4 18.42 21.17
1 253 2300 10 3.27 111.2 18.48 21.12
1 253 2300 20 3.22 111.3 18.49 21.09
1 253 2300 30... | 2 | 2016-09-02T09:16:43Z | [
"python",
"pandas"
] |
modify list elements on a condition | 39,288,021 | <p>I am new to Python but have C/C++ background.
I am trying to modify a 2D list (list of lists) elements that satisfy a condition.
All I could come up with is the following solution:</p>
<pre><code>tsdata = [[random.random() for x in range(5)] for y in range(5)]
def check(tsdata):
for i in range(len(tsdata)):
... | 0 | 2016-09-02T08:42:40Z | 39,288,170 | <p>Welcome to the world of simplicity and compact statements.</p>
<pre><code>tsdata_mod = [[0 if (x < min_value or x > max_value) else x for x in y] for y in tsdata]
</code></pre>
<p>or in function mode:</p>
<pre><code>def check(my_list):
my_list_mod = [[0 if (x < min_value or x > max_value) else x f... | 0 | 2016-09-02T08:50:51Z | [
"python",
"list"
] |
modify list elements on a condition | 39,288,021 | <p>I am new to Python but have C/C++ background.
I am trying to modify a 2D list (list of lists) elements that satisfy a condition.
All I could come up with is the following solution:</p>
<pre><code>tsdata = [[random.random() for x in range(5)] for y in range(5)]
def check(tsdata):
for i in range(len(tsdata)):
... | 0 | 2016-09-02T08:42:40Z | 39,288,192 | <p>Your solution is not bad, but the following could be more simpler to understand. (depends of how your code should evolve later)</p>
<pre><code>def new_value(value):
"""Encapsulation of the core treatment"""
return 0 if (value < min_value) or (value > max_value) else value
new_tsdata = [[new_value(val... | 0 | 2016-09-02T08:51:43Z | [
"python",
"list"
] |
modify list elements on a condition | 39,288,021 | <p>I am new to Python but have C/C++ background.
I am trying to modify a 2D list (list of lists) elements that satisfy a condition.
All I could come up with is the following solution:</p>
<pre><code>tsdata = [[random.random() for x in range(5)] for y in range(5)]
def check(tsdata):
for i in range(len(tsdata)):
... | 0 | 2016-09-02T08:42:40Z | 39,288,279 | <p>If you want to handle big arrays, you may want to use <code>numpy</code>. Besides being much more efficient, I think the code is easier to read:</p>
<pre><code>from numpy import random
tsdata = random.random((5, 5))
tsdata[tsdata < min_value] = 0
tsdata[tsdata > max_value] = 0
</code></pre>
| 2 | 2016-09-02T08:55:41Z | [
"python",
"list"
] |
How to set proxy while using urllib3.PoolManager in python | 39,288,168 | <p>I am currently using connection pool provided by urllib3 in python like the following,</p>
<pre><code>pool = urllib3.PoolManager(maxsize = 10)
resp = pool.request('GET', 'http://example.com')
content = resp.read()
resp.release_conn()
</code></pre>
<p>However, I don't know how to set proxy while using this connecti... | 0 | 2016-09-02T08:50:43Z | 39,294,281 | <p>There is an example for how to use a proxy with urllib3 in the <a href="https://urllib3.readthedocs.io/en/latest/advanced-usage.html#proxies" rel="nofollow">Advanced Usage section of the documentation</a>. I adapted it to fit your example:</p>
<pre><code>import urllib3
proxy = urllib3.ProxyManager('http://123.123.1... | 0 | 2016-09-02T14:01:08Z | [
"python",
"proxy",
"connection-pooling",
"urllib3"
] |
How to plot data from multiple files in a loop using matplotlib in python? | 39,288,210 | <p>I have a more than 1000 files which are .CSV (data_1.csv......data1000.csv), each containing X and Y values !</p>
<pre><code>x1 y1 x2 y2
5.0 60 5.5 500
6.0 70 6.5 600
7.0 80 7.5 700
8.0 90 8.5 800
9.0 100 9.5 900
</code></pre>
<hr>
<p>I have made a subplot program in python which can give two plots (plot1... | 0 | 2016-09-02T08:52:42Z | 39,288,386 | <p>You can generate a list of filenames using <code>glob</code> and then plot them in a for loop.</p>
<pre><code>import glob
import matplotlib.pyplot as plt
files = glob.glob(# file pattern something like '*.csv')
for file in files:
df1=pd.read_csv(file,header=1,sep=',')
fig = plt.figure()
plt.subplot(2,... | 2 | 2016-09-02T09:00:31Z | [
"python",
"loops",
"csv",
"matplotlib",
"plot"
] |
How to plot data from multiple files in a loop using matplotlib in python? | 39,288,210 | <p>I have a more than 1000 files which are .CSV (data_1.csv......data1000.csv), each containing X and Y values !</p>
<pre><code>x1 y1 x2 y2
5.0 60 5.5 500
6.0 70 6.5 600
7.0 80 7.5 700
8.0 90 8.5 800
9.0 100 9.5 900
</code></pre>
<hr>
<p>I have made a subplot program in python which can give two plots (plot1... | 0 | 2016-09-02T08:52:42Z | 39,371,508 | <p>Here is the basic setup for what am using here at work. This code will plot the data from each file and through each file separately. This will work on any number of files as long as column names remain the same. Just direct it to the proper folder.</p>
<pre><code>import os
import csv
def graphWriterIRIandRut():
... | 0 | 2016-09-07T13:39:56Z | [
"python",
"loops",
"csv",
"matplotlib",
"plot"
] |
How to plot data from multiple files in a loop using matplotlib in python? | 39,288,210 | <p>I have a more than 1000 files which are .CSV (data_1.csv......data1000.csv), each containing X and Y values !</p>
<pre><code>x1 y1 x2 y2
5.0 60 5.5 500
6.0 70 6.5 600
7.0 80 7.5 700
8.0 90 8.5 800
9.0 100 9.5 900
</code></pre>
<hr>
<p>I have made a subplot program in python which can give two plots (plot1... | 0 | 2016-09-02T08:52:42Z | 39,527,344 | <pre><code># plotting all the file data and saving the plots
import os
import csv
import matplotlib.pyplot as plt
def graphWriterIRIandRut():
m = 0
List1 = []
List2 = []
List3 = []
List4 = []
fileList = []
for file in os.listdir(os.getcwd()):
fileList.append(file)
while m < ... | 0 | 2016-09-16T08:52:06Z | [
"python",
"loops",
"csv",
"matplotlib",
"plot"
] |
How to collect a record by a parameter python | 39,288,333 | <p>Python source :</p>
<pre><code>@app.route('/pret/<int:idPret>', methods=['GET'])
def descrire_un_pret(idPret):
j = 0
for j in prets:
if prets[j]['id'] == idPret:
reponse = make_response(json.dumps(prets[j],200))
reponse.headers = {"Content-Type": "application/json"}
... | -2 | 2016-09-02T08:58:05Z | 39,288,394 | <p><code>j</code> is not a number. <code>j</code> is one element in the <code>prets</code> list. Python loops are foreach loops. <code>if j['id'] == idPret:</code> would work:</p>
<pre><code>for j in prets:
if j['id'] == idPret:
reponse = make_response(json.dumps(j, 200))
reponse.headers = {"Conten... | 0 | 2016-09-02T09:00:55Z | [
"python",
"flask"
] |
How to collect a record by a parameter python | 39,288,333 | <p>Python source :</p>
<pre><code>@app.route('/pret/<int:idPret>', methods=['GET'])
def descrire_un_pret(idPret):
j = 0
for j in prets:
if prets[j]['id'] == idPret:
reponse = make_response(json.dumps(prets[j],200))
reponse.headers = {"Content-Type": "application/json"}
... | -2 | 2016-09-02T08:58:05Z | 39,288,414 | <p>You are mistaking Python's for behavior for Javascript's. When you do
<code>for j in prets:</code> in Python, the contents of <code>j</code> are already the elements in <code>pretz</code>, not an index number.</p>
| 0 | 2016-09-02T09:02:11Z | [
"python",
"flask"
] |
Time series prediction with LSTM using Keras: Wrong number of dimensions: expected 3, got 2 with shape | 39,288,341 | <p>I am trying to predict the next value in the time series using the previous 20 values. Here is a sample from my code:</p>
<p><code>X_train.shape</code> is <code>(15015, 20)</code></p>
<p><code>Y_train.shape</code> is <code>(15015,)</code></p>
<pre><code>EMB_SIZE = 1
HIDDEN_RNN = 3
model = Sequential()
model.add(... | 0 | 2016-09-02T08:58:19Z | 39,289,342 | <p>If I understand your problem correctly, your input data a set of 15015 1D sequences of length 20. According to Keras doc, the input is a 3D tensor with shape (nb_samples, timesteps, input_dim). In your case, the shape of <code>X</code> should then be <code>(15015, 20, 1)</code>.</p>
<p>Also, you just need to give <... | 0 | 2016-09-02T09:44:48Z | [
"python",
"machine-learning",
"time-series",
"keras"
] |
Celery flower doesn't work under supervisor managment | 39,288,354 | <p>I have Ubuntu 14.04.4 LTS running as a vagrant environment under virtualbox. In this box I have this configuration:</p>
<ul>
<li><p>supervisor 3.0b2</p></li>
<li><p>python 3.4 under virtualenvironment</p></li>
<li><p>celery 3.1.23</p></li>
<li><p>flower 0.9.1</p></li>
</ul>
<p>A flower configuration under supervis... | 1 | 2016-09-02T08:59:05Z | 39,455,788 | <p>I have found a solution.
The problem was that I ran flower not under my virtual environment. I added a shell file "start_flower.sh":</p>
<pre><code>source /usr/share/virtualenvwrapper/virtualenvwrapper.sh
source /home/vagrant/.virtualenvs/meridian/bin/activate
workon meridian
exec flower --conf=/vagrant/meridian/m... | 0 | 2016-09-12T17:38:06Z | [
"python",
"celery",
"supervisord",
"flower"
] |
Reading several lines in a .csv file | 39,288,464 | <p>I want to read several lines of an CSV file. I am opening a list and append the one row to the list. Then I try to print the list. But the list is empty. The CSV file looks as following:</p>
<pre><code>`hallo;das;ist;ein;test;der;hoffentlich;funktioniert;fingerscrossed;
hallo;das;ist;ein;test;der;hoffentlich;funkti... | 0 | 2016-09-02T09:04:48Z | 39,288,673 | <p>The following works.
Remind, iterating over the data in the line <code>anzahl_zeilen ...</code> makes it impossible to iterate again over your data.</p>
<p>2nd thing. <code>if spamreader.line_num > 9 and spamreader.line_num < anzahl_zeilen:</code> does neither really check the columns in the row nor if you're... | 0 | 2016-09-02T09:13:45Z | [
"python",
"python-3.x",
"csv"
] |
Reading several lines in a .csv file | 39,288,464 | <p>I want to read several lines of an CSV file. I am opening a list and append the one row to the list. Then I try to print the list. But the list is empty. The CSV file looks as following:</p>
<pre><code>`hallo;das;ist;ein;test;der;hoffentlich;funktioniert;fingerscrossed;
hallo;das;ist;ein;test;der;hoffentlich;funkti... | 0 | 2016-09-02T09:04:48Z | 39,288,697 | <p>The problem with your code is that you are iterating over the spamreader twice. You can only do that once.</p>
<p>this statement will result in the correct answer.</p>
<pre><code>anzahl_zeilen = sum(1 for row in spamreader)
</code></pre>
<p>but when you now iterate over the same spamreader you'll get empty list, ... | 0 | 2016-09-02T09:15:04Z | [
"python",
"python-3.x",
"csv"
] |
Reading several lines in a .csv file | 39,288,464 | <p>I want to read several lines of an CSV file. I am opening a list and append the one row to the list. Then I try to print the list. But the list is empty. The CSV file looks as following:</p>
<pre><code>`hallo;das;ist;ein;test;der;hoffentlich;funktioniert;fingerscrossed;
hallo;das;ist;ein;test;der;hoffentlich;funkti... | 0 | 2016-09-02T09:04:48Z | 39,290,326 | <pre><code># try this code its very simple
input:
filename :samp1.csv
c1;c2;c3;c4;c5;c6;c7;c8;c9;
hallo;das;ist;ein;test;der;hoffentlich;funktioniert;fingerscrossed;
hallo;das;ist;ein;test;der;hoffentlich;funktioniert1;fingerscrossed;
hallo;das;ist;ein;test;der;hoffentlich;funktioniert2;fingerscrossed;
hallo;das;ist;ei... | 0 | 2016-09-02T10:35:50Z | [
"python",
"python-3.x",
"csv"
] |
sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) UNIQUE constraint failed: users.login | 39,288,538 | <p>I am using sqlite database and I declare the model as this:</p>
<pre><code>class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
login = db.Column(db.String(80), unique=True)
password = db.Column(db.String(64))
def is_authenticated(self):
return True... | 0 | 2016-09-02T09:08:47Z | 39,288,623 | <p>You can just run query, let's say:</p>
<pre><code>db.session.query(User).delete()
db.session.commit()
</code></pre>
<p>OR</p>
<pre><code>User.query.delete()
db.session.commit()
</code></pre>
<p>in that case, you will just remove everything from User table.</p>
| 0 | 2016-09-02T09:11:41Z | [
"python",
"sqlite",
"flask-sqlalchemy"
] |
sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) UNIQUE constraint failed: users.login | 39,288,538 | <p>I am using sqlite database and I declare the model as this:</p>
<pre><code>class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
login = db.Column(db.String(80), unique=True)
password = db.Column(db.String(64))
def is_authenticated(self):
return True... | 0 | 2016-09-02T09:08:47Z | 39,288,652 | <p>You're comparing the count to <code><= 1</code>.
So you'll attempt to create the new user even though it already exists.
So it should probably simply be <code>< 1</code>:</p>
<pre><code>if db.session.query(User).filter_by(login='passport').count() < 1:
user = User(login = 'passport', password = 'passwo... | 1 | 2016-09-02T09:13:01Z | [
"python",
"sqlite",
"flask-sqlalchemy"
] |
How can I set infinity as an element of a matrix in python(numpy)? | 39,288,580 | <p>This is the program</p>
<pre><code>import numpy as n
m = complex('inf')
z=n.empty([2,2] , dtype = complex)
z=n.array(input() , dtype = complex )
</code></pre>
<p>but in the console when i give 'm' as an input i get the following error massage:
'NameError: name 'm' is not defined'</p>
| 0 | 2016-09-02T09:10:22Z | 39,289,147 | <p>Infinity in python can be typed as:</p>
<p>float('inf') / float('-inf')</p>
<p>or simply as a number</p>
<p>1e500 (+inf)</p>
<p>-1e500 (-inf)</p>
| 0 | 2016-09-02T09:35:32Z | [
"python",
"numpy",
"user-input",
"infinity"
] |
putting int/float from file into a dictionary | 39,288,627 | <p>I like to put some values from a csv file into a dict. An example is:</p>
<pre><code>TYPE, Weldline
Diam, 5.0
Num of Elems, 4
</code></pre>
<p>and I end up after reading into a dictionary (for later use in an API) in:</p>
<pre><code> {'TYPE':'Weldline' , 'Diam':'5.0','Num of Elems':'4'}
</code></pre>
<p>Since ... | 0 | 2016-09-02T09:11:44Z | 39,288,862 | <p>You can use <code>literal_eval</code></p>
<blockquote>
<p>This can be used for safely evaluating strings containing Python values from untrusted sources without the need to parse the values oneself. It is not capable of evaluating arbitrarily complex expressions, for example involving operators or indexing.</p>
<... | 1 | 2016-09-02T09:22:28Z | [
"python",
"type-conversion"
] |
putting int/float from file into a dictionary | 39,288,627 | <p>I like to put some values from a csv file into a dict. An example is:</p>
<pre><code>TYPE, Weldline
Diam, 5.0
Num of Elems, 4
</code></pre>
<p>and I end up after reading into a dictionary (for later use in an API) in:</p>
<pre><code> {'TYPE':'Weldline' , 'Diam':'5.0','Num of Elems':'4'}
</code></pre>
<p>Since ... | 0 | 2016-09-02T09:11:44Z | 39,289,098 | <p>Also try this it seems more simple.</p>
<pre><code>import csv,ast
with open('file.csv', mode='r') as file:
reader = csv.reader(file)
mydict = {rows[0]:ast.literal_eval(rows[1]) for rows in reader}
print mydict
</code></pre>
| 0 | 2016-09-02T09:33:30Z | [
"python",
"type-conversion"
] |
putting int/float from file into a dictionary | 39,288,627 | <p>I like to put some values from a csv file into a dict. An example is:</p>
<pre><code>TYPE, Weldline
Diam, 5.0
Num of Elems, 4
</code></pre>
<p>and I end up after reading into a dictionary (for later use in an API) in:</p>
<pre><code> {'TYPE':'Weldline' , 'Diam':'5.0','Num of Elems':'4'}
</code></pre>
<p>Since ... | 0 | 2016-09-02T09:11:44Z | 39,292,792 | <p>Now I tried this:</p>
<pre><code> key = Line[0].strip()
value = Line[1].strip()
try:
value = int(Line[1].strip())
except ValueError:
try:
value = float(Line[1].strip())
... | 0 | 2016-09-02T12:46:22Z | [
"python",
"type-conversion"
] |
jinja2 load template from string: TypeError: no loader for this environment specified | 39,288,706 | <p>I'm using Jinja2 in Flask. I want to render a template from a string. I tried the following 2 methods:</p>
<pre><code> rtemplate = jinja2.Environment().from_string(myString)
data = rtemplate.render(**data)
</code></pre>
<p>and</p>
<pre><code> rtemplate = jinja2.Template(myString)
data = rtemplate.render(**data)... | 0 | 2016-09-02T09:15:29Z | 39,288,845 | <p>You can provide <code>loader</code> in <code>Environment</code> from <a href="http://jinja.pocoo.org/docs/dev/api/#loaders" rel="nofollow">that list</a></p>
<pre><code>from jinja2 import Environment, BaseLoader
rtemplate = Environment(loader=BaseLoader).from_string(myString)
data = rtemplate.render(**data)
</code>... | 1 | 2016-09-02T09:21:46Z | [
"python",
"flask",
"jinja2"
] |
Convert bash script to python | 39,288,950 | <p>I have a bash script and i want to convert it to python.</p>
<p>This is the script :</p>
<pre><code>mv $1/positive/*.$3 $2/JPEGImages
mv $1/negative/*.$3 $2/JPEGImages
mv $1/positive/annotations/*.xml $2/Annotations
mv $1/negative/annotations/*.xml $2/Annotations
cut -d' ' -f1 $1/positive_label.txt > $4_trainva... | 1 | 2016-09-02T09:26:53Z | 39,326,308 | <p>Without testing, something like that should works.</p>
<pre><code>#cut -d' ' -f1 $1/positive_label.txt > $4_trainval.txt
positive = path1+'/positive_label.txt'
path4 = os.path.join(arg4, '_trainval.txt')
with open(positive, 'r') as input_, open(path4, 'w') as output_:
for line in input_.readlines():
... | 0 | 2016-09-05T08:10:37Z | [
"python",
"bash"
] |
Create a new list from two dictionaries (case insensitive) | 39,288,989 | <p>This is a question about Python. I have the following list of dictionaries:</p>
<pre><code>listA = [
{"t": 1, "tid": 2, "gtm": "Goofy", "c1": 4, "id": "111"},
{"t": 3, "tid": 4, "gtm": "goofy", "c1": 4, "c2": 5, "id": "222"},
{"t": 1, "tid": 2, "gtm": "GooFy", "c1": 4, "c2": 5, "id": "... | 1 | 2016-09-02T09:28:25Z | 39,289,055 | <p>You'd have to test each dictionary value manually:</p>
<pre><code>def test(d1, d2):
"""Test if all values for d1 match case-insensitively in d2"""
def equal(v1, v2):
try:
return v1.lower() == v2.lower()
except AttributeError:
# not an object that supports .lower()
... | 3 | 2016-09-02T09:31:43Z | [
"python",
"dictionary"
] |
Value of settings.DEBUG changing between settings and url in Django Test | 39,289,064 | <p>I'm trying to set up test for some URLS that are set only in debug. They are not set because apparently the value of DEBUG change to False between my setting file and urls.py. I've never encountered this problem before, and I don't remember doing anything particularly fancy involving DEBUG value.</p>
<p>Here's my u... | 0 | 2016-09-02T09:32:04Z | 39,289,472 | <p>From the <a href="https://docs.djangoproject.com/en/1.10/topics/testing/overview/#other-test-conditions" rel="nofollow">docs</a></p>
<blockquote>
<p>Regardless of the value of the DEBUG setting in your configuration file, all Django tests run with DEBUG=False. This is to ensure that the observed output of your co... | 2 | 2016-09-02T09:51:15Z | [
"python",
"django",
"testing"
] |
Value of settings.DEBUG changing between settings and url in Django Test | 39,289,064 | <p>I'm trying to set up test for some URLS that are set only in debug. They are not set because apparently the value of DEBUG change to False between my setting file and urls.py. I've never encountered this problem before, and I don't remember doing anything particularly fancy involving DEBUG value.</p>
<p>Here's my u... | 0 | 2016-09-02T09:32:04Z | 39,289,679 | <p>The problem with your code is you are setting DEBUG = True after this line</p>
<pre><code> urlpatterns += [url(r'^dnfp/$', dnfp, name="debug_not_found_page"
</code></pre>
<p>The reason is that all the URLs are already appended to urlpatterns[] and you are setting it after the appending of URLs and while appendin... | 1 | 2016-09-02T10:02:10Z | [
"python",
"django",
"testing"
] |
how to empty json file before dumping data into it | 39,289,070 | <p><strong>python 3.5</strong></p>
<p>hi i have following codes to add an element to json data :</p>
<pre><code>jsonFile = open("json.json", mode="r+", encoding='utf-8')
jdata = json.load(jsonFile)
jdata['chat_text'].insert(0, {'x':'x'})
json.dump(jdata, jsonFile)
jsonFile.close()
</code></pre>
<p>but it would be re... | 2 | 2016-09-02T09:32:28Z | 39,289,364 | <p>the issue is essentially that you are opening the file twice in different modes.</p>
<pre><code>jsonFile = open("json.json", mode="r")
jdata = json.load(jsonFile)
jsonFile.close()
jdata['chat_text'].insert(0, {'x':'x'})
jsonFile = open('json.json', mode='w+')
json.dump(jdata, jsonFile)
jsonFile.close()
</code></pre... | 1 | 2016-09-02T09:45:55Z | [
"python",
"json"
] |
how to get href link from onclick function in python | 39,289,206 | <p>I want to get href link of website form onclick function
Here is html code in which onclick function call a website </p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>... | 0 | 2016-09-02T09:38:07Z | 39,290,184 | <p>You cannot directly parse <code>aHref</code> attribute, you need to extract <code>onclick</code> first.</p>
<pre><code>>>> import re
>>> data = soup.select('.taLnk')[0].get('onclick')
>>> href = re.search(r"(?is)'aHref':'(.*?)'",str(data)).group(1)
'LqMWJQzZYUWJQpEcYGII26XombQQoqnQQQQoqnq... | 0 | 2016-09-02T10:28:22Z | [
"python",
"html",
"python-3.x",
"beautifulsoup"
] |
how to get href link from onclick function in python | 39,289,206 | <p>I want to get href link of website form onclick function
Here is html code in which onclick function call a website </p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>... | 0 | 2016-09-02T09:38:07Z | 39,290,286 | <p>You can use a regex with bs4, selecting the span with the class taLnk and the <em>onclick</em> attribute starting with <em>ta.trackEventOnPage</em>:</p>
<pre><code>h = """<div class="fl">
<span class="taLnk" onclick="ta.trackEventOnPage('Eatery_Listing', 'Website', 594024, 1); ta.util.cookie.setPIDCookie... | 0 | 2016-09-02T10:33:47Z | [
"python",
"html",
"python-3.x",
"beautifulsoup"
] |
What does this numpy code snippet do? | 39,289,241 | <pre><code>float(multiply(colVec1,colVec2).T * (matrix*matrix[i,:].T)) + c
</code></pre>
<p>I am new to Python and numpy and I am trying to understand what the code snippet above does. </p>
<p>The <code>multiply().T</code> part performs an element-by-element multiplication and then does a transpose, and so the resul... | 0 | 2016-09-02T09:39:45Z | 39,289,407 | <p>Yes, <code>matrix[i, :]</code> will give you the i:th <strong>row</strong> of <code>matrix</code> since the <code>:</code> means "pick all in this dimension".</p>
<p>And no, <code>A * B</code> is not the dot product between <code>A</code> and <code>B</code>, it is the <strong>element-wise product</strong> of <code>... | 1 | 2016-09-02T09:48:31Z | [
"python",
"numpy",
"matrix"
] |
How to create a Image Dataset just like MNIST dataset? | 39,289,285 | <p>I have 10000 BMP images of some handwritten digits. If i want to feed the datas to a neural network what do i need to do ? For MNIST dataset i just had to write</p>
<pre><code>(X_train, y_train), (X_test, y_test) = mnist.load_data()
</code></pre>
<p>I am using Keras library in python . How can i create such datase... | 0 | 2016-09-02T09:42:25Z | 39,291,033 | <p>You can either write a function that loads all your images and stack them into a numpy array if all fits in RAM or use Keras ImageDataGenerator (<a href="https://keras.io/preprocessing/image/" rel="nofollow">https://keras.io/preprocessing/image/</a>) which includes a function <code>flow_from_directory</code>. You ca... | 2 | 2016-09-02T11:15:12Z | [
"python",
"image-processing",
"dataset",
"neural-network",
"keras"
] |
Having trouble to understand the output in a Jupyter notebook ("Learning Cython") | 39,289,340 | <p>In the O'Reilly video tutorial "Learning Cython" in chapter 5, there's a notebook called <code>strings.ipynb</code>.</p>
<p>First cell loads the Cython extension:</p>
<pre><code>%load_ext cython
</code></pre>
<p>Followed by this Cython cell:</p>
<pre><code>%%cython
# cython: language_level=3
def f(char* text):
... | 1 | 2016-09-02T09:44:42Z | 39,289,706 | <p>Because it was. In Python 3, <code>bytes_str</code> uses <a href="https://github.com/python/cpython/blob/master/Objects/bytesobject.c#L1370" rel="nofollow"><code>bytes_repr</code> internally</a>:</p>
<pre><code>static PyObject *
bytes_str(PyObject *op)
{
if (Py_BytesWarningFlag) {
if (PyErr_WarnEx(PyExc... | 1 | 2016-09-02T10:03:36Z | [
"python",
"python-3.x",
"cython",
"jupyter-notebook"
] |
Python PyAudio, output little cracky. Maybe math | 39,289,375 | <p>Good day. I have a small problem that may be partly math.</p>
<p>The thing is I want to play Sine wave without fixed frequency. Therefore, not to make the sound cracky between transitions or during fixed frequency i need the sine wave to start and to end with amplitude zero. Mathematicly I understand what has to be... | 1 | 2016-09-02T09:46:23Z | 39,424,253 | <p>The sine function repeats itself every multiple of <code>2*pi*N</code> where N is a whole number. IOW, <code>sin(2*pi) == sin(2*pi*2) == sin(2*pi*3)</code> and so on. </p>
<p>The typical method for generating samples of a particular frequency is <code>sin(2*pi*i*freq/sampleRate)</code> where <code>i</code> is the s... | 0 | 2016-09-10T08:38:19Z | [
"python",
"audio",
"wave",
"pyaudio",
"sine"
] |
Pandas: Get the only value of a series or nan if it does not exist | 39,289,387 | <p>I'm doing a bit more complex operation on a dataframe where I compare two rows which can be anywhere in the frame.</p>
<p>Here's an example:</p>
<pre><code>import pandas as pd
import numpy as np
D = {'A':['a','a','c','e','e','b','b'],'B':['c','f','a','b','d','a','e']\
,'AW':[1,2,3,4,5,6,7],'BW':[10,20,30,40,50,6... | 6 | 2016-09-02T09:47:03Z | 39,291,792 | <p>Credit goes to <a href="https://stackoverflow.com/users/2336654/pirsquared">piRSquared</a> for pointing me into the right direction for the solution:</p>
<pre><code>AB = P.AB.str.split('_', expand=True)
AB = AB.merge(AB, left_on=[0, 1], right_on=[1, 0],how='inner')[[0,1]]
AB = AB.merge(P,left_on=[0,1], right_on=['A... | 2 | 2016-09-02T11:53:39Z | [
"python",
"pandas"
] |
python matplotlib plot table with multiple headers | 39,289,483 | <p>I can plot my single-header dataframe on a figure with this code:</p>
<pre><code>plt.table(cellText=df.round(4).values, cellLoc='center', bbox=[0.225, 1, 0.7, 0.15],
rowLabels=[' {} '.format(i) for i in df.index], rowLoc='center',
rowColours=['silver']*len(df.index), colLabels=df.columns, colLoc='center',... | 2 | 2016-09-02T09:51:57Z | 39,291,805 | <p>OK, I used a "trick" to solve this problem: plot a new table with only one cell, without column header and without row index. The only cell value is the original top header. And place this new table on the top of the old (single-header) table. (It is not the best solution but works...).</p>
<p>The code:</p>
<pre><... | 1 | 2016-09-02T11:54:08Z | [
"python",
"matplotlib",
"multi-index"
] |
Calling Python Eve from an Flask application leads to weird errors | 39,289,552 | <p>I've created an Eve API which is being called from an Flask Application using SSL protected traffic.
The application itself should be working nevertheless an error occurs when Eve tries to handle the incoming requests. </p>
<pre><code>Eve==0.6.4
Flask==0.10.1
Traceback (most recent call last):
File "/home/use... | 0 | 2016-09-02T09:55:03Z | 39,289,553 | <p>At least in this case it was in incompatibility between the libraries, no idea why.
Upgrade Eve and Flask via pip (<code>pip install --upgrade flask</code> and <code>pip install --upgrade eve</code>) and it works again. </p>
| 0 | 2016-09-02T09:55:03Z | [
"python",
"flask",
"eve"
] |
Print Name in Text File using python Regular expression | 39,289,581 | <p>I am looking for a name in a text file using python Regular expression.
Example: If I have a Name in the format like Brad Pitt or BRAD PITT in first 10 lines I want to print the name.
I am using the following code.</p>
<pre><code>import re
import sys
name=[sys.argv[1]]
for line in name:
n=re.match("([A-Z]\... | 0 | 2016-09-02T09:56:24Z | 39,290,417 | <p>Test this <a href="https://repl.it/DKaJ" rel="nofollow">one</a></p>
<pre><code>import re
import sys
# template content : TODO load from file or program args
name="Bratt PITT\nYour Name\nSimpleName\nWrong5Name\nThis is a Too complex Name"
for line in name.splitlines():
n = re.match("^([A-Za-z\s]+)+$", line)
... | 0 | 2016-09-02T10:41:25Z | [
"python"
] |
How to get the column names of a DataFrame GroupBy object? | 39,289,611 | <p>How can I get the column names of a GroupBy object? The object does not supply a columns propertiy. I can aggregate the object first or extract a DataFrame with the get_group()-method but this is either a power consuming hack or error prone if there are dismissed columns (strings for example).</p>
| 0 | 2016-09-02T09:58:38Z | 39,289,936 | <p>Looking at the source code of <code>__getitem__</code>, it seems that you can get the column names with</p>
<pre><code>g.obj.columns
</code></pre>
<p>where g is the groupby object. Apparently <code>g.obj</code> links to the DataFrame.</p>
| 2 | 2016-09-02T10:14:55Z | [
"python",
"pandas"
] |
Execute command inside loop only upon status change | 39,289,625 | <p>I'm looking for a smooth (and if possible pythonic) way of executing something inside a while True loop only once per status change, and then if something changes it should print out the new change once rather than spam the console with whatever the current value is.</p>
<p>My general code:</p>
<pre><code>def func... | 0 | 2016-09-02T09:59:20Z | 39,289,916 | <p>I would put all the tasks into a dictionary, then you can simply track the previous status and only execute a new task when a new status has been reached, something like this:</p>
<pre><code>from time import sleep
tasks = {1:do_something,
2:do_something_else}
prev_status = None
while True:
status = c... | 1 | 2016-09-02T10:13:54Z | [
"python",
"python-2.7",
"loops"
] |
call python code of different git branch other than the current repository without switching branch | 39,289,867 | <p>So, basically I have 2 versions of a project and for some users, I want to use the latest version while for others, I want to use older version. Both of them have same file names and multiple users will use it simultaneously. To accomplish this, I want to call function from different git branch without actually swit... | -1 | 2016-09-02T10:11:34Z | 39,290,774 | <p>Without commenting on <em>why</em> you need to do that, you can simply checkout your repo twice: once for branch1, and one for branch2 (without cloning twice).<br>
See "<a href="http://stackoverflow.com/a/30186843/6309">git working on two branches simultaneously</a>".</p>
<p>You can then make your script aware of i... | 1 | 2016-09-02T10:59:57Z | [
"python",
"git",
"gitpython"
] |
call python code of different git branch other than the current repository without switching branch | 39,289,867 | <p>So, basically I have 2 versions of a project and for some users, I want to use the latest version while for others, I want to use older version. Both of them have same file names and multiple users will use it simultaneously. To accomplish this, I want to call function from different git branch without actually swit... | -1 | 2016-09-02T10:11:34Z | 39,291,484 | <p>You <em>must</em> have both versions of the code present / accessible in order to invoke both versions of the code dynamically.</p>
<p>The by-far-simplest way to accomplish this is to have both versions of the code present in different locations, as in <a href="http://stackoverflow.com/a/39290774/1256452">VonC's an... | 0 | 2016-09-02T11:38:40Z | [
"python",
"git",
"gitpython"
] |
Parsing SQL queries in python | 39,289,898 | <p>I need to built a mini-sql engine in python.So I require a sql-parser for it and I found out about python-sqlparse but am unable to understand how to extract column names or name of the table e.t.c from the SQL query.Can someone help me regarding this matter.</p>
| -3 | 2016-09-02T10:12:55Z | 39,290,439 | <p>Lets check python sqlparse documentation: <a href="https://sqlparse.readthedocs.io/en/latest/intro/#getting-started" rel="nofollow">Documentation - getting started</a></p>
<p>You can see there example how parse sql. This is what is there:</p>
<p><strong>1. First you need parse sql statement with parse method:</str... | 0 | 2016-09-02T10:42:39Z | [
"python",
"sql",
"parsing"
] |
Sorting a combined list of numbers and letters in Python | 39,289,996 | <p>I am trying to sort a list in Python, but one containing both letters and numbers in the same term. The problem with using sort on a string is that it doesn't sort the numbers correctly:</p>
<pre><code>2
23
3
</code></pre>
<p>etc</p>
<pre><code>list = [("a", ['8', '0']), ("a", ['7', '0b']), ("a", ['7', '0']), ("a... | 0 | 2016-09-02T10:17:18Z | 39,290,583 | <p>Here is my solution:</p>
<pre><code>def f(s):
m = {'a': 1,'b': 2,'c': 3,'d': 4,'e': 5,
'f': 6,'g': 7,'h': 8,'i': 9,'j': 10,
'k': 11,'l': 12,'m': 13,'n': 14,'o': 15,
'p': 16,'q': 17,'r': 18,'s': 19,
't': 20,'u': 21,'v': 22,'w': 23,
'x': 24,'y': 25,'z': 26}
result ... | 0 | 2016-09-02T10:49:27Z | [
"python",
"list",
"python-2.7",
"sorting"
] |
Sorting a combined list of numbers and letters in Python | 39,289,996 | <p>I am trying to sort a list in Python, but one containing both letters and numbers in the same term. The problem with using sort on a string is that it doesn't sort the numbers correctly:</p>
<pre><code>2
23
3
</code></pre>
<p>etc</p>
<pre><code>list = [("a", ['8', '0']), ("a", ['7', '0b']), ("a", ['7', '0']), ("a... | 0 | 2016-09-02T10:17:18Z | 39,291,296 | <p>It's not totally clear from your question, but I assume that you are ignoring the first item in each tuple, and only sorting on the list in the second item. I also assume that <em>only</em> letters from 'a' to 'i' can occur in in that list. </p>
<p>A simple way to convert a -> 1, b -> 2, c -> 3, ... i -> 9 is to ta... | 0 | 2016-09-02T11:29:29Z | [
"python",
"list",
"python-2.7",
"sorting"
] |
Sorting a combined list of numbers and letters in Python | 39,289,996 | <p>I am trying to sort a list in Python, but one containing both letters and numbers in the same term. The problem with using sort on a string is that it doesn't sort the numbers correctly:</p>
<pre><code>2
23
3
</code></pre>
<p>etc</p>
<pre><code>list = [("a", ['8', '0']), ("a", ['7', '0b']), ("a", ['7', '0']), ("a... | 0 | 2016-09-02T10:17:18Z | 39,291,329 | <p>Are you doing an incremental sort or are you only sorting by the <code>a1</code>elements?</p>
<p>If you really need to get a number value for a letter, you can probably use
<code>string.ascii_letters.index(letter)</code>
Or even better, if you only need consecutive numbers for letters, a<=b,
use <code>ord(lett... | 0 | 2016-09-02T11:30:58Z | [
"python",
"list",
"python-2.7",
"sorting"
] |
Solving two sets of coupled ODEs via matrix form in Python | 39,290,189 | <p>I want to solve a coupled system of ODEs in matrix form for two sets of variable (i.e. {y} and {m}) which has such a form:</p>
<blockquote>
<p>y'_n = ((m_n)**2) * y_n+(C * y)_n , m'_n=-4*m_n*y_n </p>
</blockquote>
<p>where <code>C</code> is a matrix, <code>[2 1, -1 3]</code>. </p>
<p>On the other hand I wa... | 1 | 2016-09-02T10:28:36Z | 39,291,710 | <p>Take a look at this to understand what is going on:</p>
<pre><code># we have a collection of different containers, namely list, tuple, set & dictionary
master = [[1, 2], (1, 2), {1, 2}, {1: 'a', 2: 'b'}]
for container in master:
a, b = container # python will automatically try to unpack the container to s... | 1 | 2016-09-02T11:49:03Z | [
"python",
"numpy",
"scipy",
"odeint"
] |
Solving two sets of coupled ODEs via matrix form in Python | 39,290,189 | <p>I want to solve a coupled system of ODEs in matrix form for two sets of variable (i.e. {y} and {m}) which has such a form:</p>
<blockquote>
<p>y'_n = ((m_n)**2) * y_n+(C * y)_n , m'_n=-4*m_n*y_n </p>
</blockquote>
<p>where <code>C</code> is a matrix, <code>[2 1, -1 3]</code>. </p>
<p>On the other hand I wa... | 1 | 2016-09-02T10:28:36Z | 39,292,390 | <p><code>odeint</code> works with one-dimensional arrays. In your function <code>dy_dt</code>, <code>Y</code> will be passed in as a one-dimensional numpy array with length 4. To split it into <code>y</code> and <code>m</code>, you can write</p>
<pre><code>y = Y[:2]
m = Y[2:]
</code></pre>
<p>The function <code>dy_... | 0 | 2016-09-02T12:25:25Z | [
"python",
"numpy",
"scipy",
"odeint"
] |
How to response different responses to the same multiple requests based on whether it has been responded? | 39,290,234 | <p>Let's say my <code>python</code> server has three different responses available. And one user send three HTTP requests at the same time. </p>
<p>How can I make sure that one requests get one unique response out of my three different responses?</p>
<p>I'm using python and mysql. </p>
<p>The problem is that even th... | 0 | 2016-09-02T10:31:10Z | 39,290,454 | <p>For starters, if MySQL isn't handling your performance requirements (and it rightly shouldn't, that doesn't sound like a very sane use-case),
consider using something like in-memory caching, or for more flexibility, Redis:
It's built for stuff like this, and will likely respond much, much quicker.
As an added bonus... | 0 | 2016-09-02T10:43:38Z | [
"python",
"distributed-computing"
] |
how to enumerate string placeholders? | 39,290,366 | <p>I'd like to know what's the best way to enumerate placeholders from strings, I've seen there is already another post which asks <a href="http://stackoverflow.com/questions/14061724/how-can-i-find-all-placeholders-for-str-format-in-a-python-string-using-a-regex">how-can-i-find-all-placeholders-for-str-format-in-a-pyt... | 0 | 2016-09-02T10:38:58Z | 39,290,458 | <p>Because you are ignoring the other elements on the tuple that <code>parse(s)</code> returns:</p>
<pre><code>>>> import string
>>>
>>> tests = [
... "{} spam eggs {}",
... "{0} spam eggs {1}",
... "{0:0.2f} spam eggs {1:0.2f}",
... "{{1}} spam eggs {{2}}"
... ]
>>>... | 2 | 2016-09-02T10:43:45Z | [
"python",
"string"
] |
unhashable type: 'numpy.ndarray' for optimization | 39,290,544 | <p>I was performing the optimization to find out the best fit line, using the scipy.optimize library, to a data set that I generated. But I am getting the error "unhashable type: 'numpy.ndarray'"</p>
<pre><code>import numpy as np
import pandas as pd
import scipy.optimize as spo
import matplotlib.pyplot as plt
def err... | 1 | 2016-09-02T10:47:33Z | 39,290,639 | <p>The function <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html#scipy.optimize.minimize" rel="nofollow"><code>scipy.optimize.minimize</code></a> takes a <strong>tuple</strong> of extra arguments, not a set. Change: </p>
<pre><code>min_result=spo.minimize(error_func, l, args={... | 3 | 2016-09-02T10:52:42Z | [
"python",
"optimization",
"scipy"
] |
Uwsgi wont load app when run as service | 39,290,628 | <p>I have setup a basic flask application in Centos 6, everything is contained in one file(app.py). I can run the file with uwsgi from the folder directory with the command <code>uwsgi --ini myuwsgi.ini</code> and everything works great. The contents of the ini file are: </p>
<pre><code>[uwsgi]
http-socket = :9090
... | 3 | 2016-09-02T10:51:41Z | 39,291,289 | <p>Try the following config and let me know if it works for you:</p>
<pre><code>[uwsgi]
callable = app
chdir = /path/to/your/project/
http-socket = :9090
plugins = python
processes = 4
virtualenv = /path/to/your/project/venv
wsgi-file = /path/to/your/project/app.py
</code></pre>
<p>You may also need to add <strong>ui... | 3 | 2016-09-02T11:29:22Z | [
"python",
"service",
"flask",
"centos",
"uwsgi"
] |
confused with the use of axis in Pandas (Python) | 39,290,667 | <p>From my understanding, axis=0 is running vertically downwards across rows and axis =1 is running horizontally across columns
for example:</p>
<pre><code>In [55]: df1
Out[55]:
x y z
0 1 3 8
1 2 4 NaN
2 3 5 7
3 4 6 NaN
4 5 7 6
5 NaN 1 9
6 NaN 9 5
</code></pre>... | 0 | 2016-09-02T10:54:25Z | 39,290,866 | <p>from the pandas documentation:</p>
<pre><code>DataFrame.dropna(axis=0, how='any', thresh=None, subset=None, inplace=False)
"Return object with labels on given axis omitted where alternately
any or all of the data are missing"
Parameters:
axis : {0 or âindexâ, 1 or âcolumnsâ}, or tuple/list thereof
... | 0 | 2016-09-02T11:04:20Z | [
"python",
"pandas"
] |
confused with the use of axis in Pandas (Python) | 39,290,667 | <p>From my understanding, axis=0 is running vertically downwards across rows and axis =1 is running horizontally across columns
for example:</p>
<pre><code>In [55]: df1
Out[55]:
x y z
0 1 3 8
1 2 4 NaN
2 3 5 7
3 4 6 NaN
4 5 7 6
5 NaN 1 9
6 NaN 9 5
</code></pre>... | 0 | 2016-09-02T10:54:25Z | 39,292,372 | <p><code>dropna()</code> drops the <strong>labels</strong> on the given axis so <code>df.dropna(axis=1)</code> means "look at the labels across axis 1 (i.e. x, y, and z) and drop that label if there are any NaN in that column"</p>
| 0 | 2016-09-02T12:24:19Z | [
"python",
"pandas"
] |
I can use ajax from /edit but not from /detail | 39,290,740 | <p>Django 1.10.</p>
<p>From DetailView I want to update the model object via ajax. Well, the model object is updated. But the ajax success function can't get data from the post method. I occur in failure function.</p>
<p>In other words, in Django in UpdateView I can stop at a breakpoint in form_valid, control that it... | 1 | 2016-09-02T10:58:24Z | 39,291,941 | <p>If I understand it correctly...</p>
<ol>
<li>You click <code>AjaxEdit</code> - it fetches response from <code>UpdateView</code> and loads it directly into your <code>/detail</code> page. You technically still on <code>detail</code> page now.</li>
<li>You check your form in chrome dev and see that form <code>action<... | 0 | 2016-09-02T12:00:30Z | [
"python",
"ajax",
"django"
] |
Merging matrices in Python | 39,290,823 | <p>I have some matrices with different lengths. The sizes are 200*59 , 200*1 and 200*1 and I want to make a big matrix of 200*61. How should I do it? </p>
| 0 | 2016-09-02T11:02:15Z | 39,290,951 | <p>Use <code>concatenate</code> from <code>numpy</code></p>
<pre><code>import numpy as np
a = np.random.rand(200,59)
b = np.random.rand(200,1)
c = np.random.rand(200,1)
d = np.concatenate((a,b,c),axis=1)
print d.shape #(200,61)
</code></pre>
| 1 | 2016-09-02T11:10:00Z | [
"python",
"matrix"
] |
cmd module - python | 39,290,830 | <p>I am trying to build a python shell using cmd module. </p>
<pre><code>from cmd import Cmd
import subprocess
import commands
import os
from subprocess import call
class Pirate(Cmd):
intro = 'Welcome to shell\n'
prompt = 'platform> '
pass
if __name__ == '__main__':
Pirate().cmdloop()
</code></p... | 2 | 2016-09-02T11:02:35Z | 39,291,035 | <p>I have a hard time trying to figure out why you would need such a thing, but here's my attempt:</p>
<pre><code>import subprocess
from cmd import Cmd
class Pirate(Cmd):
intro = 'Welcome to shell\n'
prompt = 'platform> '
def default(self, line): # this method will catch all commands
subproce... | 0 | 2016-09-02T11:15:15Z | [
"python",
"shell",
"cmd",
"subprocess"
] |
Unable to fetch result of Python Script in PHP | 39,290,891 | <p>I am using Xampp and Ubuntu 16.04..</p>
<p>now for my project i need python and php integration to call python script from PHP. Actually describing my script... I am using pypi newspaper library to extract a news summary from a news web portal</p>
<pre><code>#!/usr/bin/env python
from newspaper import Article
url=... | 1 | 2016-09-02T11:06:19Z | 39,291,245 | <p>One of the <code>passthru()</code> or <code>exec()</code> commands should do the trick. See <a href="http://php.net/manual/en/function.passthru.php" rel="nofollow">http://php.net/manual/en/function.passthru.php</a> for more info. Something like: </p>
<pre><code><?php
$full_path = `<full_path_to_python_scr... | 0 | 2016-09-02T11:27:15Z | [
"php",
"python"
] |
Find dict that has user inputted key from a list of dicts | 39,290,895 | <p><strong>python 3.5</strong></p>
<p>hi i have this simple json.json file :</p>
<p><strong>json</strong></p>
<pre><code>{"x": [
{"A": "B"},
{"C": "D"},
{"E": "F"}
]}
</code></pre>
<p>and i have this code to find the letter after A or C or E</p>
<p><strong>python</strong></p>
<pre><code>data = json.lo... | 1 | 2016-09-02T11:06:37Z | 39,291,001 | <p>So you want to find the value by searching without hard coding the index, what you need is a loop that checks each dict for the key:</p>
<pre><code>data = json.load(open('json.json'))
R = 'C' #user input
for d in data['x']:
if R in d:
print(d[R])
break # if there can be more that one match then... | 3 | 2016-09-02T11:13:44Z | [
"python",
"json"
] |
Find dict that has user inputted key from a list of dicts | 39,290,895 | <p><strong>python 3.5</strong></p>
<p>hi i have this simple json.json file :</p>
<p><strong>json</strong></p>
<pre><code>{"x": [
{"A": "B"},
{"C": "D"},
{"E": "F"}
]}
</code></pre>
<p>and i have this code to find the letter after A or C or E</p>
<p><strong>python</strong></p>
<pre><code>data = json.lo... | 1 | 2016-09-02T11:06:37Z | 39,291,177 | <p>As Padraic Cunningham pointed out, you need to loop through your results. Your solution would look like this:</p>
<pre><code>data = json.load(open('json.json'))
R = 'C' #user input
print([x for x in data['x'] if x.keys()[0] == R][0][R])
</code></pre>
<p><code>[x for x in data['x'] if x.keys()[0] == R]</code> gives... | 0 | 2016-09-02T11:23:32Z | [
"python",
"json"
] |
Does coverage provide its own version of a nose plugin? | 39,290,927 | <p>The documentation for <a href="http://nose.readthedocs.io/en/latest/plugins/cover.html" rel="nofollow">nose</a> Version 1.3.7 says that </p>
<blockquote>
<p>Newer versions of coverage contain their own nose plugin which is superior to the builtin plugin. It exposes more of coverageâs options and uses coverageâ... | 0 | 2016-09-02T11:08:35Z | 39,306,130 | <p>Coverage has never provided its own nose plugin. </p>
<p>Notice that nose is no longer maintained, as the <a href="http://nose.readthedocs.io/en/latest/" rel="nofollow">nose documentation states</a>:</p>
<blockquote>
<p>Nose has been in maintenance mode for the past several years and will likely cease without a... | 1 | 2016-09-03T10:58:11Z | [
"python",
"code-coverage",
"nose"
] |
How to change python to .exe file in visual studio | 39,290,932 | <p>How to change python code to <strong>.exe</strong> file using microsoft Visual Studio 2015 without installing any package? Under "Build" button, there is no convert to <strong>.exe</strong> file.</p>
| -2 | 2016-09-02T11:08:52Z | 39,291,254 | <p>Python is a dynamic language (executed by interpreter) and cannot be compiled to binary. (Similar to javascript, php and etc.) It needs interpreter to execute python commands. It's not possible to do that without 3rd party tools which translates python to another languages and compile them to exe.</p>
| 0 | 2016-09-02T11:27:33Z | [
"python",
"visual-studio",
"visual-studio-2015",
"exe"
] |
validate loaded data in QTableView | 39,290,991 | <p>I got a MVC sytle PyQT UI program, and already got delegates binded to certain column for whatever date or regex validation, when insert manually, everything goes fine, the limits holds on </p>
<pre><code>class IPDelegate(QStyledItemDelegate):
def createEditor(self, parent, option, index):
line_edit.set... | 1 | 2016-09-02T11:12:43Z | 39,307,932 | <p>solved by myself, did not use the misery mvc module, turn all data validation to a set of regex, loop over at both set delegate and raw regex validation</p>
| 0 | 2016-09-03T14:19:23Z | [
"python",
"delegates",
"pyqt",
"tableview"
] |
Easily editing base class variables from inherited class | 39,291,000 | <h3>How does communication between base classes and inherited classes work?</h3>
<p>I have a data class in my python code ( storing all important values, duh ), I tried inheriting new subclasses from the <em>data base class</em>, everything worked fine except the fact that the classes were not actually communicating (... | 0 | 2016-09-02T11:13:41Z | 39,291,125 | <p>Well, you could do that in this way:</p>
<pre><code>class Base:
x = 'baseclass var' # The value I want to edit
class Subclass(Base):
@classmethod
def change_base_x(cls):
Base.x = 'nothing'
print Subclass.x
Subclass.change_base_x()
print Subclass.x
</code></pre>
<p>furthermore, you don't have... | 1 | 2016-09-02T11:21:07Z | [
"python",
"class",
"object",
"inheritance",
"attributes"
] |
Flipping one digit to get all digits the same: is the code wrong? | 39,291,054 | <p>Trying to solve the following problem:</p>
<p>Given a binary D containing only digits 0's and 1's, I have to determine if all the digits could be made the same, by flipping only one digit. </p>
<p>The input is the number of Ds to test, and then the Ds, one per line. for instance:</p>
<pre><code>3
11111001111010
1... | 0 | 2016-09-02T11:16:48Z | 39,291,243 | <p>Your program doesn't output anything in case that all the digits are the same. You can fix the problem by changing the last part in following way:</p>
<pre><code>if ones == 1:
print("YES")
elif zeros == 1:
print("YES")
elif ones == 0 or zeros == 0:
print("NO") # assuming that one bit must be changed
</c... | 2 | 2016-09-02T11:27:06Z | [
"python",
"python-3.x"
] |
Flipping one digit to get all digits the same: is the code wrong? | 39,291,054 | <p>Trying to solve the following problem:</p>
<p>Given a binary D containing only digits 0's and 1's, I have to determine if all the digits could be made the same, by flipping only one digit. </p>
<p>The input is the number of Ds to test, and then the Ds, one per line. for instance:</p>
<pre><code>3
11111001111010
1... | 0 | 2016-09-02T11:16:48Z | 39,297,176 | <p>The solution is rather embarrassing: I outputted the answer as all <em>uppercase</em>, where the expected output is <em>Title case</em>. The following code is accepted:</p>
<pre><code>T = int(input())
for i in range(T):
line = input()
ones = zeros = 0
for c in line:
if int(c) == 1:
... | 0 | 2016-09-02T16:39:24Z | [
"python",
"python-3.x"
] |
ImportError: cannot import name Error | 39,291,077 | <p>I have a very simple test function that I need to capture its execution time using 'timeit' module, but I get an error</p>
<p>The function:</p>
<pre><code>import timeit
def test1():
l = []
for i in range(1000):
l = l + [i]
t1 = timeit.Timer("test1()", "from __main__ imp... | 0 | 2016-09-02T11:18:07Z | 39,291,401 | <p>I think there are couple of problems with your code. First for all make sure you can import timeit. And you have it as a module. For this, you can just run:</p>
<pre><code> python -m timeit '"-".join(str(n) for n in range(100))'
</code></pre>
<p>If it execute fine then you sure have the timeit module. </p>
<p>Now... | 0 | 2016-09-02T11:34:35Z | [
"python",
"timeit"
] |
python strange looking loop | 39,291,161 | <pre><code> char_rdic = list('helo')
char_dic = {w:i for i ,w in enumerate(char_rdic)}
</code></pre>
<p>I'm not really sure what this code actually do. what does w and i represent in this code? </p>
| -6 | 2016-09-02T11:23:04Z | 39,291,250 | <p>This code creates <code>char_dic</code> dictionary with chars from <code>'helo'</code> string as keys and their occurence indexes in given string.
<code>i</code> is an index of <code>w</code> element in <code>char_rdic</code> list.</p>
| 0 | 2016-09-02T11:27:25Z | [
"python"
] |
python strange looking loop | 39,291,161 | <pre><code> char_rdic = list('helo')
char_dic = {w:i for i ,w in enumerate(char_rdic)}
</code></pre>
<p>I'm not really sure what this code actually do. what does w and i represent in this code? </p>
| -6 | 2016-09-02T11:23:04Z | 39,291,282 | <p>This is a dict comprehension. If you are familiar with list comprehension (<code>[do_stuff(a) for a in iterable]</code> construct), that works very much the same way, but it builds a dict.</p>
<p>See <a href="https://stackoverflow.com/questions/1747817/create-a-dictionary-with-list-comprehension-in-python">Create a... | 1 | 2016-09-02T11:28:47Z | [
"python"
] |
Unwanted quotations marks in python terminal | 39,291,204 | <p>I am using Geany to code and Ubuntu 16.04 as my OS.
when I enter this code</p>
<pre><code>print("Result:",a+b)
</code></pre>
<p>It gives it's output as <code>('Result:', a+b)</code>.</p>
| -1 | 2016-09-02T11:25:14Z | 39,291,390 | <p>In <strong>python 2</strong>:</p>
<pre><code>print("Result:",a+b) --> # ('Result:', 6)
</code></pre>
<p>parens are no needed, because otherwise we are printing a tuple of two elements: string <code>'Result'</code> and an integer <code>6</code>.</p>
<p>In <strong>python 3</strong>:</p>
<pre><code>print("Result... | 0 | 2016-09-02T11:34:01Z | [
"python"
] |
Django: Not Found static/admin/css | 39,291,223 | <p>I just deployed my first Django app on Heroku but I notice that it doesn't have any CSS like when I runserver on the local machine. I know there's something wrong with static files but I don't understand much about it even when I already read <a href="https://docs.djangoproject.com/en/1.10/howto/static-files/#servin... | 0 | 2016-09-02T11:26:25Z | 39,291,292 | <p>You shouldn't change <code>BASE_DIR</code></p>
<p>Change <code>STATIC_ROOT</code></p>
<pre><code>STATIC_ROOT = os.path.join(BASE_DIR, 'static')
</code></pre>
<p>And run <code>collectstatic</code> again</p>
| 1 | 2016-09-02T11:29:26Z | [
"python",
"django",
"heroku",
"deployment"
] |
Django: Not Found static/admin/css | 39,291,223 | <p>I just deployed my first Django app on Heroku but I notice that it doesn't have any CSS like when I runserver on the local machine. I know there's something wrong with static files but I don't understand much about it even when I already read <a href="https://docs.djangoproject.com/en/1.10/howto/static-files/#servin... | 0 | 2016-09-02T11:26:25Z | 39,291,412 | <p>Django does not serve static files in production. Normally, To serve Django static files in production you need to setup a standalone server e.g. nginx.</p>
<p>However, the way to serve static files in Heroku is a little different. See the link below, provided by Heroku team, for details on how to serve static file... | 1 | 2016-09-02T11:35:09Z | [
"python",
"django",
"heroku",
"deployment"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.