Unnamed: 0 int64 0 1.91M | id int64 337 73.8M | title stringlengths 10 150 | question stringlengths 21 64.2k | answer stringlengths 19 59.4k | tags stringlengths 5 112 | score int64 -10 17.3k |
|---|---|---|---|---|---|---|
800 | 71,988,512 | Is there any way to bind a differnt click handler to QPushButton in PyQt5? | <p>I have a <code>QPushbutton</code>:</p>
<pre class="lang-py prettyprint-override"><code>btn = QPushButton("Click me")
btn.clicked.connect(lambda: print("one"))
</code></pre>
<p>Later in my program, I want to rebind its click handler, I tried to achieve this by calling <code>connect</code> again:</... | <p>Signals and slots in Qt are observer pattern (pub-sub) implementation, many objects can subscribe to same signal and subscribe many times. And they can unsubscribe with <code>disconnect</code> function.</p>
<pre><code>from PyQt5 import QtWidgets, QtCore
if __name__ == "__main__":
app = QtWidgets.QAppl... | python|qt|pyqt|pyqt5 | 1 |
801 | 61,973,633 | Python class not recognizing list | <p>I am attempting to build one of my first classes ever and after checking some documentation and other StackOverflow questions I cannot figure out why I am getting <code>NameError: name 'executed_trades' is not defined</code> in the code listed below:</p>
<pre class="lang-py prettyprint-override"><code>class Positio... | <p>You are missing <code>self</code> in <code>add_position</code> method when you refer to <code>executed_trades</code>:</p>
<pre><code>class Position:
def __init__(self):
self.executed_trades = []
def add_position(self, execution):
if execution not in self.executed_trades:
self.ex... | python|list|class | 2 |
802 | 67,283,961 | Decrypt message with cryptography.fernet do not work | <p>I just tried my hand at encrypting and decrypting data. I first generated a key, then encrypted data with it and saved it to an XML file. Now this data is read and should be decrypted again.</p>
<p>But now I get the error message "cryptography.fernet.InvalidToken".</p>
<pre><code>import xml.etree.cElementT... | <p>I found an answer to my problem:</p>
<p>I took <code>ASCII</code> instead of <code>utf-8</code>. And I added a <code>.decode('ASCII')</code> at the function "loginToRoster" to both variables 'user' and 'pw'</p>
<p>Now the encryption and decryption works fine.</p>
<p>So, the 'loginToRoster' functions looks ... | python|python-3.x|encryption|fernet | 1 |
803 | 70,225,084 | i tried to create a program for in case of an error in entering the input but after that it does not receive new output and continues in a loop | <p>after i type 5 it continue to loop and dont't get to the if statement</p>
<pre><code>def facility():
global user
while user != 1 and user != 2 and user != 3 and user != 4:
user =input("please choose between this four number. \n[1/2/3/4]\n")
if user == 1:
y = ("P... | <p>You use <code>int(input(...))</code> on your first call, but <code>input(...)</code> in the function. Thus the values are strings, not integers and your comparisons will fail.</p>
<p>Here is a fix with minor improvements:</p>
<pre><code>def facility():
user = int(input("please choose your facility..\n &quo... | python|loops | 1 |
804 | 11,245,031 | Importing CSV into MySQL Database (Django Webapp) | <p>I'm developing a webapp in Django, and for it's database I need to import a CSV file into a particular MySQL database.</p>
<p>I searched around a bit, and found many pages which listed how to do this, but I'm a bit confused.</p>
<p>Most pages say to do this:</p>
<pre><code>LOAD DATA INFILE '<file>' INTO TAB... | <p>It looks like you are in the database admin (i.e. PostgreSQL/MySQL). Others above has given a good explanation for that.</p>
<p>But if you want to import data into Django itself -- Python has its own csv implementation, like so: <code>import csv</code>.</p>
<p>But if you're new to Django, then I recommend installi... | python|mysql|django | 2 |
805 | 63,702,650 | Is there a way in Robot framework to log if keywork only if there are True? | <p>I do know that there are no switch statements in RF. I do have 50 if-keywords (that I use because no switch exists).
My log file is very long because literally every 50 if statements are logged (even those who are not true).
I would like to know if there is a way to log only the statements that are true?</p>
<p>here... | <p>May be you are looking for <code>--removekeywords</code> and <code>--flattenkeywords</code> command line options
For more details have a look at <a href="http://robotframework.org/robotframework/2.9.2/RobotFrameworkUserGuide.html#removing-and-flattening-keywords" rel="nofollow noreferrer">Removing and flattening ke... | python|logging|automated-tests|testng|robotframework | 1 |
806 | 56,826,441 | Tensorflow: customise LSTM cell with subtractive gating | <p>I want to use subtractive gating which is explained in <a href="https://arxiv.org/pdf/1711.02448.pdf" rel="nofollow noreferrer">this paper</a>
I'm using Tensorflow, and currently the code is: (Using CPU)</p>
<pre><code>import tensorflow.contrib.rnn as RNNCell
tgt_cell = RNNCell.LSTMCell(num_units=flags.hidden_si... | <p>wow thats kind of advanced. Look like RNNCell.LSTMCell and write your own with changes you want. If you look here <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/rnn/python/ops/rnn_cell.py" rel="nofollow noreferrer">https://github.com/tensorflow/tensorflow/blob/master/tensorflow/cont... | python|tensorflow|machine-learning|neural-network|lstm | 0 |
807 | 60,850,639 | list' object cannot be interpreted as an integer in RandomForest code | <p>i have used following code from machine Learning book</p>
<pre><code>from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import make_moons
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
import mglearn
X,y =make_moons(n_samples=100,noise=0.25,random_state... | <p>In</p>
<pre><code>enumerate(list(zip(axes.ravel())),forest.estimators_)
</code></pre>
<p><code>forest.estimators_</code> is outside your <code>list(zip())</code> call and is treated as the second argument for <code>enumerate</code>, which, <a href="https://docs.python.org/3/library/functions.html#enumerate" rel="n... | python|random-forest | 1 |
808 | 72,623,140 | get name attr value for formset with appropriate prefix and formset form index | <p>I am manually displaying modelformset_factory values in a Django template using the snippet below. One of the inputs is using the select type and I'm populating the options using another context value passed from the view after making external API calls, so there is no model relationship between the data and the for... | <p>I think what you are after is form.col2.html_name - <a href="https://docs.djangoproject.com/en/4.0/ref/forms/api/#django.forms.BoundField.html_name" rel="nofollow noreferrer">docs</a></p>
<p>This is the name that will be used in the widget’s HTML name attribute. It takes the form prefix into account.</p> | python|html|django|formset | 1 |
809 | 68,416,126 | Identify values in column A not in column B and column C using Python | <p>Python newbies looking for help. A dataset has 3 numerical columns: A, B, C. How do I find the values only exist in A but not B and C?</p> | <p>Your question need more details but you can adapt the code below:</p>
<pre><code>A = [1, 2, 3]
B = [1, 3, 4]
C = [1, 4, 5]
>>> set(A).difference(set(B).union(C))
{2}
</code></pre> | python|python-3.x | 0 |
810 | 68,407,571 | BranchPythonOperator not running with past skipped state task | <p>This is how my airflow dag looks like</p>
<p><a href="https://i.stack.imgur.com/GVuWn.jpg" rel="nofollow noreferrer">1</a>:<a href="https://i.stack.imgur.com/GVuWn.jpg" rel="nofollow noreferrer">Airflow dag</a></p>
<p>There is a branch task which checks for a condition and then either :</p>
<p>Runs Task B directly, ... | <p>The reason is happens isn't related to trigger rules.
It happens because <code>default_args</code> in DAG constructor contains <code>wait_for_downstream=True</code>
so when you do:</p>
<pre><code>branch_task = BranchPythonOperator(
task_id='branching',
python_callable=check_condition,
dag=dag,
depend... | python|airflow | 0 |
811 | 62,400,540 | User authentication for Spotify in Python using Spotipy on AWS | <p>I am currently building a web-app that requires a Spotify user to login using their credentials in order to access their playlists</p>
<p>I'm using the Spotipy python wrapper for Spotify's Web API and generating an access token using, </p>
<pre><code>token = util.prompt_for_user_token(username,scope,client_id,clie... | <h3>The quick way</h3>
<ol>
<li>Run the script locally so the user can sign in once</li>
<li>In the local project folder, you will find a file <code>.cache-{userid}</code></li>
<li>Copy this file to your project folder on AWS</li>
<li>It should work</li>
</ol>
<hr>
<h3>The database way</h3>
<p>There is currently an... | python|amazon-web-services|authentication|spotify|spotipy | 2 |
812 | 35,449,968 | Python not in dict condition sentence performance | <p>Does anybody know about what is better to use thinking about speed and resources? Link to some trusted sources would be much appreciated.</p>
<pre><code>if key not in dictionary.keys():
</code></pre>
<p>or</p>
<pre><code>if not dictionary.get(key):
</code></pre> | <p>Firstly, you'd do</p>
<pre><code>if key not in dictionary:
</code></pre>
<p>since dicts are iterated over by keys.</p>
<p>Secondly, the two statements are not equivalent - the second condition would be true if the corresponding values is falsy (<code>0</code>, <code>""</code>, <code>[]</code> etc.), not only if t... | python|performance|dictionary | 6 |
813 | 31,293,854 | Python apply a func to two lists of lists, store the result in a Dataframe | <p>To simplify my problem, say I have two lists of lists and a function shown below:</p>
<pre><code>OP = [[1,2,3],[6,2,7,4],[4,1],[8,2,6,3,1],[6,2,3,1,5], [3,1],[3,2,5,4]]
AP = [[2,4], [2,3,1]]
def f(listA, listB):
return len(listA+listB) # my real f returns a number as well
</code></pre>
<p>I want to get the <c... | <p>You could do so with some nested <a href="https://docs.python.org/2/tutorial/datastructures.html" rel="nofollow">list comprehension</a>, followed by an application of <a href="http://pandas-docs.github.io/pandas-docs-travis/dsintro.html?highlight=from_records" rel="nofollow"><code>pandas.DataFrame.from_records</code... | python|pandas|dataframe|series | 1 |
814 | 49,258,681 | Share functions across colaboratory files | <p>I'm sharing a colaboratory file with my colleagues and we are having fun with it. But it's getting bigger and bigger, so we want to offload some of the functions to another colaboratory file. How can we load one colaboratory file into another? </p> | <p>There's no way to do this right now, unfortunately: you'll need to move the code into a .py file that you load (say by cloning from github).</p> | python-3.x|google-colaboratory | 3 |
815 | 42,874,853 | Cannot return a float value of -1.00 | <p>I am currently doing an assignment for a computer science paper at university. I am in my first year.</p>
<p>in one of the questions, if the gender is incorrect the function is suppose to return a value of -1. But in the testing column, it says the expected value is -1.00. And I cannot seem to be able to return the... | <p>This isn’t as clear as it could be. Does your instructor or testing
software expect a string <code>'-1.00'</code>? If so, just return that. Is a
<code>float</code> type expected? Then return <code>-1.0</code>; the number of digits shown does
not affect the value.</p> | python-3.x | 1 |
816 | 42,738,126 | nosetests default encoding is ascii, main program is utf-8 | <p>All my files start with <code>#-*- coding: utf-8 -*-</code></p>
<p>My virtualenv is set to python 3.5, <code>virtualenv -p python3 venv</code></p>
<p>My app hierarchy looks like this :</p>
<pre><code>app/app/[file].py
__init__.py
/tests/test_[file].py
/__init__.py
main.py
</code></pre>
<p... | <p>Python 2.7 nose default installation on my system was in fault.</p>
<p>Without being in venv, i <code>pip uninstall nose</code>. Then i activated my virtualenv which is using Python 3.5. Being in my venv, nose could then only choose nosetests from it. It worked!</p>
<p>It seems nosetests was prioritizing "global" ... | python-3.x|unicode|nose | 1 |
817 | 51,091,576 | Undefined is not an object (tensorflow imagerecognition) | <p>When trying to integrate a pretrained tensorflow model with expo (react-native), the following error occurs within these lines:</p>
<pre><code>async classify(photo) {
try {
const tfImageRecognition = new TfImageRecognition({
model: require('./assets/output_graph.pb'),
labels: r... | <p>I have the same problem, in my case I forget to link the library.</p>
<p><strong>Linking</strong></p>
<p><code>$ react-native link react-native-tensorflow</code></p> | react-native|tensorflow|object-detection|expo | 0 |
818 | 50,603,815 | Appending two texts keeping the line structure | <p>Sorry in advance if my question is not smart enough, but I am new in Python:
I have two string files: file A and file B. The are something like this:
File A:</p>
<pre><code>File A is the master file{
sdfsf
sdfsdf
sdfsd
sdfdf
}
</code></pre>
<p>File B is similar.
I want to append file A to file B(and to other f... | <p>To append the contents of File_A to File_B, you can just treat it as a single string.</p>
<pre><code>with open('C:\\Users\\admin\\Desktop\\...\\Sofa.txt') as file_a:
contents_a = file_a.read()
with open('C:\\Users\\admin\\Desktop\\.... ....\\....\\...\\view_1.txt', 'a') as file_b:
file_b.write(contents_a)
... | python | 1 |
819 | 44,934,876 | Making my cython code more efficient | <p>I've written a python program which I try to cythonize.
Is there any suggestion how to make the for-loop more efficient, as this is taking 99% of the time?</p>
<p>This is the for-loop:</p>
<pre><code> for i in range(l):
b1[i] = np.nanargmin(locator[i,:]) # Closer point
locator[i, b1[i]] = NAN # ... | <p>A couple of suggestions:</p>
<ol>
<li><p>Take the calls to <code>np.nanargmin</code> out of the loop (use the <code>axis</code> parameter to let you operate on the whole array at once. This reduces the number of Python function calls you have to make:</p>
<pre><code>b1 = np.nanargmin(locator,axis=1)
locator[np.ara... | numpy|cython|cythonize | 1 |
820 | 45,251,046 | Referencing results with Python in Maya | <p>I've been working on a script in Maya that will allow me to work with the cameras without having to go into the <code>Attribute Editor</code> all the time. Currently I have a menu with a menu item and within that menu item I have the check box flag active as well. When the check box button is toggled it runs a comma... | <p>To get the DOF of the camera use this command:</p>
<pre><code>import maya.cmds as cmds
print(cmds.camera('cameraShape1', q=True, dof=True))
</code></pre>
<p>To disable the DOF of the camera use this command:</p>
<pre><code>cmds.camera('cameraShape1', e=True, dof=False)
</code></pre>
<p>So your <code>if statement... | python|scripting|maya | 1 |
821 | 57,872,850 | Executing a command out of conda env | <p>Im activating a conda environment beginning of the script execution but in which I want to execute a command using os.system() out of conda environment with in a loop.</p>
<p>Example:-</p>
<pre><code>conde continues ...
for n in range(5):
# Some code here with in conda environment
# Only the following com... | <p>Commands run with <code>os.system</code> will inherit the environment variables, and hence run in the activated Conda env:</p>
<pre class="lang-bash prettyprint-override"><code>$ which python
/usr/bin/python
$ python -c "import os; os.system('which python')"
/usr/bin/python
$ conda activate
(base) $ whi... | python|shell|anaconda | 1 |
822 | 54,002,432 | (Thailanguage)I have problem about read csv file and uploading file by flask | <p>I have just started learning Flask and Python. I have problems when I upload file csv and I want to lead data in file show on webpage(generate by html)<br>
now mywebpage show</p>
<p>Timestamp ... เลือกข้อที่ถูกที่สุด 0 2561/12/25 2:30:50 หลังเที่ยง GMT+7 ... NaN 1 2561/12/25 2:31:40 หลังเที่ยง GMT+7 ... NaN 2 2561/... | <p>Try this <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_html.html#pandas-dataframe-to-html" rel="nofollow noreferrer">pandas.DataFrame.to_html</a></p>
<p>For example</p>
<pre><code>>> print(yourdataframe.to_html())
</code></pre>
<p>Remember that Python and HTML are differ... | python|html|csv|flask | 0 |
823 | 53,939,222 | python pandas: replace a str value of column in another str column with a special character | <p>There is a dataframe like as following.</p>
<pre><code> id num text
1 1.2 price is 1.2
1 2.3 price is 1.2 or 2.3
2 3 The total value is $3 and $130
3 5 The apple value is 5dollar and $150
</code></pre>
<p>I want to replace the num in the text with character... | <p>Let us using <code>regex</code> and <code>replace</code></p>
<pre><code>df.text.replace(regex=r'(?i)'+ df.num.astype(str),value="UNK")
0 price is UNK
1 price is 1.2 or UNK
2 The total value is UNK
Name: text, dtype: object
#df.text=df.text.replace(regex=r'(?i)'+ df.num.astype(str),value="UNK"... | python|python-3.x|string|pandas | 2 |
824 | 53,859,101 | concatante list of lists dataframe from pd.read_html DF[0] format | <p>I have a DF[number] = pd.read_html(url.text)</p>
<p>I want to concantante or join the DF lists theres hundreads of e.g. DFs[400] into a single pandas dataframe</p>
<p>the dataframes are in list format so list of lists but python index lists like pandas dataframe</p>
<pre><code> [ Vessel Buil... | <p>You can use list comprehension:</p>
<pre><code>pd.concat([dfs[i] for i in range(len(dfs))])
</code></pre> | python|pandas|list|concat|scrape | 0 |
825 | 58,396,435 | I am not getting output for map widget in jupyter notebook | <p>I am working on Jupyter Notebook and installed ArcGis api. When I called the map from that api then map widget is not showing. All the features of arcgis api is working quite well, except it's map widget.</p>
<blockquote>
<p>Following is the code:-</p>
</blockquote>
<pre><code>from arcgis.gis import GIS
myGIS = ... | <p>Using Chrome was my answer. Everyting is working fine, as long as Chrome is the browser. Cheers.</p> | python-3.x|jupyter-notebook|arcgis | 0 |
826 | 28,629,910 | Python Class: Global/Local variable name not defined | <p>I have two sets of code, one which I use 'Class' (Second piece of code) to manage my code, and the other I just define functions, in my second piece of code I get a NameError: global name '...' is not defined.
Both pieces of code are are for the same purpose.</p>
<pre><code>from Tkinter import *
import ttk
import c... | <p>In your first code piece, you define the variable 'lment1' in the __init __ method, making it local to that single method.
When you then try to access the same variable in the 'login_try', Python doesn't know what it is.</p>
<p>If you wish to access the variable form wherever in the class, you should define it on t... | python|class|tkinter | 2 |
827 | 25,864,955 | Regex to select and replace spaces inside double brackets | <p>I'm writing a script which is used to tidy up MediaWiki files prior to conversion to confluence mark-up, this particular scenario I'm needing to fix page links which in MediaWiki are something like this</p>
<pre><code>[[this is a page]]
</code></pre>
<p>the problem being that the actual page link would be this_is... | <p>Try with <code>re.sub</code> and lambda expression</p>
<pre><code>>>> import re
>>> test = '[[this is a page]] bla bla [[this is another page]]'
>>> re.sub(r'\[\[.+?\]\]', lambda x:x.group().replace(" ","_"), test)
'[[this_is_a_page]] bla bla [[this_is_another_page]]'
</code></pre> | python|regex | 3 |
828 | 53,638,832 | Bold, underlining, and Iterations with python-docx | <p>I am writing a program to take data from an ASCII file and place the data in the appropriate place in the Word document, and making only particular words bold and underlined. I am new to Python, but I have extensive experience in Matlab programming. My code is:</p>
<pre><code>#IMPORT ASCII DATA AND MAKE IT USEABL... | <p>Untested, but assuming python-docx is similar to python-pptx (it should be, it's maintained by the same developer, and a cursory review of the documentation suggests that the way it interfaces withthe PPT/DOC files is the same, uses the same methods, etc.)</p>
<p>In order to manipulate substrings of paragraphs or w... | python|ascii|python-docx | 4 |
829 | 24,899,785 | django - view returning no value? | <p>I have the following basic views.py to test out doing queries based on the user.</p>
<pre><code>def Vendor_Matrix(request):
username = request.session.get('username','')
queryset = User.objects.filter(username=username).values_list('user_permissions', 'username', 'first_name')
return JSONResponse(querys... | <p><a href="https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpRequest.user" rel="nofollow">That's not where Django keeps the logged-in user...</a></p>
<pre><code>return JSONResponse(operator.attrgetter('user_permissions', 'username', 'first_name')(request.user))
</code></pre> | python|django | 1 |
830 | 38,426,414 | Tensorflow Inception Android | <p>I am trying to build the [TensorFlow Android Camera Demo][1].<br>
As i understand the error something is wrong with build-tools/23.0.1 removed it and reinstalled it but to no effect. what is wrong or any thoughts on how to find out what the problem is?</p>
<p>used:<br>
ndk: android-ndk-r12b<br>
tensorflow: master b... | <p>Actual problem: 64 bit machine's 32 bit compatibility
Solution found: <a href="https://stackoverflow.com/questions/17020298/android-sdks-build-tools-17-0-0-aapt-error-while-loading-shared-libraries-libz">this post</a></p> | android|android-ndk|tensorflow | 0 |
831 | 36,467,613 | Need help,writing a python BMI calc | <p>I am new to python and and currently learning to use functions properly.</p>
<pre><code>h = 1.75
w = 70.5
bmi = float(w / h ** 2)
if bmi < 18.5:
print('过轻')
elif 18.5 <= bmi < 25:
print('正常')
elif 25 <= bmi < 28:
print('过重')
elif 28 <= bmi < 32:
print('肥胖')
else bmi >= 32:
... | <p>This statement is not "else", it is another "elif".</p>
<pre><code>elif bmi >= 32:
print 'foo'
else:
print 'bar'
</code></pre> | python | 0 |
832 | 34,160,995 | Python Turtle fill the triangle with color? | <p>I am currently using the <code>turtle.goto</code> cords from a text file. I have the triangle drawn and everything but I don't know how to fill the triangle.</p> | <p>You are ending fill after every new coordinate. You need to call <code>t.begin_fill()</code> before your <code>for</code> loop and call <code>t.end_fill()</code> after the last coordinate, otherwise you are just filling in your single line with each iteration.</p> | python|colors|turtle-graphics | 2 |
833 | 38,668,814 | constrain a series or array to a range of values | <p>I have a series of values that I want to have constrained to be within +1 and -1.</p>
<pre><code>s = pd.Series(np.random.randn(10000))
</code></pre>
<p>I know I can use <code>apply</code>, but is there a simple vectorized approach?</p>
<pre><code>s_ = s.apply(lambda x: min(max(x, -1), 1))
s_.head()
0 -0.256117... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/version/0.13.1/generated/pandas.Series.clip.html" rel="nofollow"><code>clip</code></a>:</p>
<pre><code>s = s.clip(-1,1)
</code></pre>
<p>Example Input:</p>
<pre><code>s = pd.Series([-1.2, -0.5, 1, 1.1])
0 -1.2
1 -0.5
2 1.0
3 1.1
</code></pre>
<p>Exampl... | python|numpy|pandas | 4 |
834 | 40,552,485 | PyQt5 equivalent of QtWebKitWidgets.QWebView.page.mainFrame() for QtWebEngineWidgets.QWebEngineView()? | <p>I am very new to PyQt and started to play around with the following code (which originally comes from <a href="http://pythoncentral.io/pyside-pyqt-tutorial-qwebview/" rel="nofollow noreferrer">this blog post</a>):</p>
<pre><code># Create an application
app = QApplication([])
# And a window
win = QWidget()
win.setW... | <p>There is nothing equivalent to the Qt WebKit <code>QWebFrame</code> class in Qt Web Engine. Frames are just considered part of the content, so there are no dedicated APIs for dealing with them - there is just a single <code>QWebEnginePage</code>, which provides access to the whole web document.</p>
<p>There is also... | python|pyqt|pyqt5|qtwebengine | 4 |
835 | 32,722,671 | Combining multiple columns in a DataFrame | <p>I have a DataFrame with 40 columns (columns 0 through 39) and I want to group them four at a time: </p>
<pre><code>import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.binomial(1, 0.2, (100, 40)))
</code></pre>
<hr>
<pre><code>new_df["0-3"] = df[0] + df[1] + df[2] + df[3]
new_df["4-7"] = df[4] + df[... | <p>You could select out the columns and sum on the row axis, like this.</p>
<pre><code>df['0-3'] = df.loc[:, 0:3].sum(axis=1)
</code></pre>
<p>A couple things to note:</p>
<ol>
<li>Summing like this will ignore missing data while <code>df[0] + df[1] ...</code> propagates it. Pass <code>skipna=False</code> if you wan... | python|pandas|dataframe | 2 |
836 | 30,012,795 | I'm designing a flow rate based traffic controller on raspberry pi, it runs in an infinite loop | <p>I'm designing a flow rate based traffic controller on raspberry pi using buttons as traffic simulators. the problem i'm facing is that the maximum value gets selected at first and there can be no increments possible to that value and the code runs in an infinite loop.</p>
<p>For ex if i press the button at road 1 o... | <p>I was getting confused by all the layered if statements. You can use the keyword "and" in between them to combine all the ifs into one. Still, I didn't see any fault that would cause your problem. Also, if you want to change variables that are declared outside a loop, you will need to use a <code>global</code> state... | python|raspberry-pi | 0 |
837 | 43,291,801 | extracting chars from string using regex and pythonic way | <p>I have a string like this: "32H74312"
I want to extract some parts and put them in different variables. </p>
<pre><code>first_part = 32 # always 2 digits
second_part = H # always 1 chars
third_part = 743 # always 3 digit
fourth_part = 12 # always 2 digit
</code></pre>
<p>Is there some way to this in pythonic way?... | <p>There's now reason to use a regex for such a simple task.
The <em>pythonic</em> way could be something like:</p>
<pre><code>string = "32H74312"
part1 = string[:2]
part2 = string[2:3]
part3 = string[3:6]
part4 = string[6:]
</code></pre> | python|regex | 2 |
838 | 43,128,229 | TimeoutException using selenium with python | <p>I'm getting TimeoutException when using this code to get the fill in the CardNum textbox with a number</p>
<pre><code>CardNUM = WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.XPATH, '//*[@id="number"]')))
CardNUM.send_keys(cardNum)
</code></pre>
<p>Xpath is taken directly from right clickin... | <p>Most likely the element is inside an IFRAME, especially since it seems to be a credit card number. The payment portion of payment pages are typically in an IFRAME for security. Try switching to the IFRAME first then your code should work.</p> | python|selenium|xpath | 0 |
839 | 48,704,369 | How to apply linear transform on a 3D feature vector in Tensorflow? | <p>Imagine there is a tensor with the following dimensions <code>(32, 20, 3)</code> where <strong>batch_size</strong> = 32, <strong>num_steps</strong> = 20 and <strong>features</strong> = 3. The features are taken from a .csv file that has the following format:</p>
<pre><code>feat1, feat2, feat3
200, 100, 0
5.5, 200, ... | <p>Could reshape into [batchsize*num_steps, features] use a Tensorflow linear layer with 100 outputs and then reshape back would that work?</p>
<pre><code>reshaped_tensor = tf.reshape(your_input, [batchsize*num_steps, features])
linear_out = tf.layers.dense(inputs=reshaped_tensor, units=100)
reshaped_back = tf.reshape... | python|tensorflow | 2 |
840 | 51,493,185 | matching similar elements in between two lists | <p>I'm new to python so apologies if its a silly question.</p>
<p>I have two lists<br>
<code>L1=['marvel','audi','mercedez','honda']</code> and </p>
<p><code>L2=['marvel comics','bmw','mercedez benz','audi']</code>.</p>
<p>I want to extract matching elements which contains in <code>list L2</code> matched with <code... | <p>I think what you really want here is the elements of <code>L2</code> that contain any elements in <code>L1</code>. So simply replace <code>if j in i</code> with <code>if i in j</code>:</p>
<pre><code>for i in L1:
for j in L2:
if i in j:
print (j)
</code></pre>
<p>This outputs:</p>
<pre><code>m... | python|arrays|python-3.x|pandas|keyword-search | 4 |
841 | 65,887,235 | Generate a list from list of dicts if value not exists in another list | <p>im triying to filter a list of dicts using the elements of a list</p>
<pre><code>a=[{"item_id": "ITEM2090", "seller_id":1009954},
{"item_id": "ITEM2050", "seller_id":1009920},
{"item_id": "ITEM2032", "seller_id":1009960},... | <pre><code>c = [item for item in a if item["item_id"] not in b]
</code></pre>
<p>Will be better to make "b" as a set in case of a large amount of items.</p> | python|dictionary | 2 |
842 | 65,615,634 | Trying to predict with a loaded classification model with .h5 on Tensorflow, returning IndexError: list index out of range | <p>I created a classification model with both saved_model format and .h5 format. I am trying to load the model so I can deploy it with</p>
<p><code>new_model = tf.keras.models.load_model('my_model.h5')</code></p>
<p>Then I predict</p>
<pre><code>print(new_model.predict('/content/images/image.jpg'))
</code></pre>
<p>The... | <p>for model.predict to produce proper predictions it is necessary that the input be of the same nature as the inputs that the model was trained on. For example in training you read in an image from the training set. Then typically you will rescale the pixel values, usually in the range from 0 to +1 or in some cases -1... | python|tensorflow|deployment | 0 |
843 | 72,336,739 | Setting the minimum value of a pandas column using clip | <p>I want to set the <code>minimum</code> value of a column of <code>pandas</code> dataframe using <code>clip</code> method. Below is my code</p>
<pre><code>import pandas as pd
data = pd.DataFrame({'date' : pd.to_datetime(['2010-12-31', '2012-12-31', '2012-12-31']), 'val' : [1,2, 5]})
data.clip(lower=pd.Series({'val': ... | <p>You can try <code>Series.clip</code> or set the <code>date</code> column as index then <code>DataFrame.clip</code>.</p>
<pre class="lang-py prettyprint-override"><code>data['val'] = data['val'].clip(4)
# or
data = (data.set_index('date')
.clip(4)
.reset_index())
</code></pre>
<pre><code>print(data)... | python-3.x|pandas | 1 |
844 | 37,015,648 | python plot large dimension data | <p>I have a 1800*100000000 matrix, and I want to plot it in python using code below:</p>
<pre><code>import matplotlib.pyplot as plt
plt.spy(m)
plt.show()
</code></pre>
<p>The result is disappointing, it looks like a line because of little row number compared to column number:</p>
<p><a href="https://i.stack.imgur.co... | <p><a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.spy" rel="nofollow noreferrer"><code>spy()</code> accepts a number of keyword arguments, <code>aspect</code> in particular is interesting...</a></p>
<pre><code>In [1]: import numpy as np
In [2]: import matplotlib.pyplot as plt
In [3]: a = np.rando... | python|matplotlib | 1 |
845 | 48,698,062 | Set schema in pyspark dataframe read.csv with null elements | <p>I have a data set (example) that when imported with </p>
<pre><code>df = spark.read.csv(filename, header=True, inferSchema=True)
df.show()
</code></pre>
<p>will assign the column with 'NA' as a stringType(), where I would like it to be IntegerType() (or ByteType()).</p>
<p><a href="https://i.stack.imgur.com/XggfZ... | <p>You can set a new null value in spark's csv loader using <code>nullValue</code>:</p>
<p>for a csv file looking like this:</p>
<pre class="lang-py prettyprint-override"><code>col_01,col_02,col_03
111,2007-11-18,3
112,2002-12-03,4
113,2007-02-14,5
114,2003-04-16,NA
115,2011-08-24,2
116,2003-05-03,3
117,2001-06-11,4
1... | python-3.x|pyspark|spark-dataframe|pyspark-sql | 9 |
846 | 20,338,539 | ValueError: could not convert string to float in simple code | <pre><code> # -*- coding: cp1250 -*-
print ('euklides alpha 1.0')
a = raw_input('podaj liczbę A : ')
b = raw_input('podaj liczbę B : ')
a = float('a')
b = float('b')
if 'a'=='b':
print 'a'
elif 'a' > 'b':
while 'a' > 'b':
print('a'-'b')
if 'a'=='b': break
if 'a' > 'b':... | <p>the float function can take a string but it must contain a possibly signed decimal or floating point number. You want to make the variable <code>a</code> a float not the char <code>'a'</code>. </p>
<p>You don't need all the <code>'</code> around your variable names. When you put quotes around them <code>'b'</code> ... | python|string|python-2.7|floating-point | 2 |
847 | 48,024,098 | Can the print function be used reliably in GCE apps? | <p>I have a GCE app consisting of a single Python script that has some long running functions (most of these are querying databases and sending the results somewhere). It seems that when the script hangs on one of these longer running tasks that nothing is printed to Stackdriver Logging, <strong>even <code>print()</cod... | <p>Per <a href="https://unix.stackexchange.com/a/182541">this answer</a> from <a href="https://unix.stackexchange.com">unix.stackexchange.com</a>, when a process's output is redirected to something other than a terminal, the output may be temporarily stored in a buffer by the operating system. Buffering output increas... | python|google-compute-engine|stackdriver | 1 |
848 | 48,112,036 | SQLAlchemy: session.query.one() and session.add() in one transaction | <p>I want to add row with <code>VALUE1</code> to table <code>TABLE1</code> only if <code>TABLE2</code> have row with <code>VALUE2</code></p>
<p>I can do something like that:</p>
<pre><code>session.query(TABLE2)
.filter(TABLE2.FIELD2 == VALUE2)
.update({TABLE2.FIELD2: VALUE2}) # without change. only for check
... | <p>Provided you have a unique key on <code>TABLE1.VALUE1</code>, you could first query
<code>TABLE2</code> and try to insert to <code>TABLE1</code>. In case the <code>VALUE1</code> already exists in <code>TABLE1</code>, the error will be thrown and you will be able to rollback the transaction. </p>
<pre><code>from s... | python|sql|sqlalchemy | 0 |
849 | 51,391,271 | Using .txt file as a Dictionary | <p>I have a <strong>.txt</strong> file formatted like a dictionary is, for example:</p>
<p><code>{'planet': 'earth', "country": "uk"}</code></p>
<p>Just that, that's all. I would want to add more to this later. At the moment, I can save more keys to it and have it saved but...</p>
<p>How can I import this <strong>.t... | <p>You can use <a href="https://docs.python.org/2/library/ast.html#ast.literal_eval" rel="nofollow noreferrer"><code>ast.literal_eval</code></a></p>
<pre><code>import ast
with open('myfile.txt') as f:
mydict = ast.literal_eval(f.read())
</code></pre>
<p>Some <a href="https://stackoverflow.com/questions/15197673/u... | python|file|dictionary | 1 |
850 | 55,973,952 | Error during backward migration of DeleteModel in Django | <p>I have two models with one-to-one relationship in Django 1.11 with PostgreSQL. These two models are defined in <code>models.py</code> as follows:</p>
<pre class="lang-py prettyprint-override"><code>class Book(models.Model):
info = JSONField(default={})
class Author(models.Model):
book = models.OneToOneFie... | <p>I have managed to solve problem by changing the order of the migrations. </p>
<p>As I mentioned in my question, I have applied <a href="https://stackoverflow.com/a/37244199/4665915">this answer</a> by adding <code>blank=True, null=True</code> parameters to both <code>info</code> and <code>book</code> fields. But it... | python|django|postgresql|psycopg2|django-migrations | 0 |
851 | 71,853,039 | How do I convert Python scripts files to images files representing the code with highlighting? | <p>In short, how do I get this:</p>
<p><a href="https://i.stack.imgur.com/JBBws.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JBBws.jpg" alt="enter image description here" /></a></p>
<p>From this:</p>
<pre class="lang-py prettyprint-override"><code>def fiblike(ls, n):
store = [] ... | <p><a href="https://marketplace.visualstudio.com/items?itemName=adpyke.codesnap" rel="nofollow noreferrer">CodeSnap</a> is a very nice tool to do just that for VSCode.</p> | python|python-3.x | 0 |
852 | 71,368,471 | in discord.py How can i make my bot that the commands only can be use in specific channel or specific server? | <p>So, anyone can invite my personal bot to their server. So, I want the command will work on specific channel or specific server with @bot.event not client.</p> | <p>if you use <code>await bot.process_commands(message)</code> you can try this</p>
<pre><code>@bot.event
async def on_message(message):
if message.channel.id == yourchannelid:
await bot.process_commands(message)
if message.guild.id = yourguildid:
await bot.process_commands(message)
</code... | javascript|python|discord | 1 |
853 | 63,358,767 | How to filter rows and words in lower case in pandas dataframe? | <p>Hi I would like to know how to select rows which contains lower cases in the following dataframe:</p>
<pre><code>ID Name Note
1 Fin there IS A dog outside
2 Mik NOTHING TO DECLARE
3 Lau no house
</code></pre>
<p>What I would like to do is to filter rows where Note column contains at lea... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.contains.html" rel="nofollow noreferrer"><code>Series.str.contains</code></a> for filter at least one lowercase character in <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing" rel="no... | python|pandas | 2 |
854 | 69,285,376 | Problem importing matrix in Python from Excel and maybe some problems with if elif statments | <p>I'm trying running this code with some problems to solve. I'm at first trying inserting "BOD" as the name of the output and "6" as the number of input parameters.</p>
<pre class="lang-py prettyprint-override"><code> import os
import numpy as np
import pandas as pd
from pandas impor... | <p>Think about your conditions. What happens if every individual test is <code>False</code>? What happens if <em>all</em> your tests are <code>False</code> ?</p>
<p>There is a path through your decision tree in which <em>no file is opened</em>. This is currently obtaining, so <code>Data</code> doesn't exist, as you ... | python|excel|pandas|if-statement | 1 |
855 | 68,435,475 | My scrollbar is not working with mouse's scroller | <p>I have reused the code.<br />
I am trying to scroll this frame and the scrollbar is working but
I want it to be scrolled using the scroller of mouse.
What should I do?
I want it to be scrolled vertically only.</p>
<pre><code>from tkinter import *
root = Tk()
root['bg'] = 'wheat'
frame_container=Frame(root, width =... | <p>You can use <code><MouseWheel></code> virtual event to scroll the canvas and ultimately the frame.</p>
<pre><code>canvas_container.create_window((0,0),window=frame2,anchor='nw')
def _on_mousewheel(event):
canvas_container.yview_scroll(-1*int(event.delta/120), "units")
canvas_container.bind_all... | python|tkinter|scrollbar|mouse | 0 |
856 | 71,035,037 | Authorization header of GET request in python/wsgi | <p>I'm in the process of creating a POST/GET API in Python 3. I'm running Apache2 connected to a WSGI script. I've managed to retrieve very simple GET requests succesfully. My code so far:</p>
<pre><code>def application(environ, start_response):
status = '200 OK'
output = b'Hello'
print(environ)
... | <p>I figured it out. In your <em>000-default-le-ssl.conf</em> or <em>000-default.conf</em> file (depending on whether you use a secure connection or not) you're supposed to turn on authorization passing manually by writing <strong>WSGIPassAuthorization On</strong> inside your <strong>VirtualHost</strong> tag:</p>
<pre>... | python|get|header|apache2|wsgi | 1 |
857 | 45,224,527 | How to separate a string of repeating characters? | <p>All continuous groups of characters must be grouped together and put into a list. For example, if I have this string:</p>
<pre><code>1112221121
</code></pre>
<p>I would want to split this into a list:</p>
<pre><code>['111', '222', '11', '2', '1']`
</code></pre>
<p>Another example would be </p>
<pre><code>001110... | <p><code>itertools.groupby</code> does just that:</p>
<pre><code>>>> from itertools import groupby
>>> [''.join(g) for _, g in groupby('1112221121')]
['111', '222', '11', '2', '1']
</code></pre> | python | 3 |
858 | 51,840,156 | How to execute script in Anaconda with different installed Python versions? | <p>I want to run a script in Anaconda using Python 2.7.
I am using Windows 8 with Anaconda 3 and Python 3.6.5.
I created another environment with python 2.7.15 and activated it in Anaconda Prompt like advised here: <a href="https://conda.io/docs/user-guide/tasks/manage-python.html" rel="nofollow noreferrer">https://con... | <p>Using conda and environments is easy, once you get to know how to manage environments. </p>
<p>When creating an environment you may choose the python version to use and also what other libraries. </p>
<p>Let's begin creating two different environments.</p>
<pre><code>jalazbe@DESKTOP:~$ conda create --name my-py27... | python-3.x|python-2.7|console|anaconda|conda | 1 |
859 | 54,534,516 | How to stop Scrapy Selector wrap an xml with html? | <p>I do this:</p>
<pre><code>xmlstr="<root><first>info</first></root>"
res = Selector(text=xmlstr).xpath('.').getall()
print(res)
</code></pre>
<p>The output is:</p>
<pre><code>['<html><body><root><first>info</first></root></body></html>']
</co... | <p><a href="http://doc.scrapy.org/en/latest/topics/selectors.html#selector-objects" rel="nofollow noreferrer">scrapy.Selector</a> assumes html, but takes a <code>type</code> argument to change that.</p>
<blockquote>
<p><code>type</code> defines the selector type, it can be <code>"html"</code>, <code>"xml"</code> or ... | python|xpath|scrapy | 3 |
860 | 53,700,234 | Assigning current 'User' as foreign key to nested serializers | <p>I am trying to assign current 'User' to two models using nested serializers.</p>
<pre><code>class UserAddressSerializer(serializers.ModelSerializer):
class Meta:
model = UserAddress
fields = ('user', 'address_1', 'address_2', 'country',
'state_province', 'city', 'zip_code')
... | <p>You need to remove <code>user</code> from fields of <code>UserAddressSerializer</code>:</p>
<pre><code>class UserAddressSerializer(serializers.ModelSerializer):
class Meta:
model = UserAddress
fields = ('address_1', 'address_2', 'country', # <-- Here
'state_province', 'cit... | python|django|python-3.x|django-rest-framework | 1 |
861 | 53,398,884 | Pandas series giving incorrect sum | <p>Why is this Pandas series giving sum = .99999999 where as answer is 1. In my program, I need to assert on 'sum is equal to 1'. And, assertion is failing even if condition is correct.</p>
<pre><code>s = pd.Series([0.41,0.25,0.25,0.09])
print("Pandas version = " + pd.__version__)
print(s)
print(type(s))
print(type(s.... | <p>Use <a href="https://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.isclose.html" rel="nofollow noreferrer">np.isclose</a> to determine if two values are arbitrarily close. It's a remnant of how floats are stored in the machine</p> | python|pandas|series|numpy-ndarray | 3 |
862 | 53,792,144 | print text inside parent div beautifulsoup | <p>i'm trying to fetch each product's name and price from
<a href="https://www.daraz.pk/catalog/?q=risk" rel="nofollow noreferrer">https://www.daraz.pk/catalog/?q=risk</a> but nothing shows up.</p>
<pre><code>containers = page_soup.find_all("div",{"class":"c2p6A5"})
for container in containers:
pname = container.f... | <p>if the page is dynamic, Selenium should take care of that</p>
<pre><code>from bs4 import BeautifulSoup
import requests
from selenium import webdriver
browser = webdriver.Chrome()
browser.get('https://www.daraz.pk/catalog/?q=risk')
r = browser.page_source
page_soup = bs4.BeautifulSoup(r,'html.parser')
containers ... | python|web-scraping|beautifulsoup | 3 |
863 | 45,956,128 | Save unittest results in text file | <p>I'm writing code that tests via unittest if several elements exist on a certain homepage. After the test I want that the results were saved in a text file. But the results in the text file look like this:</p>
<pre><code>......................
.........
------------------------------------------
Ran 12 tests in 22.5... | <p>If the output you wish to save in a file corresponds to what is printed out to the console, you have two main options.</p>
<h3>1 - You're using Linux</h3>
<p>Then just redirect the output to a file:</p>
<pre><code>python script.py > output.txt
</code></pre>
<p>However, the output will not be printed out to th... | python|unit-testing | 3 |
864 | 54,750,890 | Multiple metrics to specific inputs | <p>I have multiple losses and metrics whether custom or imported from keras. Is there a way to specify which model outputs could be inputted to which metric instead of all of them being printed or calculated?</p> | <p>Yes, you can pass the losses/metrics as a dictionary that maps <strong>layer name</strong> to a loss/metrics.</p>
<p>A quote from the <a href="https://keras.io/models/model/" rel="noreferrer">documentation</a>:</p>
<blockquote>
<p>loss: ... If the model has multiple outputs, you can use a different
loss on eac... | python|tensorflow|keras | 10 |
865 | 54,853,238 | Power function from math module seems to stop working in Python | <p>So i'm trying to write a program which finds a Pythagorean triplet, checks if all the numbers which make up the triplet add up to 1000, and if they do then multiply the 3 numbers together and output the result. Here is my sample code:</p>
<pre><code> import math
numbers = [1,2,3]
found = False
while not found:
... | <p>Turns out, your math is incorrect.</p>
<ol>
<li>On each iteration, <em>every</em> number in the triplet is increased by 1</li>
<li><p>After <code>a</code> iterations, in order for it to be a Pythagorean triplet, the following must hold true:</p>
<pre><code>(a + 1)**2 + (a + 2)**2 == (a + 3)**2
</code></pre>
<p>He... | python | 1 |
866 | 55,064,651 | Cannot parse address which contain ".html#/something" using bs4 in python3 | <p>My goal is to parse images from second page. I am using bf4 and Python3 for this.
Please, look at those two pages:</p>
<p>1) Only <a href="https://azzardo.com.pl/lampy-techniczne/2111-bross-1-tuba-lampa-techniczna-azzardo.html" rel="nofollow noreferrer">page</a> with images for all 4 colors (I can parse this page);... | <p>Yep, looks like it's not possible to parse such responsive page using bs4</p> | python|beautifulsoup|html-parsing | 0 |
867 | 21,764,475 | Python: Scaling numbers column by column with pandas | <p>I have a Pandas data frame 'df' in which I'd like to perform some scalings column by column.</p>
<ul>
<li>In column 'a', I need the maximum number to be 1, the minimum number to be 0, and all other to be spread accordingly.</li>
<li>In column 'b', however, I need the <strong>minimum number to be 1</strong>, the <st... | <p>This is how you can do it using <code>sklearn</code> and the <code>preprocessing</code> module. Sci-Kit Learn has many pre-processing functions for scaling and centering data.</p>
<pre><code>In [0]: from sklearn.preprocessing import MinMaxScaler
In [1]: df = pd.DataFrame({'A':[14,90,90,96,91],
... | python|pandas | 85 |
868 | 31,037,751 | Reading variable number of columns in pandas | <p>I have a poorly formatted delimited file, in which the there are errors with the delimiter, so it sometimes appears that there are an inconsistent number of columns in different rows.</p>
<p>When I run</p>
<pre><code>pd.read_csv('patentHeader.txt', sep="|", header=0)
</code></pre>
<p>the process dies with this er... | <p>Try this.</p>
<pre><code>pd.read_csv('patentHeader.txt', sep="|", header=0, error_bad_lines=False)
</code></pre>
<p><code>error_bad_lines</code>: if False then any lines causing an error will be skipped bad lines, and it will be reported once the reading process is done.</p> | pandas | 2 |
869 | 30,920,380 | Displaying ggplot2 graphs from R in Jupyter | <p>When I create a plot in Jupyter using the <code>ggplot2</code> R package, I get a link to the chart that says "View PDF" instead of the chart being presented inline.</p>
<p>I know that traditionally in IPython Notebook you were able to show the charts inline using the <code>%matplotlib</code> magic function. Does J... | <p>You can show the graphs inline with this option.</p>
<pre><code>options(jupyter.plot_mimetypes = 'image/png')
</code></pre>
<p>You can also produce pdf files as you would regularly in R, e.g.</p>
<pre><code>pdf("test.pdf")
ggplot(data.frame(a=rnorm(100,1,10)),aes(a))+geom_histogram()
dev.off()
</code></pre> | r|ggplot2|ipython-notebook|jupyter | 5 |
870 | 29,319,933 | Best practise to apply several rules on 1 string | <p>i'm getting url as string and need to apply several rules to it. First rule is to remove anchors, then remove '../' notation, because urljoin joins url incorrect in some cases, and finally remove leading slash. For now i have such code:</p>
<pre><code>def construct_url(parent_url, child_url):
url = urljoin(... | <p>Unfortunately, there isn't much that really could make your function <em>simpler</em> here, since you're dealing with some pretty odd cases.</p>
<p>But you can make it more <em>robust</em> by using Python's <a href="https://docs.python.org/2/library/urlparse.html#urlparse.urlsplit" rel="nofollow noreferrer"><code>ur... | python | 0 |
871 | 8,874,276 | Trouble with making background of image transparent in python using pygame | <p>I have a rather confusing problem in running our game. I am trying to make a game using Python's pygame and I am using images downloaded from the internet. The problem is that some images have a white background and some have a colored background. I used Photoshop to get rid of the white background and re-saved the ... | <p>You need to use the .convert_alpha() method when loading the image for per pixel transparency.</p>
<p>So,</p>
<pre><code>self.image = pygame.image.load("jellyfishBad.png").convert_alpha()
</code></pre> | python|image|pygame|transparent | 2 |
872 | 8,936,297 | Attempting to display total amount_won for each user in database via For loop | <p>I'm trying to display the Sum of amount_won for each user_name in the database. My database is:</p>
<p>Stakes table</p>
<pre><code>id
player_id
stakes
amount_won
last_play_date
</code></pre>
<p>Player table</p>
<pre><code>id
user_name
real_name
site_played
</code></pre>
<p>models.py</p>
<pre><code>class Player... | <p>Check out: <a href="https://docs.djangoproject.com/en/dev/topics/db/aggregation/" rel="nofollow">https://docs.djangoproject.com/en/dev/topics/db/aggregation/</a></p>
<pre><code>players = Player.objects.annotate(total_amount_won=Sum('stakes__amount_won'))
players[0].total_amount_won # This will return the 'total am... | python|mysql|django | 2 |
873 | 58,735,125 | issue with for loop in python only gets the last item | <p>I'm a beginner in python, currently I'm trying to automate filling website field using <code>selenium</code>.</p>
<p>I'm trying to iterate over nested lists using <code>for</code> loop but always get only the last element. Any suggestions why?</p>
<pre class="lang-py prettyprint-override"><code>fields = [['a','b',... | <p>You don't need <code>range(len(list_))</code> for iterating over indeces only.</p>
<p>Usual <code>for</code> will do. You can also unpack list with <code>*</code>:</p>
<pre class="lang-py prettyprint-override"><code>fields = [['a','b','c'],['x','y','z']]
len_ = len(fields)
for i in range(len_):
driver.find_ele... | python|loops|for-loop|iteration|enumerate | 3 |
874 | 52,242,843 | How to render my Sudoku generator results to html table using Django? | <p>I am pretty new to Django and currently making a Sudoku web app. I wrote a python program to generate the Sudoku games, here is an example of the result/matrix looks like when i run the code (Sudoku Generator.py). </p>
<pre><code>[[3, 8, 2, 7, 5, 6, 1, 4, 9],[1, 4, 5, 2, 3, 9, 6, 7, 8],[6, 7, 9, 1, 4, 8, 2, 3, 5],... | <p>Asuming you use the variable <code>sudoku_numbers</code> to store your array of numbers, then in the template you can use something like this:</p>
<pre><code><table>
{% for row in sudoku_numbers %}
<tr>
{% for col in row %}
<td>{{ col }}</td>
{% endfor %}
</t... | javascript|python|html|django|sudoku | 0 |
875 | 69,135,482 | How to convert input stdin to list data structure in python | <p>I have a stdin data in this format:<br />
100 <br />
85 92 <br />
292 42<br />
88 33<br />
500<br />
350 36<br />
800 45<br />
0</p>
<p>I want something like this [[100, [85, 92], [292, 42], [88, 33]], [500, [350, 36], [800, 45], [0]]</p> | <p>Something like the following (I have tested) should do it:</p>
<pre><code>lst = []
sublst = []
for line in sys.stdin:
lineLst = [int(x) for x in line.split()]
if len(lineLst) == 1:
if sublst: lst.append(sublst)
sublst = lineLst
else:
sublst.append(lineLst)
if sublst[0] == 0: ... | arrays|python-3.x|stdin | 0 |
876 | 62,415,649 | How do I save to a specific directory using openpyxl? | <p>I am trying to save an Excel workbook I created using openpyxl to a specific directory that the user inputs via a Tkinter "browse" button. I have the workbook saving at the inputted "save spot," butI am getting an error saying that it is a directory. </p>
<p>Within the function that is producing the workbook, I hav... | <p>you need to provide full path to the desired folder please see example below</p>
<pre><code>from openpyxl import Workbook
wb = Workbook()
ws1 = wb.active
ws1.title = "1st Hour"
wb.save('/home/user/Desktop/FileName.xlsx')
</code></pre>
<p>so you might add additionally filename to the save_spot variable </p>
<pre><... | python|python-3.x|tkinter|openpyxl | 3 |
877 | 62,426,416 | Definining `fac` with generators. And: Why no stack overflow with generators? | <p>Is there a way we can define the following code (a classic example for recursion) via generators in Python? I am using Python 3.</p>
<pre class="lang-py prettyprint-override"><code>def fac(n):
if n==0:
return 1
else:
return n * fac(n-1)
</code></pre>
<p>I tried this, no success:</p>
<pre c... | <p>OK, after your comments I have completely rewritten my answer.</p>
<ol>
<li>How does recursion work and why do we get a stack overflow?</li>
</ol>
<p>Recursion is often an elegant way to solve a problem. In most programming languages, every time you call a function, all the information and state needed for the fun... | python | 1 |
878 | 36,547,848 | Python Request JSON | <p>I would like to check each JSON content type with my expectation type. I receive JSON in my python code like this:</p>
<pre><code>a = request.json['a']
b = request.json['b']
</code></pre>
<p>when I checked a and b type, it is always return Unicode. I checked it like this:</p>
<pre><code>type(a) # or
type(b) # (... | <p>I suspect you are on Python 2.x and not Python 3 (because in Python 3 both <code>type('a')</code> and <code>type(u'a')</code> are <code>str</code>, not <code>unicode</code>)</p>
<p>So in Python 2, what you should know is <code>str</code> and <code>unicode</code> both are subclasses of <code>basestring</code> so ins... | python|json|types | 3 |
879 | 19,686,429 | Python does not sort sql query result | <p><code>
results = conn.execute(SEARCH_SQL, dict(fingerprint="{"+fp_str+"}")).fetchall()
print sorted(results)
</code></p>
<p>I retrieve some datas from database by using sql alchemy. <code>results</code> is like that:</p>
<pre><code>[(0.515625, u'str1'), (0.625, u'str2'), (0.901042, u'str3')]
</code></pre>
<p>How... | <p>You have a list of tuples. How would you like to sort them?</p>
<p>For example, if you want to sort them according to the first key:</p>
<pre><code>sorted(results, key=lambda t:t[0])
</code></pre>
<p>or in reverse order:</p>
<pre><code>sorted(results, key=lambda t:t[0], reverse=True)
</code></pre> | python|sqlalchemy | 1 |
880 | 13,253,792 | list of class objects (birds). each bird has a color. how do I most efficiently get a set of all colors? | <p>I have a list of class objects, say birds. Each bird has a color. I want to easily get a set of bird colors from this list of birds. What is the quickest, most efficient way to do this?</p> | <p>That would probably be:</p>
<pre><code>set(bird.color for bird in birds)
</code></pre> | python | 5 |
881 | 54,433,453 | Create multiple Dataframe from XML based on Specific Value | <p>I am trying to parse an XML and save the results in Pandas Data-frame. I have succeeded in saving the details in one specific Data-frame. However now am trying to save the results in multiple data-frame based on one specific class value.</p>
<pre><code>import pandas as pd
import xml.etree.ElementTree as ET
import o... | <p>This is being answered with below method:</p>
<pre><code>def ExtractMOParam(xmlfile2):
tree2=etree.parse(xmlfile2)
root2=tree2.getroot()
df_list2=[]
for i, child in enumerate(root2):
for subchildren in (child.findall('{raml21.xsd}header') or child.findall('{raml20.xsd}header')):
for subchildren in (chil... | python-3.x|pandas|elementtree | 0 |
882 | 71,396,254 | If my function returns list index, what should it return if position does not exist | <p>I wrote a function that returns the index of an item in a list if that item exists, otherwise return False</p>
<pre><code>def student_exists(ID):
for student in students:
if student.id == ID:
return students.index(student)
return False
</code></pre>
<p>But then I realised that it can be a... | <p>You can return <code>None</code> if the item does not exist.</p>
<p>When you return <code>None</code>, you will avoid the location 0 problem. Note that when trying to ask if something is <code>None</code> you should use: <code>if x is None</code>.</p>
<p>Note that the <code>is</code> operator should be used for chec... | python | 2 |
883 | 39,203,422 | Scikit Learn Categorical data with random forests | <p>I am trying to work with the titanic survival challenge in kaggle <a href="https://www.kaggle.com/c/titanic" rel="nofollow">https://www.kaggle.com/c/titanic</a>.</p>
<p>I am not experienced in R so i am using Python and Scikit Learn for the <strong>Random Forest Classifier</strong></p>
<p>I am seeing many people u... | <p>If you just map levels to numeric values, python will treat your values as numeric. That is, numerically <code>1<2</code> and so on even if your levels were initially unordered. Think about the "distance" problem. This distance between 1 and 2 is 1, between 1 and 3 is 2. But what were the original distances betwe... | python|scikit-learn|random-forest | 6 |
884 | 55,309,793 | Python - Enforce specific method signature for subclasses? | <p>I would like to create a class which defines a particular interface, and then require all subclasses to conform to this interface. For example, I would like to define a class</p>
<pre class="lang-py prettyprint-override"><code>class Interface:
def __init__(self, arg1):
pass
def foo(self, bar):
... | <p>So, first, just to state the obvious - Python has a built-in mechanism to test for the <em>existence</em> of methods and <em>attributes</em> in derived classes - it just does not check their signature.</p>
<p>Second, a nice package to look at is <a href="https://zopeinterface.readthedocs.io/en/latest/" rel="norefer... | python|class|metaclass | 7 |
885 | 55,291,859 | Not all parameters were used in the SQL statement when using python and mysql | <p>hi I am doing the python mysql at this project, I initial the database and try to create the table record, but it seems cannot load data to the table, can anyone here can help me out with this</p>
<pre><code>import mysql.connector
mydb = mysql.connector.connect( host="localhost",user="root",password="asd619248636",... | <p>Changing the following should fix your problem:</p>
<pre><code>sql = "INSERT INTO record (temperature,humidity) VALUES (%s, %s)"
val = ("2.3","4.5") # You can also use (2.3, 4.5)
mycursor.execute(sql,val)
</code></pre>
<p>The database API takes strings as arguments, and later converts them to the appropriate datat... | python|mysql|python-3.x | 4 |
886 | 37,506,824 | syntax_error:update for dictionary | <p>How can I fix this?</p>
<pre><code># E.g. word_count("I am that I am") gets back a dictionary like:
# {'i': 2, 'am': 2, 'that': 1}
# Lowercase the string to make it easier.
# Using .split() on the sentence will give you a list of words.
# In a for loop of that list, you'll have a word that you can
# check for inclu... | <p>To update a key in a dictionary, just assign to the key using <code>[...]</code> subscription syntax:</p>
<pre><code>word_dict[word] = word_dict[word] + 1
</code></pre>
<p>or even</p>
<pre><code>word_dict[word] += 1
</code></pre>
<p>Your attempt is not valid syntax, for two reasons:</p>
<ul>
<li><code>word_dict... | python|string|dictionary | 2 |
887 | 7,438,666 | Python opencv not receiving camera feed | <p>I've been trying to use the SimpleCV (<a href="http://simplecv.org" rel="nofollow">www.simplecv.org</a>) module to run image recognition and manipulation. Unfortunately, my incoming video feed has been quite finicky, and I'm not sure what I did wrong. Just using some basic sample code:</p>
<pre><code>import cvwindo... | <p>I'm one of the SimpleCV developers. It appears you are trying to use the standard python openCV wrapper.</p>
<p>What I recommend doing is just run the example here:
<a href="https://github.com/sightmachine/SimpleCV/blob/develop/SimpleCV/examples/display/simplecam.py" rel="nofollow">https://github.com/sightmachine/... | python|opencv|camera|simplecv | 5 |
888 | 38,584,184 | Imputer on some Dataframe columns in Python | <p>I am learning how to use Imputer on Python.</p>
<p>This is my code:</p>
<pre><code>df=pd.DataFrame([["XXL", 8, "black", "class 1", 22],
["L", np.nan, "gray", "class 2", 20],
["XL", 10, "blue", "class 2", 19],
["M", np.nan, "orange", "class 1", 17],
["M", 11, "green", "class 3", np.nan],
["M", 7, "red", "class 1", ... | <p>This is because <code>Imputer</code> usually uses with DataFrames rather than Series. A possible solution is:</p>
<pre><code>imp=Imputer(missing_values="NaN", strategy="mean" )
imp.fit(df[["price"]])
df["price"]=imp.transform(df[["price"]]).ravel()
# Or even
imp=Imputer(missing_values="NaN", strategy="mean" )
df[... | python|scikit-learn|missing-data|imputation | 17 |
889 | 40,446,650 | Why is it dataframe.head() in python and head(dataframe) in R? Why is python like this in general? | <p>Beginner here. Shouldnt the required variables be passed as arguments to the function. Why is it variable.function() in python?</p> | <p>It's simple:</p>
<p><code>foo.bar()</code> does the same thing as <code>foo.__class__.bar(foo)</code></p>
<p>so it <em>is</em> a function, and the argument <em>is</em> passed to it, but the function is stored attached to the object via its class (type), so to say. The <code>foo.bar()</code> notation is just shorth... | python | 0 |
890 | 26,169,593 | Adding default file directory to FileDialog in Traits | <p>I am using the FileDialog class within TraitsUI, which works pretty well, except for the life of me, I have not been able to figure out how to pass a <em>default</em> directory, for the dialogue to use. </p>
<p>Ideally, the dialogue box would open at a point in the local file system other than the top of the tree.... | <p>I suggest <em>not</em> using the TraitsUI FileDialog. I think you'll do better with pyface.api.FileDialog (toolkit-specific; for the API, see <a href="https://github.com/enthought/pyface/blob/master/pyface/i_file_dialog.py" rel="nofollow">https://github.com/enthought/pyface/blob/master/pyface/i_file_dialog.py</a>).<... | python|file|enthought|traitsui | 2 |
891 | 26,086,365 | Why is PySide's exception handling extending this object's lifetime? | <p><strong>tl;dr -- In a PySide application, an object whose method throws an exception will remain alive even when all other references have been deleted. Why? And what, if anything, should one do about this?</strong></p>
<p>In the course of building a simple CRUDish app using a Model-View-Presenter architecture with... | <p>The problem is <code>sys.last_tracback</code> and <code>sys.last_value</code>.</p>
<p>When a traceback is raised interactively, and this seems to be what is emulated, the last exception and its traceback are stores in <code>sys.last_value</code> and <code>sys.last_traceback</code> respectively.</p>
<p>Doing</p>
<... | python|exception-handling|garbage-collection|pyside | 3 |
892 | 32,342,729 | Pass object along with object method to function | <p>I know that in Python that if, say you want to pass two parameters to a function, one an object, and another that specifies the instance method that must be called on the object, the user can easily pass the object itself, along with the name of the method (as a string) then use the <code>getattr</code> function on ... | <p>A method is just a function with the first parameter bound to an instance. As such you can do things like. </p>
<pre><code># normal_call
result = "abc".startswith("a")
# creating a bound method
method = "abc".startswith
result = method("a")
# using the raw function
function = str.startswith
string = "abc"
res... | python|class|object|parameters | 9 |
893 | 32,410,103 | Django rest framework is taking too long to return nested serialized data | <p>We are having four models which are related, While returning queryset serializing the data is too slow(serializer.data). Below are our models and serializer.</p>
<p>Why django nested serializer is taking too long to return rendered response. What are we doing wrong here?</p>
<p>Note:Our DB lies in AWS when connect... | <p>Did you checked which part is the slow one? like, How many records do you have in that db? and I would try to run the query and check if the query is slow, then I'd check the serializers with less than 100 registers and so on.</p>
<p>I'd recommend you to read this article <a href="http://www.dabapps.com/blog/api-pe... | python|django|api|rest|django-rest-framework | 2 |
894 | 44,050,853 | Pandas json_normalize and null values in JSON | <p>I have this sample JSON</p>
<pre><code>{
"name":"John",
"age":30,
"cars": [
{ "name":"Ford", "models":[ "Fiesta", "Focus", "Mustang" ] },
{ "name":"BMW", "models":[ "320", "X3", "X5" ] },
{ "name":"Fiat", "models":[ "500", "Panda" ] }
]
}
</code></pre>
<p>When I need to con... | <p>You can fill <code>cars</code> with empty dicts to prevent this error</p>
<pre><code>data['cars'] = data['cars'].apply(lambda x: {} if pd.isna(x) else x)
</code></pre> | python|json|pandas | 10 |
895 | 44,129,680 | extracting data from json using python | <p>Extracting Data from JSON</p>
<p>The program will prompt for a URL, read the JSON data from that URL using urllib and then parse and extract the comment counts from the JSON data, compute the sum of the numbers in the file.</p>
<p>Sample data: <a href="http://python-data.dr-chuck.net/comments_42.json" rel="nofollo... | <p>You could try:</p>
<pre><code>import json
import urllib
total = 0
url='http://python-data.dr-chuck.net/comments_42.json'
uh=urllib.urlopen(url).read()
info =json.loads(uh)
count_values = [ el['count'] for el in info['comments'] ]
name_values = [ el['name'] for el in info['comments'] ]
print count_values
print n... | python | 1 |
896 | 44,275,166 | Simpler way with datetime time deltas? | <p>and thanks in advance! I've got a function I wrote that generates and appends a url to a list in the form of "<a href="http://www.examplesite.com/" rel="nofollow noreferrer">http://www.examplesite.com/</a>'year' + '-' + 'month'", appending a string format of the given year for each month. The function works just f... | <p>You have to subtract 1 to decrease the year even using datetime object as:</p>
<pre><code>>>> from datetime import date
>>> print date.today().year - 1
</code></pre>
<p>result is 2016. I think the way you process year is good enough.</p>
<p>just want to simplify the month, using range() other t... | python|python-3.x|datetime | 0 |
897 | 44,254,759 | Ajax query not working in python django? | <p>I want to change the status of data coming from table but it seems like like i have messed up some code in it.</p>
<p>my ajax request:-</p>
<pre><code>function changeStatusDataById(object) {
var baseURL = location.protocol + '//' + location.hostname + (location.port ? ':' + location.port : '');
var r = con... | <p>i was just missing / on the url when i was calling ajax.</p>
<pre><code> $.ajax({
url: baseURL + '/promoted-user/list/changeStatus/',
method: 'POST',
dataType: "json",
contentType: "application/json",
data: JSON.stringify(requestData),
beforeS... | jquery|python|ajax|django | 0 |
898 | 32,885,411 | Access coastal outlines (e.g. from Basemap, or somewhere else) without installing Basemap | <p>I would like to have polygons or vertices of coastlines on the Earth to manipulate in Blender (and in Python stand-alone), but I would like to avoid installing into each of the multiple Pythons on my computer. Basically it looks a bit tricky to do once, much less four times.</p>
<p>All I want is points along coastl... | <p>I found a simple solution which does not involve Basemaps or the like, thanks to the answer in GIS.stackexchange <a href="https://gis.stackexchange.com/q/164930/60078">here</a></p>
<p>I am reposting some of the info here:</p>
<p><em>The answer by @artwork21 is the accepted answer. I am just adding some supplementa... | python|blender|matplotlib-basemap | 0 |
899 | 34,827,141 | Evaluating the performance gain from multi-threading in python | <p>I tried to compare the performance gain from parallel computing using multithreading module and the normal sequence computing but couldn't find any real difference. Here's what I did:</p>
<pre><code>import time, threading, Queue
q=Queue.Queue()
def calc(_range):
exponent=(x**5 for x in _range)
q.put([x**0.... | <p>The reference implementation of Python (CPython) has a so-called interpreter lock where always one thread executes Python byte-code. You can switch for example to IronPython which has no GIL or you can take a look at the multiprocessing module which spawns several Python processes which can execute your code indepen... | python|multithreading | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.