title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
Concatenating data frames into a pandas dataframe with pre set row names python | 38,394,005 | <p>I was trying to refactor code that was previously very manual, and involved setting the index for each new data frame I created, to essentially create this desired output:</p>
<pre><code> f1 precision recall
A 0.600315956 0.72243346 0.513513514
B 0.096692112 0.826086957 0.051351351
C 0.08564231... | 0 | 2016-07-15T10:37:12Z | 38,426,587 | <p>I solved my problem.</p>
<p>Using <a href="http://stackoverflow.com/questions/10715965/add-one-row-in-a-pandas-dataframe">this answer</a>, my code becomes:</p>
<pre><code>summaryDF = pd.DataFrame(columns=('precision','recall','f1'))
def evaluation(trueLabels, evalLabels):
global summaryDF
precision = pr... | 0 | 2016-07-17T22:37:19Z | [
"python",
"pandas",
"dataframe",
"row",
"concat"
] |
How does Django Form validation work? | 38,394,078 | <p>There is reasonably precise
documentation about <a href="https://docs.djangoproject.com/en/1.10/ref/forms/validation/" rel="nofollow">Django Form validation</a>
(as of Django 1.10)
and I have used it successfully already,
so what is my problem?</p>
<p><strong>My problem is remembering this stuff.</strong></p>
<p... | 0 | 2016-07-15T10:40:59Z | 38,394,079 | <p>Assume you have a <a href="https://docs.djangoproject.com/en/dev/ref/forms/" rel="nofollow">Form</a> class <code>MyForm</code> with an instance called <code>myform</code>
and containing various <a href="https://docs.djangoproject.com/en/dev/ref/forms/fields/" rel="nofollow">Fields</a>, in particular a
<code>SomeFie... | 1 | 2016-07-15T10:40:59Z | [
"python",
"django",
"validation",
"frameworks",
"django-forms"
] |
setting PYTHON_LIBRARY during opencv-2.4.10 build | 38,394,084 | <p>I'm on CentOS6.7 and I'm building opencv-2.4.10 (I removed 2.4.9 because my python cv2 package didn't seem to go along with underneath opencv-2.4.9. When I print cv2.__version__ in python, it shows 2.4.10 so I figured I should upgrade opencv to 2.4.10 because python cv2 is just a python wrapper for real c++ opencv.... | 0 | 2016-07-15T10:41:04Z | 38,395,768 | <p>I succeeded in building opencv-2.4.10 by following commands. </p>
<p>make clean ; cmake -D CMAKE_INSTALL_PREFIX=/usr/local -D BUILD_EXAMPLES=ON -D CUDA_GENERATION=Auto -D PYTHON_INCLUDE_DIR=/home/ckim/anaconda2/include/python2.7/ PYTHON_LIBRARY=/home/ckim/anaconda2/lib/libpython2.7.so .. | & tee log.cmake
mak... | 0 | 2016-07-15T12:09:07Z | [
"python",
"opencv",
"centos"
] |
Appending NaN to a Dataframe if variable is not defined | 38,394,221 | <p>I am using a code to read a dict and then calculate some variables and append it in a df in last. I am using this type of thing to calculate values.</p>
<pre><code>try:
most_visited_city = sorted_cities[-1]
per_visit_max_city = 100 * cities[sorted_cities[-1]]['count'] / float(total_visits)
if total_visi... | 0 | 2016-07-15T10:47:22Z | 38,396,368 | <p>Numpy NaN is distinct from the generic Python None.</p>
<p>Try this:</p>
<pre><code>def ret(x):
try:
x
except NameError:
return numpy.nan
else:
return x
</code></pre>
| 0 | 2016-07-15T12:40:06Z | [
"python",
"dataframe"
] |
Buying ram to avoid chunking for 30-50Gb plus files | 38,394,265 | <p>I use pandas to read very large csv files, which also are gzipped.
I unzip into csv files which are approx 30-50GB.
I chunk the files and process/manipulate them.
Finally add the relevant data to HDF5 files which I compress </p>
<p>It works fine but is slow since I have to deal with one file per day and have severa... | 1 | 2016-07-15T10:48:52Z | 38,394,831 | <p>I think you have quite a few things which can be optimized:</p>
<ul>
<li><p>first of all read only those columns that you really need instead of reading and then dropping them - use <code>usecols=list_of_needed_columns</code> parameter</p></li>
<li><p>increase your chunksize - try it with different values - i would... | 1 | 2016-07-15T11:18:13Z | [
"python",
"csv",
"pandas",
"ram",
"chunking"
] |
Distribute pip package no source code | 38,394,362 | <p>I have an "homemade" python package which i can successfully install via pip package manager.</p>
<p>I'd like ti distribute it without giving the source code (*.py files)... i tried to compile them with</p>
<p><code>python -m compileall .</code></p>
<p>and then installed by typing <code>pip install .</code></p>
... | 0 | 2016-07-15T10:54:15Z | 38,394,512 | <p>I guess it is to do with setuptools not packaging up <code>*.pyc</code> files, because normally you don't want them.</p>
<p>You should create a file <code>MANIFEST.in</code> with the content</p>
<pre><code>global-include *.py[co]
global-exclude *.py
</code></pre>
<p>This tells setuptools to exclude <code>*.py</co... | 0 | 2016-07-15T11:01:31Z | [
"python",
"raspberry-pi",
"pip"
] |
Python SQLite delete rows IN | 38,394,364 | <p>It's a similar problem to others out there but no body has clearly explained how to correct this:</p>
<p><strong><em>process.py</em></strong></p>
<pre><code>import sqlite3 # version 2.6.0
connection = sqlite3.connect('./db.sqlite')
cursor = connection.cursor()
count_before = cursor.execute('SELECT COUNT(*) FROM ... | 1 | 2016-07-15T10:54:22Z | 38,394,385 | <p>Right, need to commit on connection:</p>
<pre><code>cursor.close()
connection.commit() # <<<<< !!
connection.close()
</code></pre>
| 1 | 2016-07-15T10:55:07Z | [
"python",
"sqlite"
] |
Tkinter createfilehandler with socket not working | 38,394,380 | <p>I found a working example for Tkinter createfilehandler with socket in Chapter 18 from "Python and Tkinter Programming" (of John Grayson) client_server.py</p>
<p>I have tested it on Linux Mint 14.04, with python 2.7.6, and the program seems to work without errors, but ...</p>
<p>The problem is that: server sends d... | -1 | 2016-07-15T10:54:53Z | 38,394,944 | <p>The host variable in <code>Server.__init__</code> is quite likely different than IP address <code>127.0.0.1</code> used by <code>GUIClient</code></p>
<pre><code>class Server:
def __init__(self):
host = socket.gethostbyname(socket.gethostname())
...
# addr probably != 127.0.0.1
s... | 0 | 2016-07-15T11:24:17Z | [
"python",
"sockets",
"tkinter"
] |
Tensorflow compare tf.int32 and tf.constant gives error | 38,394,413 | <pre><code>import tensorflow as tf
a=tf.int32
b=tf.constant(3)
a==b
</code></pre>
<p>gives error instead of giving 'false'</p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.4/dist-packages/tensorflow/python/framework/dtypes.py", line 24... | -3 | 2016-07-15T10:56:31Z | 38,398,094 | <p>This comparison does not make sense. </p>
<pre><code>>>> a=tf.int32
>>> type(a)
<class 'tensorflow.python.framework.dtypes.DType'>
>>> print(a)
<dtype: 'int32'>
</code></pre>
<p>versus</p>
<pre><code>>>> b=tf.constant(3)
>>> type(b)
<class 'tensorflow.py... | 3 | 2016-07-15T14:03:29Z | [
"python",
"python-3.x",
"tensorflow",
"python-3.4"
] |
python and shell for loop combined extrange behaviour | 38,394,422 | <p>I have a simple python script to rename my data: wchich has worked for one file:</p>
<pre><code>for line in Coord:
coord = line.split()[0]
miRname = line.split()[1]
print miRname
os.system('samtools view -h ' + BAMfile + ' '+ coord + ' >' + miRname) #extract the reads from a coordinate
os.sys... | 0 | 2016-07-15T10:56:59Z | 38,657,447 | <p>there is a typo <code>bam in $MAPPPINGS_DIR</code> three P instead of two... â sp asic</p>
| 0 | 2016-07-29T11:15:45Z | [
"python",
"bash",
"for-loop"
] |
Running a kivy program on Android | 38,394,429 | <p>First of all i am aware that there have been alot of similair questions asked already, but somehow i cant figure anything out, I have a python-kivy program that I want to run on Android, the program works perfectly on my computer, I've ran various simple programs using Python Interpreter with Kivy, so far it was the... | 1 | 2016-07-15T10:57:18Z | 38,395,303 | <p>You may try using <strong>buildozer</strong> to package your app and deploy to Android device directly for debug, you only need to install this in your machine, and change the developer options in Android to allow external source.</p>
<p>Basically once you install the <strong>buildozer</strong>, you need to initial... | 1 | 2016-07-15T11:44:46Z | [
"android",
"python",
"python-3.x",
"kivy"
] |
How to sort dataframe in numerical ascending order? | 38,394,599 | <p>I'm having my Dataframe which contains two columns. I want to sort this Dataframe in numerical ascending order. I'm tried to sort it but It will sort in the alphabetical order which I don't want.</p>
<p>I'm tried with following code : </p>
<p><strong>program code-</strong></p>
<pre><code>dfs.sort_index(ascending=... | -1 | 2016-07-15T11:05:53Z | 38,395,443 | <p>Make sure the values are numeric by forcing it explicit <code>a = a[:,0].astype(int)</code>. Then try <code>a[a[:, 0].argsort()]</code>, where <code>a</code> is the dataframe and <code>0</code> is the column index.
More on syntax - <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.argsort.html" rel... | 0 | 2016-07-15T11:51:28Z | [
"python",
"sorting",
"pandas",
"dataframe"
] |
Fastest way to filter a pandas dataframe on multiple columns | 38,394,739 | <p>I have a pandas dataframe with several columns that labels data in a final column, for example, </p>
<pre><code>df = pd.DataFrame( {'1_label' : ['a1','b1','c1','d1'],
'2_label' : ['a2','b2','c2','d2'],
'3_label' : ['a3','b3','c3','d3'],
'data' : [1,2,3,... | 1 | 2016-07-15T11:13:26Z | 38,394,847 | <p>If I understood correctly, merge should do the job:</p>
<pre><code>pd.DataFrame(list_t, columns=['1_label', '2_label', '3_label']).merge(df)
Out[73]:
1_label 2_label 3_label data
0 a1 a2 a3 1
1 d1 d2 d3 4
</code></pre>
| 4 | 2016-07-15T11:18:45Z | [
"python",
"pandas"
] |
Fastest way to filter a pandas dataframe on multiple columns | 38,394,739 | <p>I have a pandas dataframe with several columns that labels data in a final column, for example, </p>
<pre><code>df = pd.DataFrame( {'1_label' : ['a1','b1','c1','d1'],
'2_label' : ['a2','b2','c2','d2'],
'3_label' : ['a3','b3','c3','d3'],
'data' : [1,2,3,... | 1 | 2016-07-15T11:13:26Z | 38,394,859 | <p>Assuming no duplicates, you could create index out of the columns you want to "filter" on:</p>
<pre><code>In [10]: df
Out[10]:
1_label 2_label 3_label data
0 a1 a2 a3 1
1 b1 b2 b3 2
2 c1 c2 c3 3
3 d1 d2 d3 4
In [11]: df.set_index(['1_l... | 4 | 2016-07-15T11:19:28Z | [
"python",
"pandas"
] |
How to revise this code | 38,394,751 | <pre><code>score = raw_input("Enter Score:___ (between 0.0 and 1.0)")
try:
y = float(score)
except:
print 'Type a Number'
try:
if y > 1 or y < 0:
y = 'Not in Score Range'
x = int(y)
except:
print 'Not in Score Range'
else:
if y >= 0.9:
print 'A'
elif y >= .8... | 0 | 2016-07-15T11:14:16Z | 38,394,817 | <p>You can do that by simply adding a <code>flag</code> variable:</p>
<pre><code>score = raw_input("Enter Score:___ (between 0.0 and 1.0)")
flag = 0
try:
y = float(score)
except:
print 'Type a Number'
flag = 1
if flag == 0:
try:
if y > 1 or y < 0:
y = 'Not in Score Ran... | 2 | 2016-07-15T11:17:45Z | [
"python"
] |
How to revise this code | 38,394,751 | <pre><code>score = raw_input("Enter Score:___ (between 0.0 and 1.0)")
try:
y = float(score)
except:
print 'Type a Number'
try:
if y > 1 or y < 0:
y = 'Not in Score Range'
x = int(y)
except:
print 'Not in Score Range'
else:
if y >= 0.9:
print 'A'
elif y >= .8... | 0 | 2016-07-15T11:14:16Z | 38,394,983 | <p>I personally prefer to work without flags, and simply wrapping it in a function.</p>
<pre><code>def get_classifier():
score = raw_input("Enter Score:___ (between 0.0 and 1.0)")
try:
score = float(score)
except:
print('Type a Number')
return None
if not 0. <= score <= 1... | 2 | 2016-07-15T11:26:55Z | [
"python"
] |
How to revise this code | 38,394,751 | <pre><code>score = raw_input("Enter Score:___ (between 0.0 and 1.0)")
try:
y = float(score)
except:
print 'Type a Number'
try:
if y > 1 or y < 0:
y = 'Not in Score Range'
x = int(y)
except:
print 'Not in Score Range'
else:
if y >= 0.9:
print 'A'
elif y >= .8... | 0 | 2016-07-15T11:14:16Z | 38,395,321 | <p>To add yet another variant, you could differentiate between different exceptions. May be overkill for this problem, but I think in general this is more elegant:</p>
<pre><code>class OutOfRangeException(Exception):
pass
def stringToScore(string):
x = float(string)
if not ( 0 < x < 1):
rais... | 0 | 2016-07-15T11:45:40Z | [
"python"
] |
how to specify test specific setup and teardown in python unittest | 38,394,782 | <p>I want to create unittest test with two different set up and tearDown methon in same class with two different test.</p>
<p>each test will use its specific setUp and tearDown method in python unittest framework.</p>
<p>could anyone help me.</p>
<pre><code> class processtestCase(unittest.TestCase):
pr... | -1 | 2016-07-15T11:15:45Z | 38,395,203 | <p>In the question, you mention that you have two tests, each with its own setup and teardown. There are at least two ways to go:</p>
<p>You can either embed the <code>setUp</code> and <code>tearDown</code> code into each of the tests:</p>
<pre><code>class FooTest(unittest.TestCase):
def test_0(self):
...... | 0 | 2016-07-15T11:39:20Z | [
"python",
"python-unittest",
"nose2"
] |
Accessing the data field in a pcap dump file in python | 38,394,804 | <p>I am using the following code:</p>
<pre><code>import pyshark
cap = pyshark.FileCapture('/home/my_location/python_parse/my_file.pcap')
count = 0;
for caps in cap:
print caps.pretty_print();
print "Count is " + str(count)
count+=1;
</code></pre>
<p>My pcapfile is located here <a href="http://s000.tinyupl... | 3 | 2016-07-15T11:16:49Z | 39,819,879 | <p>You can use the <code>usb_capdata</code> field of the DATA layer.</p>
<pre><code>import pyshark
caps = pyshark.FileCapture('/home/my_location/python_pars/my_file.pcap')
print caps[10].layers[1].usb_capdata
</code></pre>
<p>Will output the same as wireshark :</p>
<pre><code>'80:08:0b:82:00:00:85:97:8a:86:00:00'
</... | 0 | 2016-10-02T17:49:48Z | [
"python",
"wireshark",
"pcap"
] |
Is it possible to do static code analysis for python using SonarQube? | 38,394,843 | <p>I need to check for errors in my python files before building the project. Is this possible using SonarQube? If Yes, what checks are performed for Python(syntax, indentation, import errors, etc)?</p>
| -1 | 2016-07-15T11:18:39Z | 38,395,447 | <p>SonarQube Analyzers assume they're scanning compilable code. Pylint checks are available but off by default. For a full list of built-in rules, see the <a href="http://dist.sonarsource.com/reports/coverage/rules/python_rules_coverage.html" rel="nofollow">SonarAnalyzer for Python rule report</a>.</p>
| 0 | 2016-07-15T11:51:40Z | [
"python",
"sonarqube",
"syntax-error",
"sonar-runner",
"static-code-analysis"
] |
graphlab create sframe how to get SArray median | 38,395,359 | <p>I'm studying graphlab create
with </p>
<pre><code>data=graphlab.SFrame.read_csv('test.csv')
</code></pre>
<p>im trying to get median of one of columns</p>
<pre><code>data_train.fillna(('Credit_History',data_train['Credit_History'].median()))
</code></pre>
<p>but I got error</p>
<pre><code>----------------------... | 1 | 2016-07-15T11:47:18Z | 38,405,492 | <p><code>SArray</code> doesn't have a median method. The best way to get the median is through the <code>sketch_summary</code> method, then <code>quantile</code>. More info on the sketch summary at</p>
<p><a href="https://turi.com/products/create/docs/generated/graphlab.Sketch.html" rel="nofollow">https://turi.com/pro... | 1 | 2016-07-15T21:51:28Z | [
"python",
"pandas",
"machine-learning",
"data-analysis",
"graphlab"
] |
graphlab create sframe how to get SArray median | 38,395,359 | <p>I'm studying graphlab create
with </p>
<pre><code>data=graphlab.SFrame.read_csv('test.csv')
</code></pre>
<p>im trying to get median of one of columns</p>
<pre><code>data_train.fillna(('Credit_History',data_train['Credit_History'].median()))
</code></pre>
<p>but I got error</p>
<pre><code>----------------------... | 1 | 2016-07-15T11:47:18Z | 38,405,583 | <p>I think I understand what your trying to do. Sframe doesn't have a default median function. I would improvise like this:</p>
<pre><code>import numpy as np
data_train.fillna('Credit_History', np.median(data_train['Credit_History']))
</code></pre>
| 3 | 2016-07-15T22:02:06Z | [
"python",
"pandas",
"machine-learning",
"data-analysis",
"graphlab"
] |
Python file to run from C++ code | 38,395,421 | <p>I am using Python 3.3.
I am using C++ Qt code and embedding python into it. I want to execute one python file using C Python API in Python 3.</p>
<p>Below is sample code i am using to read the file and execute using Qt.</p>
<pre><code>FILE *cp = fopen("/tmp/my_python.py", "r");
if (!cp)
{
return;
}
Py... | 0 | 2016-07-15T11:50:39Z | 38,396,321 | <p>The following test program works fine passing the <code>FILE</code> pointer in directly for me.</p>
<p><strong>runpy.c</strong></p>
<pre><code>#include <stdio.h>
#include <Python.h>
int main(int argc, char** argv)
{
if (argc != 2)
{
printf("Usage: %s FILENAME\n", argv[0]);
return 1;
}
... | 1 | 2016-07-15T12:37:55Z | [
"python",
"python-2.7",
"python-3.x"
] |
global name maxLengthPOI not defined in Python | 38,395,490 | <p>I have trouble understanding this strange behavior of Global variable in Python</p>
<p>I would like to explain the code is brief:
Here I have a function populate_sheet, that compares the same column in two different dataframes and returns another dataframe having uncommon records.</p>
<p>Next, If the columnName is... | 0 | 2016-07-15T11:53:43Z | 38,395,588 | <p>When you call </p>
<pre><code>#THROWS ERROR: Global name maxLengthPOI is not defined.
def modifyPoI_0(value):
global maxLengthPOI
</code></pre>
<p><code>maxLengthPOI</code> does not exists.</p>
<p>As you see in the first code you posted, <code>maxLengthPOI</code> is not <code>global</code> at ... | 1 | 2016-07-15T11:59:24Z | [
"python",
"global-variables",
"global"
] |
global name maxLengthPOI not defined in Python | 38,395,490 | <p>I have trouble understanding this strange behavior of Global variable in Python</p>
<p>I would like to explain the code is brief:
Here I have a function populate_sheet, that compares the same column in two different dataframes and returns another dataframe having uncommon records.</p>
<p>Next, If the columnName is... | 0 | 2016-07-15T11:53:43Z | 38,395,869 | <pre><code>def populate_sheet(df, input, output, sheet_name, sheet, columnName,
maxLengthPOI = 1 # defined in populate_sheet() so local to populate_sheet(), not global!
def modifyPoI_0(value):
global maxLengthPOI # not defined (as a global)
</code></pre>
<p>Define <code>maxLengthPOI</code> outside of... | 0 | 2016-07-15T12:14:00Z | [
"python",
"global-variables",
"global"
] |
Python script to strip new lines from .txt files contained in a directory | 38,395,551 | <p>I have a list of .txt files contained in a directory. Each file may have multiple lines. What could be the Python script to strip off all newlines from all the files contained in that directory? The resulting files should have exactly one line containing all the texts.</p>
<pre><code>import os
os.chdir("/home/Pavye... | -7 | 2016-07-15T11:57:08Z | 38,396,034 | <pre><code>import os
import sys
import fileinput
dir = "." #Directory to scan for files
file_list = os.listdir(dir)
for file in file_list:
if file.endswith(".txt"):
with fileinput.FileInput(file, inplace=True, backup=".bak") as f:
for line in f:
sys.stdout.write(line.replace("... | -1 | 2016-07-15T12:22:38Z | [
"python",
"python-3.x"
] |
Python script to strip new lines from .txt files contained in a directory | 38,395,551 | <p>I have a list of .txt files contained in a directory. Each file may have multiple lines. What could be the Python script to strip off all newlines from all the files contained in that directory? The resulting files should have exactly one line containing all the texts.</p>
<pre><code>import os
os.chdir("/home/Pavye... | -7 | 2016-07-15T11:57:08Z | 38,397,487 | <p>Use <a href="https://docs.python.org/3/library/glob.html?highlight=glob#glob.glob" rel="nofollow"><code>glob.glob()</code></a> to find the files of interest, i.e. those that end with <code>.txt</code>. <code>glob()</code> returns a list of matching filenames and also leaves the path intact, so you don't need to chan... | 0 | 2016-07-15T13:35:11Z | [
"python",
"python-3.x"
] |
Change number of parameters in a function and in the least square (global fitting) | 38,395,743 | <p>I would like to make a global fitting of a set of data. the equation has 5 parameter (<code>r1</code> <code>r2</code> <code>dw</code> <code>pop</code> <code>kex</code>). If I do a individual fit I will have these parameter to fit for 1 input file and this is ok, I can do that. But when I try to make a global fitting... | -1 | 2016-07-15T12:07:28Z | 38,397,029 | <p>I don't understand your problem. Can you explain?</p>
<p>I think there is something to do with <a href="https://docs.python.org/2/library/functools.html#functools.partial" rel="nofollow">functools.partial</a>.</p>
<blockquote>
<p>Return a new partial object which when called will behave like func called with the... | 0 | 2016-07-15T13:12:33Z | [
"python",
"function",
"least-squares",
"data-fitting"
] |
Python Beautiful Soup find string and extract following string | 38,395,751 | <p>I am programming a web crawler with the help of beautiful soup.I have the following html code:</p>
<pre><code><tr class="odd-row">
<td>xyz</td>
<td class="numeric">5,00%</td>
</tr>
<tr class="even-row">
<td>abc</td>
<... | 0 | 2016-07-15T12:08:05Z | 38,396,613 | <p>If I understand your question correctly, and if I assume your html code will always follow your sample structure, you can do this:</p>
<pre><code>result = {}
table_rows = soup.find_all("tr")
for row in table_rows:
table_columns = row.find_all("td")
result[table_columns[0].text] = tds[1].text
print result #... | 0 | 2016-07-15T12:50:48Z | [
"python",
"string",
"beautifulsoup"
] |
Python Beautiful Soup find string and extract following string | 38,395,751 | <p>I am programming a web crawler with the help of beautiful soup.I have the following html code:</p>
<pre><code><tr class="odd-row">
<td>xyz</td>
<td class="numeric">5,00%</td>
</tr>
<tr class="even-row">
<td>abc</td>
<... | 0 | 2016-07-15T12:08:05Z | 38,396,683 | <p>So as I understand your question you want to iterate over the tuples
('xyz', '5,00%'), ('abc', '50,00%'), ('ghf', '2,50%'). Is that correct?</p>
<p>But I don't understand how your code produces any results, since you are searching for <code><a></code> tags.</p>
<p>Instead you should iterate over the <code>&l... | 0 | 2016-07-15T12:54:33Z | [
"python",
"string",
"beautifulsoup"
] |
Python Beautiful Soup find string and extract following string | 38,395,751 | <p>I am programming a web crawler with the help of beautiful soup.I have the following html code:</p>
<pre><code><tr class="odd-row">
<td>xyz</td>
<td class="numeric">5,00%</td>
</tr>
<tr class="even-row">
<td>abc</td>
<... | 0 | 2016-07-15T12:08:05Z | 38,403,278 | <p>Once you find the correct <em>td</em>which I presume is what you meant to have in place of <em>a</em> then get the next sibling with the class you want:</p>
<pre><code>h = """<tr class="odd-row">
<td>xyz</td>
<td class="numeric">5,00%</td>
</tr>
<tr class="... | 0 | 2016-07-15T18:52:51Z | [
"python",
"string",
"beautifulsoup"
] |
Display result of multi index array groupby in pandas dataframe | 38,395,789 | <p>I have a data frame which looks like:</p>
<pre><code> D Type Value
0 1 A 2
1 1 B 4
2 2 C 1
3 1 A 1
</code></pre>
<p>I want to group by D and Type and sum the values.</p>
<pre><code>data=df.groupby(['D','Ty... | 2 | 2016-07-15T12:10:30Z | 38,396,182 | <p><strong>UPDATE:</strong></p>
<pre><code>r = df.pivot_table(index=['D'], columns='Type', aggfunc='sum').reset_index()
r.columns = [tup[1] if tup[1] else tup[0] for tup in r.columns]
r.to_csv('c:/temp/out.csv', index=False)
</code></pre>
<p>Result:</p>
<pre><code>D,A,B,C
1,3.0,4.0,
2,,,1.0
</code></pre>
<p><strong... | 1 | 2016-07-15T12:30:36Z | [
"python",
"pandas",
"dataframe"
] |
Django get_or_create failed with multiprocessing.Pool | 38,395,914 | <p>This is my project setup, using standard Django startproject command with a single app:</p>
<pre><code>Python 3.5.1
Django 1.9.7
PostgreSQL 9.5.3
Ubuntu 16.04
</code></pre>
<p>The app's models.py defines 2 models:</p>
<pre><code>from django.db import models
class A(models.Model):
n = models.PositiveIntegerFi... | 0 | 2016-07-15T12:16:13Z | 38,396,426 | <p>This behavior is explained in the <a href="https://docs.djangoproject.com/en/1.9/ref/models/querysets/#get-or-create" rel="nofollow">documentation for <code>get_or_create()</code></a>:</p>
<blockquote>
<p>This method is atomic assuming correct usage, correct database configuration, and correct behavior of the und... | 0 | 2016-07-15T12:42:47Z | [
"python",
"django",
"postgresql",
"multiprocessing"
] |
Are datetime timestamps updated after pickling? | 38,395,920 | <p>I'm creating a timestamp using datetime.date.today().day. Later in the code, this one shall be compared to another (current) timestamp, but just on the day-level: "If the current day is not the day of the former timestamp, do stuff".</p>
<p>To do this, I'm saving the first timestamp using pickle. Now I wonder, if t... | 1 | 2016-07-15T12:16:32Z | 38,396,115 | <p>The method <code>datetime.datetime.today()</code> <em>creates</em> a new <code>datetime.datetime</code> object of the current moment. The object itself doesn't know how it was created, i.e. neither the function nor the function's intention. It only know when it was created, and this is what will be stored.</p>
<p>I... | 3 | 2016-07-15T12:27:22Z | [
"python",
"pickle"
] |
Are datetime timestamps updated after pickling? | 38,395,920 | <p>I'm creating a timestamp using datetime.date.today().day. Later in the code, this one shall be compared to another (current) timestamp, but just on the day-level: "If the current day is not the day of the former timestamp, do stuff".</p>
<p>To do this, I'm saving the first timestamp using pickle. Now I wonder, if t... | 1 | 2016-07-15T12:16:32Z | 38,396,371 | <p>It doesn't autoupdate after loading. To demonstrate it, check this small example:</p>
<pre><code>import pickle
import datetime
today1 = datetime.datetime.today()
pickle.dump(today1, open('today','wb') )
sleep(5)
today2 = pickle.load(open('today','r'))
# today1 => datetime.datetime(2016, 7, 15, 18, 6, 6, ... | 2 | 2016-07-15T12:40:11Z | [
"python",
"pickle"
] |
Issue in saving figure in python | 38,396,008 | <p>I am new to Python. I am trying to save the figure but I am unable to do so properly. My code is </p>
<pre><code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
dataFilePath = 'file.txt';
data=pd.read_csv(dataFilePath, delim_whitespace=True, skipinitialspace=True);
I = data['I'];
A = data['... | 0 | 2016-07-15T12:21:10Z | 38,396,636 | <p>In my application setting the size of the figure using a command such as:
plt.figure(1).set_size_inches(10,12), to adjust the aspect ratio helped.</p>
| -1 | 2016-07-15T12:51:38Z | [
"python",
"matplotlib"
] |
Draw individual components in networkx | 38,396,040 | <p>I'm trying to draw just the largest components in networkx.</p>
<p>I've seen this <a href="http://stackoverflow.com/questions/26105764/how-do-i-get-the-giant-component-of-a-networkx-graph">How do I get the giant component of a NetworkX graph?</a> so can get the largest component(s). But having trouble working out h... | 0 | 2016-07-15T12:23:16Z | 38,418,083 | <p>Here's an example that plots the largest <code>n</code> with <code>n=10</code>. </p>
<pre><code>import matplotlib.pyplot as plt
import networkx as nx
G=nx.fast_gnp_random_graph(1000,0.002)
n=10
largest_components=sorted(nx.connected_component_subgraphs(G), key=len, reverse=True)[:n]
for index,component in enumerat... | 1 | 2016-07-17T05:07:32Z | [
"python",
"networkx"
] |
Atom not ignoring *.pyc files added to ignore list | 38,396,092 | <p>I've added <code>*.pyc</code> to the ignored names in the settings but they're still visible in the tree view. Below is my config file:</p>
<pre><code> "*":
core:
disabledPackages: [
"terminal-plus"
"atom-terminal"
"term3"
]
ignoredNames: [
".git"
".hg"
".svn"
... | 0 | 2016-07-15T12:26:40Z | 38,396,175 | <p>See the discussion on the resolved issue here:</p>
<p><a href="https://github.com/atom/tree-view/issues/50" rel="nofollow">https://github.com/atom/tree-view/issues/50</a></p>
| 1 | 2016-07-15T12:30:15Z | [
"python",
"atom-editor"
] |
Matplotlib: Plot something new in an axis upon key press | 38,396,318 | <p>Each time the user presses a key on the keyboard, a new plot should be drawn. The example below uses just a random plot, in reality, I'll combine it with a statemachine that calls a different <code>plot()</code> function on each press.</p>
<p>I have the short minimal code with a random plot:</p>
<pre><code>fig = p... | 1 | 2016-07-15T12:37:47Z | 38,396,781 | <p>This is my code, I figured it has to do with the plt.figure(1), because if I do that in the plot method it does generate a new graph everytime I press a key.</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure(1)
ax1 = fig.add_subplot(111, aspect='equal')
def plot(e):
fig = plt.... | 0 | 2016-07-15T12:59:32Z | [
"python",
"matplotlib",
"plot"
] |
Matplotlib: Plot something new in an axis upon key press | 38,396,318 | <p>Each time the user presses a key on the keyboard, a new plot should be drawn. The example below uses just a random plot, in reality, I'll combine it with a statemachine that calls a different <code>plot()</code> function on each press.</p>
<p>I have the short minimal code with a random plot:</p>
<pre><code>fig = p... | 1 | 2016-07-15T12:37:47Z | 38,398,417 | <p>add following line to the function:</p>
<pre><code>fig.canvas.draw_idle()
</code></pre>
| 0 | 2016-07-15T14:17:42Z | [
"python",
"matplotlib",
"plot"
] |
Twython 404 on create_list_members method | 38,396,400 | <p>I have the following code, which gets a list of ids for a users friends on Twitter. These ids as then passed to a newly created list but I'm getting the following error:</p>
<pre><code>Traceback (most recent call last):
File "twitter.py", line 34, in <module>
twitter.create_list_members(list_id=list_id,... | 0 | 2016-07-15T12:41:24Z | 38,922,673 | <p>Add a sleep of one second after creating the list. The page doesn't exist because the list hasn't finished being created.</p>
<pre><code># create list and return list id
list_id = twitter.create_list(name=user)['id']
print list_id
time.sleep(1) # Sleep one second
# get users following ids
following_ids = twitter... | 1 | 2016-08-12T16:30:18Z | [
"python",
"twitter",
"twython"
] |
Tkinter clear a message widget | 38,396,427 | <p>I am creating a function in which I output a text file's contents to a 'Message' widget in Tkinter. The user selects an option which corresponds to a text file, and presses 'OK'.</p>
<p>The problem I'm having is that I do not know how to clear the message box after selecting two consecutive options. </p>
<p>QUESTI... | 1 | 2016-07-15T12:42:48Z | 38,401,112 | <p>Your problem is that you created the <code>about_message</code> widget inside the selection function, so you recreate one each time you call the function. I suggest you to create the widget outside the selection function so that you can do <code>about_message.configure(text="new text")</code>. Here is the code:</p>
... | 1 | 2016-07-15T16:35:01Z | [
"python",
"python-3.x",
"tkinter"
] |
Error in view - 'float' object has no attribute 'label' | 38,396,572 | <p>I am getting error in my view during template rendering </p>
<blockquote>
<p>'float' object has no attribute 'label'</p>
</blockquote>
<p>It has to do with this line I just added a float conversion </p>
<pre><code> form.fields['quantity_order'] = float(bom.quantity) * float(quantity)
</code></pre>
<p>(I added... | 0 | 2016-07-15T12:49:04Z | 38,396,952 | <p>I will answer what worked for me</p>
<pre><code>data_dict = { 'quantity_order': float(bom.quantity) * float(quantity)}
form = Production_orderForm(data_dict)
</code></pre>
| 0 | 2016-07-15T13:08:31Z | [
"python",
"django"
] |
Mysql/python fetchall() can't handle result because it is too big | 38,396,835 | <p>I have a table of 2,760,000 rows. In mysqlworkbench, it takes 36 sec to select * from original table. </p>
<p>I want to create another table using this existing table in python (using <strong>my_func()</strong> to convert values).</p>
<p>But, when I run it in the command line, it never seems to finish.</p>
<pre><... | 0 | 2016-07-15T13:02:42Z | 38,397,181 | <p>Per the <a href="http://mysql-python.sourceforge.net/MySQLdb.html#some-mysql-examples" rel="nofollow">documentation</a>:</p>
<blockquote>
<p>db.store_result() returns the entire result set to the client
immediately. If your result set is really large, this could be a
problem. One way around this is to add a L... | 1 | 2016-07-15T13:18:44Z | [
"python",
"mysql",
"database",
"bigdata"
] |
Mysql/python fetchall() can't handle result because it is too big | 38,396,835 | <p>I have a table of 2,760,000 rows. In mysqlworkbench, it takes 36 sec to select * from original table. </p>
<p>I want to create another table using this existing table in python (using <strong>my_func()</strong> to convert values).</p>
<p>But, when I run it in the command line, it never seems to finish.</p>
<pre><... | 0 | 2016-07-15T13:02:42Z | 38,397,196 | <p>Use cursor as iterator (without calling <code>fetchall</code>):</p>
<pre><code>sql = "SELECT ID, Eye, Values FROM my_original_table"
curQuery.execute(sql)
for row in curQuery:
# ...
</code></pre>
<p>above is equivalent to process a query using while loop with <code>fetchone</code>:</p>
<pre><code>curQuery.ex... | 1 | 2016-07-15T13:19:36Z | [
"python",
"mysql",
"database",
"bigdata"
] |
Python Tkinter TTK Separator With Label | 38,396,900 | <p>I am trying to create a custom widget that includes a separator behind a label. I would like the separator to stretch out behind the label to each side of the window (using grid).
I tried to create this myself, but I couldn't get the separator to stick to the edges.</p>
<p><a href="http://i.stack.imgur.com/6qz7g.pn... | 2 | 2016-07-15T13:06:11Z | 38,400,404 | <p>The only problem with your code is that you haven't called <code>grid_columnconfigure</code> to tell tkinter what to do with extra space. Since you didn't tell the inner frame what to do with extra space, it left it blank. When the widget is placed in its parent and expands, your inner widgets weren't using the extr... | 1 | 2016-07-15T15:54:15Z | [
"python",
"tkinter",
"label",
"separator"
] |
Find Divisible Sum Pairs in an array in O(n) time | 38,396,908 | <p>You are given an array of <code>n</code> integers <code>a0, a1, .. an</code> , and a positive integer <code>k</code>. Find and print the number of pairs <code>(i,j)</code> where and <code>i+j</code> is evenly divisible by <code>k</code> (Which is <code>i+j % k == 0</code>). This problem has been taken from <a href="... | -1 | 2016-07-15T13:06:27Z | 38,397,523 | <p>You have <code>n * (n - 1) / 2</code> pairs because everyone (<code>n</code>) can be paired with everyone else (<code>n-1</code>); but since the order doesn't matter we avoid counting mirror pairs by dividing by two. </p>
<p>Also remainders over the same quotient are summed when the numerators are summed, but the r... | 1 | 2016-07-15T13:36:46Z | [
"python",
"algorithm",
"bucket",
"mod"
] |
Find Divisible Sum Pairs in an array in O(n) time | 38,396,908 | <p>You are given an array of <code>n</code> integers <code>a0, a1, .. an</code> , and a positive integer <code>k</code>. Find and print the number of pairs <code>(i,j)</code> where and <code>i+j</code> is evenly divisible by <code>k</code> (Which is <code>i+j % k == 0</code>). This problem has been taken from <a href="... | -1 | 2016-07-15T13:06:27Z | 38,397,774 | <p>I translate the C code...</p>
<pre><code>using namespace std;
int main(){
int n;
int k;
cin >> n >> k;
int a[n];
int m[k];
for(int i=0; i<k; i++)
m[i]=0;
for(int i = 0; i < n; i++){
cin >> a[i];
m[a[i]%k]++;
}
int sum=0;
sum+=(m[0]*(m[... | 2 | 2016-07-15T13:48:41Z | [
"python",
"algorithm",
"bucket",
"mod"
] |
Custom tagger NLTK 3 | 38,397,115 | <p>I am working with nltk's default tagger to get a POS tag of the word but I am not getting the expected results:</p>
<pre><code>>>> nltk.pos_tag(nltk.tokenize.word_tokenize("I want a watch"))
[('I', 'PRP'), ('want', 'VBP'), ('a', 'DT'), ('watch', 'NN')]
>>> nltk.pos_tag(nltk.tokenize.word_tokenize(... | 2 | 2016-07-15T13:15:59Z | 38,400,112 | <p>NLTK <code>pos_tag</code> uses the <a href="https://github.com/nltk/nltk/blob/develop/nltk/tag/__init__.py#L110" rel="nofollow"><code>PerceptronTagger</code></a> by default. But you can use other <em>taggers</em> which have been trained on their respective datasets. </p>
<p>In the following case, the <a href="http:... | 1 | 2016-07-15T15:40:19Z | [
"python",
"python-3.x",
"nlp",
"nltk"
] |
Cannot upgrade (install latest) version of azure pip module | 38,397,140 | <p>I try to install latest (<a href="https://pypi.python.org/pypi/azure/2.0.0rc5" rel="nofollow">2.0.0rc5</a>) version of azure pip package, but pip insist to install 1.0.3.</p>
<pre><code># pip install --upgrade azure
Requirement already up-to-date: azure in /usr/local/lib/python2.7/site-packages
[...]
</code></pre>
... | 0 | 2016-07-15T13:17:12Z | 38,397,481 | <p>I found the <em>pre</em> option and <code>pip install --upgrade azure --pre</code> works. </p>
<p><code>pip show azure
[...]
Metadata-Version: 2.0
Name: azure
Version: 2.0.0rc5
Summary: Microsoft Azure Client Libraries for Python
[...]</code></p>
<p>And Ansible suggestion doesn't (<a href="https://docs.ansible... | 0 | 2016-07-15T13:34:51Z | [
"python",
"azure",
"pip"
] |
Iterate over all items in json object | 38,397,285 | <p>After loading json from a file via <code>data = json.load(fp)</code> I want to iterate over all items that were in json, excluding of course all special Python symbols.
How is this done properly?</p>
| -5 | 2016-07-15T13:24:16Z | 38,397,347 | <p><code>data</code> should be an ordinary collection at this point, so you'd iterate over it the same way you'd iterate over any other list/dict/whatever. The fact that it came from <code>load</code> doesn't incur any extra requirements on your part.</p>
<p>Here's an example that uses <code>loads</code>, which is sim... | 2 | 2016-07-15T13:28:01Z | [
"python",
"json",
"python-3.x",
"python-3.5"
] |
What's wrong with this python decorator? | 38,397,319 | <p>I have the following decorator that should handle "no network" exceptions:</p>
<pre><code>class NetworkError(RuntimeError):
pass
def reTryer(max_retries=5, timeout=5):
def wraper(func):
request_exceptions = (
requests.exceptions.Timeout,
requests.exceptions.ConnectionError,
... | 2 | 2016-07-15T13:26:43Z | 38,398,097 | <p>To answer your question:</p>
<p>As the implementation seems correct, I can imagine some things which could be the cause of the problem.</p>
<p>Mainly I think about the decorated function never returning, throwing a different exception than you had in focus, or even returning normal.</p>
<p>You could test this wit... | 1 | 2016-07-15T14:03:42Z | [
"python",
"python-3.x",
"exception",
"networking"
] |
Python need third quote style for '<a href="{{ url_for('index') }}"> index </a>' | 38,397,398 | <p>Simple question but I never had this issue and right now I am really puzzled.</p>
<p>For my flask google maps function I need to set an infobox which should be clickable and redirects the user to the room which has been clicked.</p>
<p>For this I use:</p>
<pre><code>infobox=['<a href="{{ url_for('index') }}"&g... | 0 | 2016-07-15T13:30:34Z | 38,397,471 | <p>If you're simply asking how to escape the apostrophes you want to include your string, then this should work:</p>
<pre><code>infobox=['<a href="{{ url_for(\'index\') }}"> index </a>']
</code></pre>
<p>Alternatively, with python, you can also use three apostrophes or quotes to enable easier input of str... | 1 | 2016-07-15T13:34:12Z | [
"python"
] |
Alternatives to numpy einsum | 38,397,399 | <p>When I calculate third order moments of an matrix <code>X</code> with <code>N</code> rows and <code>n</code> columns, I usually use <code>einsum</code>:</p>
<pre><code>M3 = sp.einsum('ij,ik,il->jkl',X,X,X) /N
</code></pre>
<p>This works usually fine, but now I am working with bigger values, namely <code>n = 120... | 6 | 2016-07-15T13:30:34Z | 38,400,501 | <p>Note that calculating this will need to do at least ~n<sup>3</sup> × N = 173 billion operations (not considering symmetry), so it will be slow unless numpy has access to GPU or something. On a modern computer with a ~3 GHz CPU, the whole computation is expected to take about 60 seconds to complete, assuming no... | 4 | 2016-07-15T15:59:03Z | [
"python",
"numpy",
"matrix"
] |
find range of values with reduceByKey using spark in one operation | 38,397,442 | <p>I am trying to have the output of my reduceByKey function, using pyspark, to be the range of the integers passed through with respect to the key.</p>
<p>I try to make a custom function: </p>
<pre><code>def _range(x,y):
return [max(x,y), min(x,y)]
data2 = data_.map(lambda x: (x[u'driverId'] + ',' + x[u'afh... | 1 | 2016-07-15T13:32:44Z | 38,398,669 | <p>A correct approach here is <code>combineByKey</code> defined as follows:</p>
<pre><code>def seq_op(acc, x):
return (min(x, acc[0]), max(x, acc[1]))
def comb_op(acc1, acc2):
return (min(acc1[0], acc2[0]), max(acc1[1], acc2[1]))
(pairs
.aggregateByKey((sys.float_info.max, sys.float_info.min), seq_op, co... | 0 | 2016-07-15T14:28:51Z | [
"python",
"apache-spark",
"mapreduce",
"pyspark",
"rdd"
] |
P4 Trigger, %args% parameter is empty | 38,397,445 | <p>I create perforce trigger and I like to get <code>%args%</code> value.</p>
<p>I can't get <code>%args%</code> value.</p>
<p><a href="https://www.perforce.com/perforce/r14.2/manuals/p4sag/chapter.scripting.html#scripting.triggers" rel="nofollow">For more informatin go perforce doc page.</a></p>
<p>This is may trig... | 0 | 2016-07-15T13:33:06Z | 38,406,468 | <p>(Assuming you've got a server >= 2014.1 like Bryan mentioned.)</p>
<p>How did you submit and what do you expect in %args% ?</p>
<p>For example, if I submit with:</p>
<pre><code>p4 submit -r -dTest
</code></pre>
<p>The script will see %args% as "-r -dTest".</p>
<p>Since %args% can be (empty) you might want it la... | 0 | 2016-07-16T00:02:14Z | [
"python",
"triggers",
"perforce"
] |
Getting the value of a previous excel cell in python | 38,397,448 | <p>So given a cell I want to know the value in which the cell right before it (same row, previous column) has.
Here is my code and I thought it was working but...: </p>
<pre><code>def excel_test(col_num, sheet_object):
for cell in sheet_object.columns[col_number]:
prev_col = (column_index_from_string(cell.colu... | 0 | 2016-07-15T13:33:19Z | 38,400,250 | <p>You should look at the <code>cell.offset()</code> method.</p>
| 0 | 2016-07-15T15:46:30Z | [
"python",
"excel",
"openpyxl",
"attributeerror"
] |
Python - For loop isn't working as expected | 38,397,473 | <p>I have a dictionary that looks like this</p>
<pre><code>>>> testd
{'0CD7D6FE4A6411E61693005056AA00F2':
[
{'USERNAME': 'abc', 'REPORT': 'NEW', 'CLASS': 'IR', 'CREATED': '15/07/2016 08:13:45.783199', 'TRANSACTION_TYPE': 'Elec', 'STATE': 'RQ', 'REPORT_TYPE': 'RT', 'MESSAGE_TYPE': None, 'ID': '37A8E019BB90637... | -1 | 2016-07-15T13:34:18Z | 38,397,696 | <p>You now have fast lookup by <code>VID</code>. What you want is lookup by <code>VID</code> and then <code>ID</code> which implies double nesting.</p>
<p>You can do it using one more nesting of the existing mapping:</p>
<pre><code>>>> from collections import defaultdict
>>> by_vid_by_id = dict(test... | 2 | 2016-07-15T13:45:36Z | [
"python",
"dictionary",
"lambda"
] |
Python - For loop isn't working as expected | 38,397,473 | <p>I have a dictionary that looks like this</p>
<pre><code>>>> testd
{'0CD7D6FE4A6411E61693005056AA00F2':
[
{'USERNAME': 'abc', 'REPORT': 'NEW', 'CLASS': 'IR', 'CREATED': '15/07/2016 08:13:45.783199', 'TRANSACTION_TYPE': 'Elec', 'STATE': 'RQ', 'REPORT_TYPE': 'RT', 'MESSAGE_TYPE': None, 'ID': '37A8E019BB90637... | -1 | 2016-07-15T13:34:18Z | 38,397,730 | <p>If you want a new dictionary you can try this</p>
<pre><code>newd = {}
for key,value in testd.iteritems():
newd[key] = [val for val in value if val['ID'] == testld[key]]
</code></pre>
<p>It'll throw a KeyError if you have a key in testd that isn't in testld, but that seems like something that shouldn't be happ... | 0 | 2016-07-15T13:47:01Z | [
"python",
"dictionary",
"lambda"
] |
How to assign ranks to records in a spark dataframe based on some conditions? | 38,397,552 | <p>Given a dataframe :</p>
<pre><code>+-------+-------+
| A | B |
+-------+-------+
| a| 1|
+-------+-------+
| b| 2|
+-------+-------+
| c| 5|
+-------+-------+
| d| 7|
+-------+-------+
| e| 11|
+-------+-------+
</code></pre>
<p>I want to assign ranks to... | 3 | 2016-07-15T13:38:09Z | 38,399,373 | <p>A SQL solution would be </p>
<pre><code>select a,b,1+sum(col) over(order by a) as rnk
from
(
select t.*
,case when b - lag(b,1,b) over(order by a) <= 2 then 0 else 1 end as col
from t
) x
</code></pre>
<p>The solution assumes the ordering is based on column <code>a</code>. </p>
<p><a href="http://rextester.co... | 1 | 2016-07-15T15:01:16Z | [
"python",
"sql",
"dataframe",
"pyspark",
"rank"
] |
Can I use Prefetch_related to prefetch more than just one model? | 38,397,553 | <p>In my view I a prefetching related data in order to read it later from the template </p>
<pre><code>soproduct = SOproduct.objects.select_related('product__material').prefetch_related(
Prefetch(
'product__material__bomversion_set',
queryset=BOMVersion.objects.default().active(),
... | 0 | 2016-07-15T13:38:15Z | 38,397,978 | <p>Yes, just add comments between the entries. </p>
<p>I have never used the Prefetch object before, Just use prefetch_related as follows:</p>
<pre><code>soproduct = SOproduct.objects.select_related('product__material').prefetch_related(
'product__material__bomversion_set',
'second_t... | 1 | 2016-07-15T13:57:37Z | [
"python",
"django"
] |
Find and count equal dicts inside a list | 38,397,557 | <p>I have a list with multiple dicts in, I need to check which dicts are repeated and create a new list with only a single occurrence of each but with the amount of repeated elements in the first list.</p>
<p>For example:</p>
<p>I have that list:</p>
<pre><code>[{'a': 123, 'b': 1234, 'c': 'john', 'amount': 1},
{'a'... | 1 | 2016-07-15T13:38:33Z | 38,397,748 | <p>Here is an option using pandas by which we can concatenate the dictionary into a data frame, and then we can groupby column a, b and c and calculate the sum of amount. And if we want a dictionary back, pandas data frame has a built in <code>to_dict()</code> function. Specifying the parameter as <code>index</code>, w... | 3 | 2016-07-15T13:47:42Z | [
"python",
"list",
"dictionary",
"count",
"repeat"
] |
What should my Python program include in order to use compiled Haxe object? | 38,397,593 | <p>I know, It's a very trivial question, but I haven't found any example, so I am stucked now.</p>
<p>I have a very simple Haxe object. This is the content of the file <code>Thing.hx</code>:</p>
<pre><code>@Persistent
class Thing {
@Property
public var thingName: String;
}
</code></pre>
<p>I can compile it:</p>
... | 1 | 2016-07-15T13:40:46Z | 38,430,158 | <p>Finally, I've figured out that I need to add some <code>haxe</code> compiler option to include the missing methods.</p>
<p>First I needed to install <code>nape</code>:</p>
<pre><code>haxelib install nape
</code></pre>
<p>Then compile:</p>
<pre><code>haxe -lib nape Thing.hx -python Thing.py --macro "include('nape... | 1 | 2016-07-18T06:46:19Z | [
"python",
"python-3.x",
"haxe"
] |
How to change the base class in Python | 38,397,610 | <p>Say I have following</p>
<pre><code>Class A(object):
base Functions
Class B (A):
some useful functions
Class C(object)
req base functions
</code></pre>
<p>Now I want to create a class which has all the functions from B but instead of functions from A refers to functions from C.
Something like</p>
<pr... | 0 | 2016-07-15T13:41:41Z | 38,398,298 | <p>Change the <code>__bases__</code> attribute of <code>B</code> class.</p>
<p>Well, it's ugly but it works:</p>
<pre><code>class A(object):
def f(self):
print("A.f()")
class B (A):
def g(self):
print("B.g()", end=": ")
super(B, self).f()
class C(object):
def f(self):
pri... | 0 | 2016-07-15T14:13:10Z | [
"python",
"python-2.7",
"inheritance"
] |
Include none python files to module | 38,397,656 | <p>I'm writing my own module to ansible and part of the code can't be in python as the software I'm working against does not have a python api. It does support groovy so I included a groovy script but in the module directory but when i run the module i notice that ansible copies all python files in the module to /tmp/a... | 0 | 2016-07-15T13:43:40Z | 38,400,122 | <p>From <a href="http://docs.ansible.com/ansible/developing_modules.html#conventions-recommendations" rel="nofollow">Developing Modules</a>:</p>
<blockquote>
<p>Modules must be self-contained in one file to be auto-transferred by ansible.</p>
</blockquote>
<p>Why not use groovy-script as a module?</p>
<p>Put <code... | 1 | 2016-07-15T15:40:40Z | [
"python",
"ansible"
] |
Retrieve top n in each group of a DataFrame in pyspark | 38,397,796 | <p>There's a DataFrame in pyspark with data as below:</p>
<pre><code>user_id object_id score
user_1 object_1 3
user_1 object_1 1
user_1 object_2 2
user_2 object_1 5
user_2 object_2 2
user_2 object_2 6
</code></pre>
<p>What I expect is returning 2 records in each group with the same user_id, which need to ... | 1 | 2016-07-15T13:49:33Z | 38,398,563 | <p>I believe you need to use <a href="https://databricks.com/blog/2015/07/15/introducing-window-functions-in-spark-sql.html" rel="nofollow">window functions</a> to attain the rank of each row based on <code>user_id</code> and <code>score</code>, and subsequently filter your results to only keep the first two values.</p... | 2 | 2016-07-15T14:24:11Z | [
"python",
"apache-spark",
"pyspark",
"apache-spark-sql",
"spark-dataframe"
] |
Python Performance - for loops with method without looped variables | 38,397,868 | <p>I have a doubt in performance and can't find how python behaves in each of these cases:</p>
<pre><code>def something(object):
if object== 'something':
return 1
else:
return 0
</code></pre>
<p>Option 1:</p>
<pre><code>def something_bigger(list, object):
total= 0
for item in list:
... | 1 | 2016-07-15T13:52:39Z | 38,401,393 | <p>No. Python is not compiled the way Java or C# applications (for example) are. A line of code is only evaluated right as it's executed.</p>
<p>This question I asked a few weeks ago can really detail one of the
core differences in Python:
<a href="http://stackoverflow.com/questions/37756081/why-doesnt-python-spot-er... | 0 | 2016-07-15T16:51:15Z | [
"python"
] |
Can't write and save a video file using OpenCV and Python | 38,397,964 | <p>I'm trying to process frames from a video stream, and it as a new video.</p>
<p>This is what I'm doing : </p>
<p><code>fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('Videos/output.mp4',fourcc, fps, (1080,1080))</code></p>
<p>I keep getting : </p>
<p><code>OpenCV: FFMPEG: tag 0x44495658/'XVID' is... | 0 | 2016-07-15T13:57:17Z | 39,000,182 | <p>Define the codec and create VideoWriter object like this</p>
<pre><code>fourcc = cv2.VideoWriter_fourcc(*'MPEG')
out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480))
</code></pre>
| -1 | 2016-08-17T15:01:39Z | [
"python",
"opencv"
] |
Assign user input to a variable in Python | 38,398,029 | <p>I am having some problem when trying to get the input text and assign them to variable in Python. Here are my code:</p>
<pre><code>#!/usr/bin/python3
from tkinter import *
fields = 'Last Name', 'First Name', 'Job', 'Country'
def fetch(entries):
for entry in entries:
field = entry[0]
text = entry[1... | 0 | 2016-07-15T13:59:58Z | 38,400,518 | <p>Make <code>entries</code> a global variable. If there are more than 4 fields in <code>entries</code>, maybe instead of using a nested list where each item has 2 fields (a field, and text), you should make each item hold the four fields (first name, last name, job, country). This way each entry in <code>entries</code... | 0 | 2016-07-15T16:00:00Z | [
"python",
"variables",
"textbox"
] |
Python List of Strings to Tuple Pairs | 38,398,063 | <p>I am having some difficulty coming up with an efficient way of taking a list of strings and converting it to tuple pairs. I have a list similar to:</p>
<pre><code>listOfNames = ['red-l','blue-l','green-s','red-s','blue-s']
</code></pre>
<p>Every color in this example (red, blue, and green) has either a '-l' or '-... | 1 | 2016-07-15T14:01:46Z | 38,398,179 | <p>Check out the <code>itertools.product()</code> function. This returns the cartesian product of two lists. In your case you could do,</p>
<pre><code>from itertools import product
l_names = ['red-l', 'blue-l']
s_names = ['red-s', 'blue-s', 'green-s']
tupleOfNames = list(product(l_names, s_names))
</code></pre>
| -3 | 2016-07-15T14:06:53Z | [
"python",
"list",
"tuples"
] |
Python List of Strings to Tuple Pairs | 38,398,063 | <p>I am having some difficulty coming up with an efficient way of taking a list of strings and converting it to tuple pairs. I have a list similar to:</p>
<pre><code>listOfNames = ['red-l','blue-l','green-s','red-s','blue-s']
</code></pre>
<p>Every color in this example (red, blue, and green) has either a '-l' or '-... | 1 | 2016-07-15T14:01:46Z | 38,398,384 | <p>A possible solution, We can sort the list firstly and then groupby the color part of each term and transform each group into a tuple, if it contains only one element insert a None in the tuple:</p>
<pre><code>import re
from itertools import groupby
li = []
listOfNames.sort()
for k, g in groupby(listOfNames, lambda... | 3 | 2016-07-15T14:16:30Z | [
"python",
"list",
"tuples"
] |
Python List of Strings to Tuple Pairs | 38,398,063 | <p>I am having some difficulty coming up with an efficient way of taking a list of strings and converting it to tuple pairs. I have a list similar to:</p>
<pre><code>listOfNames = ['red-l','blue-l','green-s','red-s','blue-s']
</code></pre>
<p>Every color in this example (red, blue, and green) has either a '-l' or '-... | 1 | 2016-07-15T14:01:46Z | 38,398,393 | <p>I wrote this function which is far from perfect, but delivers the result you wish for:</p>
<pre><code> def tupleofnames(listofnames):
result = []
colors = set([x[:-2] for x in listOfNames])
for c in colors:
if c+"-l" in listofnames:
if c+'-s' in list... | 0 | 2016-07-15T14:16:49Z | [
"python",
"list",
"tuples"
] |
Python List of Strings to Tuple Pairs | 38,398,063 | <p>I am having some difficulty coming up with an efficient way of taking a list of strings and converting it to tuple pairs. I have a list similar to:</p>
<pre><code>listOfNames = ['red-l','blue-l','green-s','red-s','blue-s']
</code></pre>
<p>Every color in this example (red, blue, and green) has either a '-l' or '-... | 1 | 2016-07-15T14:01:46Z | 38,398,479 | <pre><code>listOfNames = ['red-l','blue-l','green-s','red-s','blue-s']
l_list = [a[:-2] for a in filter(lambda x:x[-1]=='l',listOfNames)]
s_list = [a[:-2] for a in filter(lambda x:x[-1]=='s',listOfNames)]
s = {a[:-2] for a in listOfNames}
tuplesOfNames = [tuple([c+'-l' if c in l_list else None,c+'-s' if c in s_list els... | 0 | 2016-07-15T14:20:38Z | [
"python",
"list",
"tuples"
] |
Python List of Strings to Tuple Pairs | 38,398,063 | <p>I am having some difficulty coming up with an efficient way of taking a list of strings and converting it to tuple pairs. I have a list similar to:</p>
<pre><code>listOfNames = ['red-l','blue-l','green-s','red-s','blue-s']
</code></pre>
<p>Every color in this example (red, blue, and green) has either a '-l' or '-... | 1 | 2016-07-15T14:01:46Z | 38,399,453 | <p>I think a nice (and perhaps better) solution is:</p>
<pre><code>from collections import defaultdict
d = defaultdict(list)
listOfNames = ['red-l','blue-l','green-s','red-s','blue-s']
# Go over the list and remember for each color the entry
for s in listOfNames:
d[s[:-2]].append(s[-1])
# Go over the colors and pr... | 0 | 2016-07-15T15:05:47Z | [
"python",
"list",
"tuples"
] |
gsutil config -a. Which key to use? | 38,398,066 | <p>There are so many keys to be created for use with Google Compute Cloud.
I'm trying to create .boto file using gsutil and it's asking for "Google access key ID". My goal is to script access to "Google Cloud Storage" using Python.</p>
<p>So, when gsutil is asking for "Google access key ID" - is it the one from </p>
... | 2 | 2016-07-15T14:01:54Z | 38,399,516 | <p>gsutil config -a lets you use HMAC-style access keys. These aren't service account keys; if you want to use a service account you should use gsutil config -e. But if you really did want to use HMAC keys, you can get them from <a href="https://console.cloud.google.com/storage/settings" rel="nofollow">https://console.... | 2 | 2016-07-15T15:09:37Z | [
"python",
"google-cloud-storage",
"boto",
"gsutil"
] |
gsutil config -a. Which key to use? | 38,398,066 | <p>There are so many keys to be created for use with Google Compute Cloud.
I'm trying to create .boto file using gsutil and it's asking for "Google access key ID". My goal is to script access to "Google Cloud Storage" using Python.</p>
<p>So, when gsutil is asking for "Google access key ID" - is it the one from </p>
... | 2 | 2016-07-15T14:01:54Z | 38,399,698 | <p>It's second option</p>
<ul>
<li>Credentials->OAuth 2.0 client IDs</li>
</ul>
<p>For <code>Cloud Storage API</code> access I have to use <strong>OAuth2</strong> because I access user data.</p>
<p>If I had to access <code>Translate API</code> I'd use <strong>API Key</strong> because no user data access required.</... | 0 | 2016-07-15T15:18:26Z | [
"python",
"google-cloud-storage",
"boto",
"gsutil"
] |
Why I can't get callback via AJAX in Flask project? | 38,398,089 | <p>This program is based on Flask, it allows user to click 'LIKE' button to increase 1 like_count for the post.</p>
<p>with follows, I can not POST the 'postid' to '/like' function and can not get callback from it. Terminal shows TypeError: </p>
<blockquote>
<p>like() missing 1 required positional argument: 'postid... | 0 | 2016-07-15T14:03:10Z | 38,398,453 | <p>You're posting <code>postid</code> as form data, not as a url value. Remove the argument from the view signature and get the value from <code>request.form</code>.</p>
<pre><code>def like():
postid = request.form['postid']
</code></pre>
| 2 | 2016-07-15T14:19:11Z | [
"jquery",
"python",
"ajax",
"django",
"flask"
] |
pip freeze > requirements.txt including all system installed packages inside virtualenv | 38,398,154 | <p>Bit of backstory, I'm relatively new to Python and development in general and have stupidly been installing project specific packages as system packages. This is now causing me issues when trying to create requirements.txt files for specific projects, inside of virtualenvs.</p>
<p>For example, I've installed Kivy s... | 0 | 2016-07-15T14:06:00Z | 38,398,556 | <p>You can freeze just your local packages in each virtualenv by using the <code>-l</code> (or <a href="https://pip.pypa.io/en/stable/reference/pip_freeze/#cmdoption-l" rel="nofollow"><code>--local</code></a>) parameter</p>
<pre><code>pip freeze --local > requirements.txt
</code></pre>
| 2 | 2016-07-15T14:23:47Z | [
"python",
"virtualenv"
] |
Python - Find name of a folder based on a part of it's name | 38,398,162 | <p>basically I have a structure like "myapp/installed_application_10101010/", however, the number of that folder will change regularly. </p>
<p>Therefore I need a way to find this folder everytime. Almost similar to how unix works when you press tab in the terminal, it'll autofill the rest of the name. </p>
| -1 | 2016-07-15T14:06:16Z | 38,398,254 | <p>You could use the <a href="https://docs.python.org/3/library/glob.html" rel="nofollow">glob</a> module for this.</p>
<pre><code>import glob
possible_folders = glob.glob('myapp/installed_application_*/')
# returns ['myapp/installed_application_10101010/']
</code></pre>
<p>The method returns a list because there co... | 1 | 2016-07-15T14:11:03Z | [
"python"
] |
Display a time using a given timezone in Django | 38,398,172 | <p>I'm developing a Django app for logging dives and each dive has a datetime and a timezone in it. I'm using the django-timezone-field app for the timezone.</p>
<pre><code>class Dive(models.Model):
...
date_time_in = models.DateTimeField(default=timezone.now)
timezone = TimeZoneField(default=timezone.get_curren... | 0 | 2016-07-15T14:06:33Z | 38,402,212 | <p>Check your timezone setting in <code>settings.py</code></p>
| 0 | 2016-07-15T17:41:10Z | [
"python",
"django",
"datetime",
"timezoneoffset"
] |
Display a time using a given timezone in Django | 38,398,172 | <p>I'm developing a Django app for logging dives and each dive has a datetime and a timezone in it. I'm using the django-timezone-field app for the timezone.</p>
<pre><code>class Dive(models.Model):
...
date_time_in = models.DateTimeField(default=timezone.now)
timezone = TimeZoneField(default=timezone.get_curren... | 0 | 2016-07-15T14:06:33Z | 38,402,696 | <p>Do you have USE_TZ = true in your settings file? If you created your app using the djangoadmin-startproject command, it is set by default.</p>
<p>Also, I struggled with timezones at my last job but found that using pytz really helped. Have you tried that package yet?</p>
<p>EDIT: Ok man I may be way off, but since... | 0 | 2016-07-15T18:13:49Z | [
"python",
"django",
"datetime",
"timezoneoffset"
] |
Display a time using a given timezone in Django | 38,398,172 | <p>I'm developing a Django app for logging dives and each dive has a datetime and a timezone in it. I'm using the django-timezone-field app for the timezone.</p>
<pre><code>class Dive(models.Model):
...
date_time_in = models.DateTimeField(default=timezone.now)
timezone = TimeZoneField(default=timezone.get_curren... | 0 | 2016-07-15T14:06:33Z | 38,417,972 | <p>Sorry, I don't think I explained my problem very well. I finally figured this out, so I'll answer my own question.</p>
<p>1) turned out to be easy, Django have a template tag for displaying times in a given zone:</p>
<pre><code>{{ dive.date_time_in|timezone:dive.timezone|date:"Y-m-d H:i e" }}
</code></pre>
<p>For... | 0 | 2016-07-17T04:42:16Z | [
"python",
"django",
"datetime",
"timezoneoffset"
] |
Relative import inside project results in "SystemError: Parent module '' not loaded, cannot perform relative import" | 38,398,319 | <p>I am working on a project which has the following structure:</p>
<pre><code>project
âââ config.py
âââ modules
âââ a.py
</code></pre>
<p>According to <a href="https://www.python.org/dev/peps/pep-0328/#guido-s-decision" rel="nofollow">PEP 328</a> relative imports are possible.
However when I s... | 2 | 2016-07-15T14:13:50Z | 38,400,509 | <p>You can overcome this error by:</p>
<ol>
<li>create __init__.py in <strong>project</strong> and <strong>modules</strong> directory </li>
<li>run <strong>python -m project.modules.a</strong> in parent directory of <strong>project</strong></li>
</ol>
<p>See <a href="http://www.napuzba.com/story/import-error-relative... | -1 | 2016-07-15T15:59:40Z | [
"python",
"python-3.x",
"python-import",
"relative-import"
] |
Relative import inside project results in "SystemError: Parent module '' not loaded, cannot perform relative import" | 38,398,319 | <p>I am working on a project which has the following structure:</p>
<pre><code>project
âââ config.py
âââ modules
âââ a.py
</code></pre>
<p>According to <a href="https://www.python.org/dev/peps/pep-0328/#guido-s-decision" rel="nofollow">PEP 328</a> relative imports are possible.
However when I s... | 2 | 2016-07-15T14:13:50Z | 38,416,314 | <p>Relative imports can only work where the module was itself imported. Running that command in an interactive session has no parent module. Also, the current directory is implicitly search (thus treated like a package) and so <code>import a</code> from an interactive interpreter in that directory will have no parent m... | 0 | 2016-07-16T22:43:38Z | [
"python",
"python-3.x",
"python-import",
"relative-import"
] |
Tkinter saving to file not working when used with other code | 38,398,328 | <p>I have a program which compresses a sentence that you input into a list of words and an index list; I also have a program which creates a text while using Tkinter to browse your library and save it. </p>
<p>Both of these pieces of code work individually, however when i use them together in an attempt to save the li... | 1 | 2016-07-15T14:14:19Z | 38,398,495 | <p>Your code runs perfectly fine on my Ubuntu 14.04. The very last line however is wrong. </p>
<pre><code>wordFile.write(file_text)
</code></pre>
<p><code>write</code> expects a <code>string</code>, but you are giving a <code>list</code> to it.</p>
<p>Either use</p>
<pre><code>wordFile.write(str(file_text))
</code>... | 1 | 2016-07-15T14:21:25Z | [
"python",
"tkinter"
] |
How to make code ready to be made into an executable? | 38,398,455 | <p>I created a pretty large Python project with multiple GUIs. I was thinking of creating an executable from it using <code>py2exe</code>, which automatically includes all packages you're using and it formats the files so that imports and everything will run fine. </p>
<p>However, there are lines in my code where I lo... | 0 | 2016-07-15T14:19:23Z | 38,409,490 | <p>See this discussion <a href="http://stackoverflow.com/questions/5458048">How to make a Python script standalone executable to run without ANY dependency?</a>.</p>
| 0 | 2016-07-16T09:04:02Z | [
"python",
"qt",
"executable",
"py2exe"
] |
Counting the number of loops python | 38,398,461 | <p>I am learning python, and one of the exercises is to make a simple multiplication game, that carries on every time you answer correctly. Although I have made the game work, I would like to be able to count the number of tries so that when I've answered correctly a few times the loop/function should end. My problem i... | 0 | 2016-07-15T14:20:03Z | 38,398,633 | <p>You could surround your call of <code>multiplication_game()</code> at the end with a loop. For example:</p>
<pre><code>for i in range(5):
multiplication_game()
</code></pre>
<p>would allow you to play the game 5 times before the program ends. If you want to actually count which round you're on, you could crea... | 1 | 2016-07-15T14:26:55Z | [
"python",
"loops"
] |
Counting the number of loops python | 38,398,461 | <p>I am learning python, and one of the exercises is to make a simple multiplication game, that carries on every time you answer correctly. Although I have made the game work, I would like to be able to count the number of tries so that when I've answered correctly a few times the loop/function should end. My problem i... | 0 | 2016-07-15T14:20:03Z | 38,398,650 | <p>I would use a <code>for</code> loop and <code>break</code> out of it:</p>
<pre><code>attempt = int(input(": "))
for count in range(3):
if attempt == answer:
print("correct")
break
print("not correct")
attempt = int(input("try again: "))
else:
print("you did not guess the number")
<... | 1 | 2016-07-15T14:27:49Z | [
"python",
"loops"
] |
Counting the number of loops python | 38,398,461 | <p>I am learning python, and one of the exercises is to make a simple multiplication game, that carries on every time you answer correctly. Although I have made the game work, I would like to be able to count the number of tries so that when I've answered correctly a few times the loop/function should end. My problem i... | 0 | 2016-07-15T14:20:03Z | 38,398,706 | <pre><code> NB_MAX = 10 #Your max try
def multiplication_game():
num1 = random.randrange(1,12)
num2 = random.randrange(1,12)
answer = num1 * num2
i = 0
while i < NB_MAX:
print('how much is %d times %d?' %(num1,num2))
attempt = int(input(": "))
while attempt ... | 0 | 2016-07-15T14:30:22Z | [
"python",
"loops"
] |
raw_id_fields raising error Related Field got invalid lookup: icontains | 38,398,687 | <p>I don't know why but django-admin, raw_id_fields is returning me an related field error. I'll explain what I've done and the different methods I tried without result.</p>
<p>For this particular case I have 5 different models:</p>
<ul>
<li>System: Orphan</li>
<li>Concept: Orphan</li>
<li>Extract: Related with Syste... | 0 | 2016-07-15T14:29:35Z | 38,399,111 | <p>I was able to fix it.. the problem (or at least the way It got fixed was for the search fields in the related modeladmin of the extract)</p>
<p>I had:</p>
<pre><code>class ExtractManager2(admin.ModelAdmin):
search_fields = ('system', 'extract_name', 'tech_name', 'description', )
</code></pre>
<p>Whe... | 0 | 2016-07-15T14:49:29Z | [
"python",
"django",
"django-admin"
] |
OpenGL (python) - display an image? | 38,398,699 | <p>I'm trying to use PyQT and the Python binding for OpenGL to display an image on a rectangle. So far, here's my code:</p>
<pre><code>gVShader = """
attribute vec4 position;
attribute vec2 texture_coordinates;
varying vec4 dstColor;
varying vec2 v_texture_coord... | 0 | 2016-07-15T14:29:54Z | 38,399,165 | <p>Your texture is <a href="https://www.opengl.org/wiki/Common_Mistakes#Creating_a_complete_texture" rel="nofollow">incomplete</a>. You are not setting filtering and wrap modes. Add these after <code>glTexImage2D</code>:</p>
<pre><code> glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST )
glTexPa... | 1 | 2016-07-15T14:51:43Z | [
"python",
"opengl"
] |
Django admin site modify save | 38,398,833 | <p>In the admin site, I have a custom form. However, I want to override the save method so that if a certain keyword is entered, I do not save it into the database. Is this possible?</p>
<pre><code>class MyCustomForm (forms.ModelForm):
def save(self, commit=True):
input_name = self.cleaned_data.get('input... | 1 | 2016-07-15T14:36:41Z | 38,402,143 | <p>The <code>save()</code> method is supposed to return the object, whether saved or not. It should rather look like:</p>
<pre><code>def save(self, commit=True):
input_name = self.cleaned_data.get('input_name')
if input_name == "MyKeyword":
commit = False
return super().save(commit=commit)
</code><... | 1 | 2016-07-15T17:36:25Z | [
"python",
"django",
"model",
"django-admin",
"override"
] |
Extract Page Intro Info with Beautiful Soup | 38,398,837 | <p>I am new to Beautiful Soup and I am trying to extract the information that appears on a page. This info is contained in the div class="_50f3", and depending on the user it can contain multiple info (studies, studied, works, worked, lives, etc). So, far I have managed though the following code to parse the div classe... | 0 | 2016-07-15T14:36:48Z | 38,398,869 | <p>In general case this is just <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#get-text" rel="nofollow"><code>get_text()</code></a> you need - it would construct a single element text string recursively going through the child nodes:</p>
<pre><code>table = soup.find_all('div', {'class': '_50f3'})
prin... | 2 | 2016-07-15T14:38:37Z | [
"python",
"beautifulsoup"
] |
Extract Page Intro Info with Beautiful Soup | 38,398,837 | <p>I am new to Beautiful Soup and I am trying to extract the information that appears on a page. This info is contained in the div class="_50f3", and depending on the user it can contain multiple info (studies, studied, works, worked, lives, etc). So, far I have managed though the following code to parse the div classe... | 0 | 2016-07-15T14:36:48Z | 38,398,891 | <pre><code>for i in range(len(table)):
print(table[i].text)
</code></pre>
<p>Should Work</p>
| 1 | 2016-07-15T14:39:29Z | [
"python",
"beautifulsoup"
] |
How to combine request from external API and send it as a response in Flask | 38,398,968 | <p>I'm hitting the Hacker news API <a href="https://github.com/HackerNews/API" rel="nofollow">here</a> and want to get the details of each posts that I get through the JSON. I want to send this JSON to my React front-end. </p>
<p>This request is taking a long time. What do I need to do to send the response? </p>
<pre... | 1 | 2016-07-15T14:43:05Z | 38,404,194 | <p>You're querying a json API and treating the response as text:</p>
<pre><code>r = requests.get('https://hacker-news.firebaseio.com/v0/askstories.json?print=pretty')
data = r.text
</code></pre>
<p>So, <code>r.text</code> would be a string "[1234,1235,1236]" and <em>not</em> a list of integers.</p>
<p>So when you it... | 2 | 2016-07-15T19:57:59Z | [
"python",
"flask",
"python-requests"
] |
How to combine request from external API and send it as a response in Flask | 38,398,968 | <p>I'm hitting the Hacker news API <a href="https://github.com/HackerNews/API" rel="nofollow">here</a> and want to get the details of each posts that I get through the JSON. I want to send this JSON to my React front-end. </p>
<p>This request is taking a long time. What do I need to do to send the response? </p>
<pre... | 1 | 2016-07-15T14:43:05Z | 38,404,261 | <p><code>requests</code> has a <code>.json()</code> method that you should use to convert your JSON array string into a python list. </p>
<pre><code>In [1]: import requests
In [2]: r = requests.get('https://hacker-news.firebaseio.com/v0/askstories.json?print=pretty')
In [3]: jsonData = r.json()
In [4]: for data in ... | 1 | 2016-07-15T20:02:27Z | [
"python",
"flask",
"python-requests"
] |
User Defined and built in Arguments in exceptions | 38,399,040 | <p>The following code when executed doesn't result in argument( i.e : Divide by Zero is not permitted ) being printed. It only gives built in error message from-
ZeroDivisionError. So, whats the use of user defined arguments when built in error messages are available.</p>
<pre><code>print "Enter the dividend"
dividend... | -1 | 2016-07-15T14:46:20Z | 38,399,661 | <p>Make your Exception generic works:</p>
<pre><code>dividend=int(input("Enter the dividend: "))
divisor=int(input("Enter the divisor: "))
try:
result=dividend/divisor
except Exception,argument:
print "Divide by Zero is not permitted \n ",str(argument) # Argument not getting printed
else:
print "Result... | 0 | 2016-07-15T15:16:41Z | [
"python",
"exception"
] |
User Defined and built in Arguments in exceptions | 38,399,040 | <p>The following code when executed doesn't result in argument( i.e : Divide by Zero is not permitted ) being printed. It only gives built in error message from-
ZeroDivisionError. So, whats the use of user defined arguments when built in error messages are available.</p>
<pre><code>print "Enter the dividend"
dividend... | -1 | 2016-07-15T14:46:20Z | 38,399,854 | <p>The spelling of "ZeroDivisonError" is incorrect and moreover it shouldnt be in "".
Correct line:</p>
<pre><code> except ZeroDivisionError,argument:
print "Divide by Zero is not permitted \n ",argument
</code></pre>
| 0 | 2016-07-15T15:26:13Z | [
"python",
"exception"
] |
How to get list of class variables in the order they are defined? | 38,399,078 | <p>I have a class that specifies the column layout of a csv file as:</p>
<pre><code>class RecordLayout(object):
YEAR = 0
DATE = 1
MONTH = 2
ID = 3
AGE = 4
SALARY = 5
</code></pre>
<p>I need to get the list of the class variables in the order they are defined. </p>
<p>So far, I tried:</p>
<pr... | 1 | 2016-07-15T14:48:04Z | 38,399,251 | <p>You should use an <a href="https://docs.python.org/3/library/enum.html" rel="nofollow">Enum</a> for this.</p>
<pre><code>>>> class RecordLayout(Enum):
... YEAR = 0
... DATE = 1
... MONTH = 2
... ID = 3
... AGE = 4
... SALARY = 5
...
>>> for i in RecordLayout:
... print(i)... | 3 | 2016-07-15T14:56:16Z | [
"python",
"list",
"class",
"variables"
] |
use of global, but still not recognized in Python function | 38,399,309 | <p>I was making a game where you need to fight monsters, just to practice my coding, when I got an error I couldn't understand. Here is the code, and the error I received:</p>
<p>Note: I changed it to the full code so you could see everything. Sorry about how long it is.</p>
<pre><code>import random
import time
play... | 2 | 2016-07-15T14:58:59Z | 38,399,358 | <p><code>global</code> doesn't actually create a variable; it just indicates that the name <em>should</em> be defined in the global scope, and to modify that (instead of a local variable) when you assign to it. You still need to give it a value before you try to access it.</p>
| 5 | 2016-07-15T15:00:38Z | [
"python"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.