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
4,800
30,272,269
Python text extraction does not work on some pdfs
<p>I am trying to read a pdf through url. I followed many stackoverflow suggestions and used PyPdf2 FileReader to extract text from the pdf. My code looks like this :</p> <pre><code>url = "http://kat.kar.nic.in:8080/uploadedFiles/C_13052015_ch1_l1.pdf" #url = "http://kat.kar.nic.in:8080/uploadedFiles/C_06052015_ch1_l1...
<p>If you read the comments in the pyPDF documentation you'll see that it's written right there that this functionality will not work well for some PDF files; in other words, you're looking at a restriction of the library.</p> <p>Looking at the two PDF files, I can't see anything wrong with the files themselves. But.....
python|pdf|web-scraping|pypdf|pdfminer
3
4,801
61,287,301
PyQtGraph: stop execution without process manager
<p>I'm trying to use the module <em>pyqtgraph</em> in <strong>python</strong> to plot some real time data but the program stucks in the plot, I mean, once I close the plot window the program doesn't stop running and I have to kill it using process manager.</p> <p>Even with a simple code such as this one, the same happ...
<p>Qt should automatically exit once all of its windows have closed. The example you posted works fine if I run it from a command line. </p> <p>As eyllanesc pointed out in the comments, spyder is known to interfere with some Qt operation if it is not configured correctly.</p>
python|pyqtgraph
0
4,802
65,558,799
Flask: db is not being referenced properly when importing into my database seeder script
<pre><code># project\__init__.py from flask import Flask from flask_mysqldb import MySQL from .config import app_config db = MySQL() def create_app(config_name): app = Flask(__name__, instance_path=os.path.join(os.path.dirname(__file__), 'instance'), instance_relative_config=True) app....
<blockquote> <p>My database connection works fine when I host the app and carry out CRUD operations using the interface in my browser. Such as login, sign up, create a shipment.</p> </blockquote> <p>This indicates to me that you are correctly connecting to your db for each request.</p> <blockquote> <p>However, when I r...
python|mysql|flask
0
4,803
65,752,249
Indefinite while loop not exited by giving it empty str
<p>Can someone please explain to me why this program returns an error about not being able to convert <code>''</code> to <code>int</code>? I know it can't be converted, but why does it even go into the while loop after entering <code>''</code>?</p> <pre class="lang-py prettyprint-override"><code>x = input('Enter a numb...
<p>You're not checking if <code>x</code> equals <code>''</code> in between getting it via <code>input</code> and attempting to pass it to <code>int</code>:</p> <pre class="lang-py prettyprint-override"><code> x = input() if difference &lt; int(y) - int(x): </code></pre> <p>It's <em>already</em> in the while loop...
python
1
4,804
72,145,742
Django 3.2: AttributeError: 'NoneType' object has no attribute 'attname'
<p>I am working with Django 3.2, and have come across a problem that seems to have answers <a href="https://stackoverflow.com/questions/46360477/attributeerror-nonetype-object-has-no-attribute-attname-django">here</a> and <a href="https://stackoverflow.com/questions/67628299/attributeerror-nonetype-object-has-no-attrib...
<p>The problem seems to be that the <a href="https://github.com/django/django/blob/08e6073f878264a0c091da0d3db456820252ef6c/django/db/models/base.py#L406" rel="nofollow noreferrer"><code>__init__</code></a> method from the django <code>Model</code> class never gets called. This is because an <code>__init__</code> metho...
python|django|django-models
1
4,805
43,100,154
Python error : index out of bounds
<p>I was curious about image processing with python, so I found this great library imageio, I tried to manipulate the pixels of a picture and save them in a new file, but i had some problems with the loops this is what the code looks like <a href="https://i.stack.imgur.com/9v9zU.png" rel="nofollow noreferrer">enter im...
<p>Because your image doesn't have squarred shape, reshape it before you go through your loop</p>
python|image-processing|python-imageio
1
4,806
36,828,348
Pandas read_csv, reading a csv file with a missing header element
<p>I'm trying to import a csv file with pandas.read_csv. The file is as follows:</p> <pre><code> "COL_A","COL_B","COL_C" "ROW1COLA","ROW1COLB","ROW1COLC","ROW1COLD" "ROW2COLA","ROW2COLB","ROW2COLC","ROW2COLD" "ROW3COLA","ROW3COLB","ROW3COLC","ROW3COLD" "ROW4COLA","ROW4COLB","ROW4COLC","ROW4COLD" ...
<p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow"><code>read_csv</code></a> with parameters <code>header=0</code> which first row set to columns and then is overwritten by parameter <code>names</code> to custom column names. Parameter <code>sep=',...
python|csv|pandas
4
4,807
20,026,876
animate visibility of QButtonGroup or layout containing it
<p>I want to place group of buttons ontop of a QLabel showing image, the question is how do I animate the fade in visibility of the QButtonGroup, I want to place my buttons at the bottom area so whenever pointer is at the bottom area the button group should animate to fully visible but if I move the pointer out of the ...
<p>I did same thing with QLabels, QButtons and other Widgets. There are different solutions accordingly on what you need. In my case I just created a custom component with a <code>QTimer</code> and a <code>QGraphicsOpacityEffect</code>. The timer increases or decreases the opacity value (by a coefficient)..</p>
python|qt|pyqt4|fadein
0
4,808
66,889,597
Slice a dataframe based on a specific range repeated over a column in pandas
<p>I have a dataframe with one of the columns having a counter. The counter goes from 0-127 and is repeated. The start and end of dataframe can have sliced counters, for example first row could start with 32 but would end at 127, then 0-127 repeated slices and the last slice could end abruptly not necessarily being 127...
<p>Well if the total number of rows is not a multiple of 128, no you will no be able to slice the dataframe in subsets each containing exactly 128 rows.</p> <p>But it is trivial to slice the dataframe in slices of 128 rows, the last of them having <em>at most</em> 128 rows with <code>iloc</code>:</p> <pre><code>for i i...
python|pandas|csv
0
4,809
66,951,760
Extract data from website and save the excel with every extraction
<p>I have a Python script where I extract data from a website using multiple URLs saved in excel. Currently, I have a script that saves the collected information in an excel file after looping the entire URLs available in excel. Now the problem arises when the extraction interrupts due to network or any other way nothi...
<p>The improvements needed are a bit broad so I'll summarise:</p> <ol> <li><p><a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_excel.html" rel="nofollow noreferrer"><code>df.to_excel()</code></a> and <code>df.to_csv()</code> will overwrite the target file each time it's written, so it can only ...
python
0
4,810
66,954,978
How to run functions in forward order from lambda functions (Python)
<p>I'm trying to convert the function below to the lambda function. And this function below has some functions that need to be executed in order. I searched many times, but there aren't have any clues. What I trying to convert is</p> <pre class="lang-py prettyprint-override"><code>def drawSquare(moveLength): A_Turt...
<h2>Before, A Disclaimer</h2> <p>This use of <a href="https://stackoverflow.com/questions/8049798/understanding-nested-list-comprehension">list comprehension</a> in Python is problematic because it can hide the semantics of the code and I would advice you not to use it in this case. Your code is fine as is, but you can...
python|function|lambda|nested
0
4,811
64,541,111
How normalize non-uniform Python dataframe
<p>dataframe-1 I am showing below was one row in my primary dataframe.</p> <p>I used [][] notation to retrieve that only row I wanted as a dictionary from which I created this dataframe-1 below.</p> <p>My question is how can I make all the 'keys' as columns and 'values' as row value and store it in dataframe-2?</p> <p>...
<p>I think you want to:</p> <ol> <li>Unpivot the columns using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.melt.html" rel="nofollow noreferrer">pandas.melt()</a> method</li> <li>apply the <code>pandas.DataFrame.dropna()</code> method</li> <li>apply <a href="https://pandas.pydata.org/panda...
python|json|dataframe
0
4,812
64,178,655
Pandas Dataframe not able to store decimal values
<p>I need to store values that can have values upto 5 decimal point value but pandas is storing them all as 0. A piece of code to perform can be found below where GDF is an empty dataframe with row name 'A' and i am trying to place in a value at a particular cell in row A where the word Cl is located. Please help</p> <...
<p>Try to change the default used for printing frames by :</p> <pre><code>pandas.set_option(&quot;display.precision&quot;, 6) </code></pre>
python|pandas
0
4,813
70,443,791
Why total keeps equalling 0 ? Help me please
<p>I am new to Python, right here I'm trying to get the value of x, y and z from input and calculate the total. But total keeps equalling 0?</p> <p>Please help me, thank you so much</p> <pre><code> total = 0 x = 0 y = 0 z = 0 prices = [x, y, z] i = 0 while i &lt; 3: purchase = int(input('pu...
<p>You add the purchases to the variables x, y and z but never update the array so when you add up the total, you're adding an array filled with nothing.</p> <p>You could do this, using the array and its index:</p> <pre><code>total = 0 x = 0 y = 0 z = 0 prices = [x, y, z] i = 0 while i &lt; 3: purchase = int(input...
python-3.x
0
4,814
73,322,027
Which specific heteroskedasticity test is included in Python pmdarima auto_arima() results?
<p>I posted this question some time ago ago on <a href="https://stats.stackexchange.com/questions/582063/which-specific-heteroskedasticity-test-is-included-in-python-pmdarima-auto-arima">CrossValidated</a>, but no one has been able to answer it yet, so I've decided to post it here just in case:</p> <p>I'm using <code>a...
<p>I've stumbled upon this question while searching for the same question.</p> <p>Now, I realize this does <em>not</em> answer your specific question - i.e. which test specifically the <code>summary()</code> method shows the results for - but in that example above <code>Prob(H) (two-sided)</code> suggests the same resu...
python|time-series|arima|pmdarima
0
4,815
64,818,455
Concatenate list of 1d numpy arrays to 2d numpy
<p>I have object contain list of numpy, like the follow:</p> <pre><code>[array([1, 2, 6]), array([1, 2, 7]), array([1, 2, 3]), array([3, 4, 3]), array([5, 6, 9]), array([5, 6, 7])] </code></pre> <p>How to build one numpy from them, like the follow?</p> <pre><code>[[1,2,6], [1,2,7], [1,2,3], [3,4,3], [5,6,9], ...
<pre><code>l = [array([1, 2, 6]), array([1, 2, 7]), array([1, 2, 3]), array([3, 4, 3]), array([5, 6, 9]), array([5, 6, 7])] np.stack(l) </code></pre> <p>Output -</p> <pre><code>array([[1, 2, 6], [1, 2, 7], [1, 2, 3], [3, 4, 3], [5, 6, 9], [5, 6, 7]]) </code></pre>
python|list|numpy
1
4,816
63,789,459
Access denied for user 'root'@'localhost' error even after grant the privileges to root @localhost in python pyspark
<p>I want to read the data from Mysql on terminal using JDBC driver in python pyspark. However, I keep getting the same issue of error <code>Access denied for user 'root'@'localhost'</code> error even after I've grant the privileges for the <code>root@localhost</code>.</p> <p>My code:</p> <pre><code>spark.read.format(&...
<p>Solved:</p> <p>change the host in the url</p> <pre><code>&quot;url&quot;,&quot;jdbc:mysql://XXX.XXX.XXX.X:3306/users&quot; </code></pre>
python|jdbc|pyspark
1
4,817
53,015,456
Flask passing uploaded file to another service using requests
<p>I have Python flask webservice that takes in a file:</p> <p>Headers: </p> <p>Content-type: multipart/formdata</p> <p>Content:</p> <p>"fileTest": UPLOADED FILE</p> <p>When I pass the file to another service using requests lib, I get issue where the uploaded file is not passed.</p> <p>My Code:</p> <pre><code>fi...
<p>You need to follow requests document.</p> <blockquote> <p><a href="http://docs.python-requests.org/en/master/user/quickstart/#post-a-multipart-encoded-file" rel="nofollow noreferrer">http://docs.python-requests.org/en/master/user/quickstart/#post-a-multipart-encoded-file</a></p> </blockquote> <pre><code>url = 'h...
python-2.7|flask|python-requests
0
4,818
65,472,865
Module installation Problem in Pypy Windows 10
<p>I am trying to install packages to my pypy module however it keeps giving me this error. I am interested in installing the pandas module however giving me this error. I am on a windows 10 setup. This is the cmd output of the error. The pypy module is installed in the correct full path and all but its giving me error...
<p>why are you using <code>pypy3</code>???</p> <p>just use <code>pip install numpy</code> , <code>pip install pandas</code> ... and so one.</p> <p>I strongly recommend you uninstall python and all your packages and then reinstall them correctly, either from <a href="https://www.anaconda.com/products/individual" rel="n...
python-3.x|list|cmd|module
0
4,819
71,898,763
Can I add two classes to an element in html in other places?
<p>I'm write template (in particular, pagination) for Flask, but dont know, how to safe class &quot;page-item&quot; and give class &quot;disabled&quot;</p> <pre><code>&lt;li class=&quot;page-item&quot; {% if pages.has_prev %} class=&quot;disabled&quot; {% endif %}&gt; </code></pre>
<p>You can have multiple classes, but you can't have multiple <code>class</code> attributes. They all have to be in the same attribute.</p> <p>Put the <code>if</code> inside the <code>class</code> attribute.</p> <pre><code>&lt;li class=&quot;page-item {% if pages.has_prev %} disabled {% endif %}&quot; &gt; </code></pre...
python|html|flask
0
4,820
61,972,916
Iteration/double iteration over a nested list in Python
<p>I'm sorry if a similar question was answered here already, but maybe i don't know how to find it.</p> <p>I have some lists who look like this: </p> <pre><code>A1, A6 = [157, 157, 0], [407, 157, 0] A2, A7 = [207, 157, 0], [457, 157, 0] </code></pre> <p>Then i grouped them using another list:</p> <pre><code>A_LIST...
<p>This should work:</p> <pre><code>def between(x, val): if val &lt;= x &lt;= val + 50: return True else : return False # don't forget this one if click != (0, 0, 0): # i = 0 &lt;-- don't need this line for i in A_LIST: if between(mouse_x, i[0]) and between(mouse_y, i[1]) : ...
python|list|iteration
0
4,821
60,621,699
Python Write lines of a text in between a range of numbers to a new file
<p>Sample Text File:</p> <pre><code>1. some text here 2. more text here more text here more text here more text here 3. more text here more text here more text here more text here 4. more text here more text here more text here more text here 5. more text here more text here more text here more text here 6. last text ...
<p>One simple approach would be to split the file at each line that starts with <code>1.</code>:</p> <pre><code>import re with open("text.txt") as txt_file: content = txt_file.read() chunks = [] for match in re.split(r"(?=^1\.)", content, flags=re.MULTILINE): if match: chunks.append(mat...
python|file|text|readlines
4
4,822
71,287,034
How to filter a df based on user input
<p>I am trying to implement an auto complete feature on a flask app where I want that when the user input characters, a windows will appear with options with stock symbols.</p> <p>My current /search html is basic intentionally becaue I want to debug as I go along</p> <pre><code>def search(): from ftplib import FTP ...
<p>try applying fstrings like that:</p> <pre><code>nasdaq_exchange_info=nasdaq_exchange_info.query(f&quot;Security_Name.str.contains({request.args.get('q')}, case=False)&quot;) </code></pre>
javascript|python|pandas|flask
0
4,823
11,373,380
How to disable copy/paste or download a file from a file preview in plone 4.1?
<p>I have registered javascript under portal_javascript using the answer 1 from <a href="https://stackoverflow.com/questions/9958478/how-to-disable-copy-paste-browser">How to Disable Copy Paste (Browser)</a> steps I followed: 1> copied the script in a file </p> <pre><code>document.onkeydown = function(e) { if (e....
<p>Try this to prevent default behaviour.</p> <pre><code>document.onkeydown = function(e) { if (e.ctrlKey &amp;&amp; e.keyCode === 65) { alert('not allowed'); } if (e.ctrlKey &amp;&amp; e.keyCode === 67) { alert('not allowed'); } if (e.ctrlKey &amp;&amp; e.keyCode === 86) { ...
javascript|python|plone
2
4,824
11,253,338
Can't override default kwarg value of False in template inclusion tag
<p>I've written this template inclusion tag:</p> <pre><code>@register.inclusion_tag('blog/post_detail.html') def post_detail(post, show_meta=True): return { 'post': post, 'show_meta': show_meta } </code></pre> <p>And I call it like this:</p> <pre><code>{% post_detail post show_meta=False %} <...
<p><code>True</code> and <code>False</code> are not defined in the template context by default, and by the normal template language rules, non-existent names are treated as False. Try passing 0 and 1 instead.</p>
python|django|django-templates
1
4,825
60,938,359
How to get Python to run JavaScript on a open chrome tab?
<p>I've made a python script that grabs IPs you connect to on a website and stores them. I'm checking each time since I don't want to connect to the same IP twice. (This is a bit buggy since I get multiple requests, if someone can explain how to put a timer on the skip call without disrupting the rest of the program).<...
<p>you can use a webdriver for the desired browser and execute javascript code in the browser head and then execute javascript in the browser head from python code much like the auto login commented feature in this application <a href="https://github.com/engMaher/BAF/blob/master/BAF_0.2.0.py" rel="nofollow noreferrer"...
javascript|python
0
4,826
66,055,368
Passing string argument from bash script to python3
<p>I am trying to read multiple directory locations from a text file using a bash script and pass as argument to another python script. The directory name contains space which shows</p> <pre><code>test.py: error: unrecognized arguments: 1B/PHASE/PHASE_90 </code></pre> <p>I am using following bash script:</p> <pre><code...
<p>You should just <a href="https://www.gnu.org/software/bash/manual/html_node/Quoting.html" rel="nofollow noreferrer">quote</a> <code>$line</code> like <code>python3 test.py -i &quot;$line&quot;</code> to group the argument. You can use tools like <a href="https://www.shellcheck.net/" rel="nofollow noreferrer">shellch...
python|bash|python-3.8
2
4,827
69,094,888
How can I maintain Date Range Searched Result in Django views and Pagination
<p>I have a date range search query with the total of the result which is displayed in django templates using loop in a table with pagination. And whenever the date range result exceeds one page and I click on the next page, the following page now display all the list of query that was initialize firstly in the views t...
<p>This is happening becouse when you change the page, you are not sending a POST request. So your entire function won't work. Paginator is made to build a single page with pagination inside, not to build a request type function</p> <pre><code>def SearchIncomeRange(request): searchForm = IncomeSearchForm(request.PO...
python|django
0
4,828
69,133,918
Generate two arrays from a list of pairs
<p>Suppose I have the following arrays</p> <pre><code>a = [1, 2, 3] b = [4, 5, 6] </code></pre> <p>And I created the list</p> <pre><code>c = [(1,4), (1,5), (1,6), (2,4), (3,5), (2,6), (3,4), (3,5), (3,6)] </code></pre> <p>How can I create two lists as follows:</p> <pre><code>a = [1, 1, 1, 2, 2, 2, 3, 3, 3] b = [4, 5, 6...
<p>You can <code>zip</code> with tuple unpacking here.</p> <pre><code>a, b = zip(*c) print(a) # (1, 1, 1, 2, 3, 2, 3, 3, 3) print(b) # (4, 5, 6, 4, 5, 6, 4, 5, 6) </code></pre> <hr /> <p>Since, numpy is tagged, you can directly generate the required data using <a href="https://numpy.org/doc/stable/reference/generated/n...
python|arrays|list|numpy
2
4,829
68,200,316
Ready server with a queue of tasks
<p>If you don't like this question, please recommend improvements</p> <p>Could you please recommend python libraries for this archirecture <a href="https://i.stack.imgur.com/HjiZy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HjiZy.png" alt="enter image description here" /></a></p> <p>Idea of the w...
<p>Python standard library has what you want : <a href="https://docs.python.org/3/library/threading.html" rel="nofollow noreferrer"><code>threading</code></a>, <a href="https://docs.python.org/3/library/queue.html" rel="nofollow noreferrer"><code>queue</code></a>, <a href="https://docs.python.org/3/library/http.server....
python|server
0
4,830
68,369,498
Django logout function stopped working when creating userprofile function
<p>I am learning Django by creating a project.</p> <p>The problem I am facing is that the user logout function stopped working after I created another function to view user profile in <code>view.py</code>.</p> <p>Here are my codes in <code>view.py</code></p> <pre><code>from django.shortcuts import render, redirect from...
<p>You can try to make the <code>Logout</code> function in your template a <code>form</code> that would be:</p> <p><code>template.html</code></p> <pre><code>&lt;form action=&quot;{% url 'tech_user:logouturl' %}&quot; method='POST'&gt; {% csrf_token %} &lt;button type=&quot;submit&quot;&gt;Log out&lt;/button&gt;...
python|django|django-models|django-views
0
4,831
59,242,783
image classifier 'Node' object has no attribute 'output_masks'
<p>hiya so ive been doing this image classifier project for university and ive been having trouble with how to use the models and what codes to use and if im doing everything right ive been reading this but i still dont know why i keep getting errors <a href="https://keras.io/applications/#vgg16" rel="nofollow noreferr...
<p>There is an issue on GitHub regarding this subject <a href="https://github.com/keras-team/keras/issues/10907" rel="nofollow noreferrer">GitHub Keras 10907</a></p> <p>In the posts there is something about tensorflow and keras relation:</p> <blockquote> <p>I had a similar issue, but with different architecture. As...
python
1
4,832
59,434,649
lambda function not working in multi-process
<p>I'm trying to use lambda function for multiple arguments in multi-process. However, it is not working properly. There is no run-time error but the CPU is not working on python according to activity monitor. However, <code>repeat</code> function is working normally. My code is shown below:</p> <pre><code>def testfun...
<p>In module <a href="https://docs.python.org/3/library/multiprocessing.html" rel="nofollow noreferrer">multiprocessing</a> you could use <a href="https://docs.python.org/3/library/multiprocessing.html#multiprocessing.pool.Pool.starmap" rel="nofollow noreferrer">starmap</a> instead of <code>map</code> with <code>lambda...
python|python-multiprocessing
1
4,833
63,193,121
Why does my code for removing the even numbers from the beginning of a list not work?
<pre class="lang-py prettyprint-override"><code>def delete_starting_evens(lst): for i in lst: if i%2==0: lst.remove(i) else: break return lst </code></pre> <p>The given code produces unexpected results, but I'm not able to figure out from the output where the problem lies.</p>
<p>That's because you're suppressing items of a list your for-loop is iterating on. Hence it suppresses half of your items. For instance if you call your function on list <code>[2, 2, 4, 6, 1]</code> it will delete the first 2 of your list then move to <code>lst[1]</code> which is 4 (after deletion of the first 2), d...
python-3.x|list|error-handling
0
4,834
62,048,679
Creating multiple boxplots using plotly
<p>I'm trying to replicate the following boxplot I made in matplotlib using plotly:</p> <p><img src="https://i.stack.imgur.com/Ouq1b.png" alt=""></p> <hr> <p>My data is in a very simple dataframe imported from an Excel file and looks like follows:</p> <h2><img src="https://i.stack.imgur.com/7rYpY.png" alt=""></h2> ...
<p>You can use <code>plotly.express</code> or <code>plotly.graph_objects</code>.</p> <p><em>Reading data:</em></p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.read_csv(r'Documents\test.csv', sep=',') print(df) print(df.to_dict()) </code></pre> <pre><code> p=0; t=0 p=1; t=6&quot; p=1...
python|python-3.x|matplotlib|plotly|boxplot
4
4,835
35,469,731
Tensorflow GPU error: ImportError: libcudart.so.7.0: cannot open shared object file: No such file or directory
<p>This is the traceback,</p> <pre><code>&gt;&gt;&gt; import tensorflow Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/home/eldor4do/tensorflow_gpu/lib/python2.7/site-packages/tensorflow/__init__.py", line 23, in &lt;module&gt; from tensorflow.python import * File "...
<p>Your problem is cuda7.5. As far as I understand, TensorFlow is linked in a way that it only works with cuda7.0. You either need to build it from source, or degrade your local cuda version to 7.0 (as an option, create a docker container and install lower version of cuda there, if you need 7.5 for other purposes).</p>
tensorflow
0
4,836
35,383,449
Remove duplicate columns only by their values
<p>I just got an assignment which i got a lot of features (as columns) and records (as rows) in a csv file.</p> <p>Cleaning the data using Python (including pandas):</p> <pre><code>A,B,C 1,1,1 0,0,0 1,0,1 </code></pre> <ol> <li><p>I would like to delete all the duplicate columns with the same values and to remain on...
<blockquote> <p>I would like to delete all the duplicate columns with the same values and to remain only one of them. <code>A</code> will be the only column one to remain.</p> </blockquote> <p>You mean that's the only one among the <code>A</code> and <code>C</code> that's kept, right? (<code>B</code> doesn't duplica...
python|pandas
1
4,837
59,626,774
using named models in symfit python module for fitting with a gaussian distribution
<p>I am trying to write a code for fitting two data set with two different equation with some shared parameters simultaneously with symfit module. it is too complicated to show it here so I show another code with the same command and simpler. Here I tried to fit a series of data with a linear function but with a gauss...
<p>You could try replacing <code>Model</code> with <code>GradientModel</code> or even <code>CallableModel</code>. The problem arises because by default the Hessian of the model is computed and for a gaussian this produces a <code>DiracDelta</code> which is not simplified away. Using either of these other models does no...
python|gaussian|symfit
0
4,838
49,339,512
Iterate to find the repeat values in Pandas dataframe
<p>Window 10, Python 3.6</p> <p>I have a dataframe df </p> <pre><code>df=pd.DataFrame({'name':['boo', 'foo', 'too', 'boo', 'roo', 'too'], 'zip':['30004', '02895', '02895', '30750', '02895', '02895']}) </code></pre> <p>I want to find the repeat record that has same 'name' and 'zip', and record the re...
<p>I believe you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>groupby</code></a> all columns and use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.size.html" rel="nofollow noreferrer"><code...
python|pandas|loops
2
4,839
60,078,017
How can i captured detected images of face in opencv to make a database?
<p>I am trying to enroll the faces of the user in opencv for facial recognition. I have finihed the detection part but what i wanted to achieve is to save the detected faces.So basically waht i wanted to achieve is : when i see in the webcam it automatically capture 20-30 or n no images and saves it locally.</p> <p>Cu...
<p>If only one person is looking at the camera in a given scenario, you can use a counter. </p> <pre><code>N = 20 cnt = 0 while True: ... ... # If the frame contains only one face for (x,y,w,h) in faces: cv2.rectangle(frame,(x,y),(x+w,y+h),(255,255,0),4) faceimg=frame[y:y+h,x:x+w] ...
python|opencv|image-processing|facial-identification
1
4,840
65,498,255
Why is filtering with multiple conditions not working?
<p>I need to filter my DataFrame based on two conditions. I need to filter out any observation where cause = 'fire' AND the flag = 1. It can be fire and flag = 0. It can be flag = 1 and cause != 'fire'. Just not both at the same time.</p> <p>I tried the following:</p> <pre><code> df.loc[(df['flag'] != 1) &amp; (df[...
<p>built a DF with contents you defined. Make sure you code your logic. You state NOT(cause==&quot;Fire&quot; AND flag==1)</p> <pre><code>import random c = [&quot;Fire&quot;,&quot;Water&quot;] df = pd.DataFrame({&quot;flag&quot;:[random.randint(0,1) for r in range(10)], &quot;cause&quot;:[c[random.randint(0,1)] for ...
python|pandas|pandas-loc
0
4,841
50,872,953
sorting of list of lists in python
<p>how can i sort a list of list in python with use of bubble sort datewise??</p>
<p>You can use <code>sorted.</code> with <code>lambda</code> in <code>key</code></p> <p><strong>Ex:</strong></p> <pre><code>import datetime l = [['sana', '2017-09-11', '76', '5af50d3b6528870010a42a1c', '', ''], ['sana', '2018-05-11', '75', '5af50e046528870010a42a1d', '', ''], ['sana', '2017-11-11', '70', '5af50e8a652...
python
2
4,842
26,580,905
Python math logic error
<pre><code>for i in range(1,11): print(i,end=":") if i &lt; 100: square = i * i print(square) </code></pre> <p>so with the code above ill get the following output:</p> <pre><code>1:1 2:4 3:9 4:16 5:25 6:36 7:49 8:64 9:81 10:100 </code></pre> <p>now I am trying to add the total of the numbers ...
<p>Because you did't defined total before and you are adding twice the square instead of adding the square to total.</p> <p>FROM:</p> <pre><code>for i in range(1,11): print(i,end=":") if i &lt; 100: square = i * i total = square + square print(square) print(total) </code></pre> <p>TO:...
python|math
0
4,843
61,310,942
Invalid character identifier error within a data dictionary
<p>I am trying to make dataframe for a final project at school. I have already calculated the numbers for everything, however, Python is not happy with the data dictionary that I am making. I have tried making the numbers into strings but the same syntax error kept popping up and I'm not sure on what to do about it. </...
<p>When I look at this code in Vim, I see &lt;202c> periodically throughout your lists. That is what is causing the problem. You may want to look at it with a different text editor in order to remove those factors.</p> <p>Try copying this :</p> <pre><code>avg_pm10_traffic_joint= {'Average Cycle Length (Min)': [2.9444...
python|syntax-error|data-dictionary|invalid-characters
1
4,844
61,183,878
Python - Calling a function from a different class to draw a line using PyQt Error: "'sip.wrappertype'"
<p>I am trying to create two classes using PyQt to create a gui like so;</p> <pre><code>import sys from PyQt5.QtGui import QPainter, QPen, QBrush from PyQt5.QtWidgets import QWidget, QApplication from PyQt5.QtCore import Qt, QRect, QPoint class line(): def makeline(): qp.drawLine(250,250,350,300) test = ...
<p>In your code, <code>qp</code> does not exists in the scope of <code>makeline</code>.</p> <p>Creating a new one like you did won't help for two reasons:</p> <ul> <li>you are trying to paint on a class, but QPainter can only be initiated on an <em>instance</em>;</li> <li>painting has to operate on a QPainter instanc...
python|class|pyqt|pyqt5
0
4,845
56,410,741
TypeError: 'bool' object is not callable in Pygame
<p>This is my error:</p> <blockquote> <pre><code>g.run() TypeError: 'bool' object is not callable </code></pre> </blockquote> <p>Here is my code:</p> <pre><code>import pygame import time pygame.init() pygame.display.set_caption('Platformer') class Game: def __init__(self): self.x=7 self.y=400 ...
<p>Instead of calling:</p> <pre><code>g.run() </code></pre> <p>You need to call:</p> <pre><code>g.GameLoop() </code></pre> <p>Since <code>run</code> is just a boolean variable in your class.</p>
python-3.x|pygame
0
4,846
55,381,959
django-cors-header not working as expected when using Postman
<p>I'm trying to use my DRF API in my React Web App with Axios but I'm getting CORS policy blocked.</p> <p>I've checked the headers using POSTMAN and seems like django-cors-header is not actually embedding the <code>Access-Control-Allow-Origin: *</code></p> <p>This is my settings.py from Django:</p> <pre><code>INST...
<p>In settings.py set <code>ALLOWED_HOSTS = []</code> to <code>ALLOWED_HOSTS = [&quot;*&quot;]</code></p>
django|python-3.x|reactjs|django-rest-framework|django-cors-headers
0
4,847
42,356,989
Taking a sum in python over vectors scaling a variable to graph
<p>I am trying to plot a log-likelihood function in python for the Berthe-Blocke equation and I keep getting a nonsensical plot. Currently I am taking doing </p> <pre><code> def Berthe_Blocke(beta, prefac, I): gamma=(1/numpy.sqrt(1- beta)) vsq=beta*9*10**20 return prefac*(numpy.log(2*0.511*numpy.power(gam...
<p>Turns out the variables were being passed as an integer, and needed to be forced to be used as floats using float(l)</p>
python-2.7|numpy
0
4,848
58,372,768
File permissions issue with python/Spyder/Anaconda after upgrading mac to Catalina
<p>After upgrading macOS to Catalina, my Anaconda installation was helpfully reconfigured by Apple. Advice from the Anaconda website suggested a fresh install was the best way to go. Did that and all seemed good. I use spyder from the Anaconda navigator. But trying a previously running python code failed due to app...
<p>I guess you have solved this by now, but for future reference, I still post my answer. </p> <p>TLDR: I opened a file (from the folder causing the problem) <strong>directly in the spyder editor</strong> (File | open). As a consequence, the editor should have triggered the pop-up dialog question whether you want to a...
python|permissions|anaconda|spyder
5
4,849
36,146,469
500 + Website Check in Python for multiple status
<ul> <li><p>I know there are multiple question for url checks. I am very new to python so trying to understand from multiple posts and searching for new library for help as well. I am trying to work for below point for internal as well as external websites. :</p> <pre><code> Status Code Status Description Res...
<p>I think you can the page presence with this code:</p> <pre><code>import httplib from urlparse import urlparse def chkUrl(url): p = urlparse(url) conn = httplib.HTTPConnection(p.netloc) conn.request('HEAD', p.path) resp = conn.getresponse() return resp.status &lt; 400 if __name__ == '__main__':...
python|python-2.7|python-3.x|url|http-headers
1
4,850
33,086,881
Merge two python pandas data frames of different length but keep all rows in output data frame
<p>I have the following problem: I have two pandas data frames of different length containing some rows and columns that have common values and some that are different, like this:</p> <pre><code>df1: df2: Column1 Column2 Column3 ColumnA ColumnB ColumnC 0 a ...
<p>You can read the documentation here: <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html" rel="noreferrer">http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html</a></p> <p>What you are looking for is a left join. The default option is an inner join....
python|pandas|merge|dataframe
56
4,851
33,391,229
How to initialize LpVariable in PuLP
<p>I have declared list <code>facility</code> of <code>LpVariable</code>:</p> <pre><code>for fac in range (len(candidates)): facility.append(LpVariable("Facility_{0}".format(fac),lowBound=0, upBound=1, cat= pulp.LpInteger )) </code></pre> <p>When I do <code>print(value(facility[i]))</code> , it gives me output as...
<p>You can try <code>facility[i].setInitialValue(0.)</code>, as described <a href="https://pythonhosted.org/PuLP/pulp.html" rel="nofollow">here</a>. </p> <p>Note that PuLP will delegate this call to the corresponding method from the API of the solver you are calling. Therefore, it will work only if the solver supports...
python-3.x|linear-programming|pulp
2
4,852
38,224,019
Cartopy-Python syntax - multiple objects/countries in one line
<p>I'm following this example, <a href="https://gis.stackexchange.com/questions/88209/python-mapping-in-matplotlib-cartopy-color-one-country">Python Mapping in Matplotlib Cartopy Color One Country</a>. It's fully working with several countries, e.g. USA, France, UK, Japan.</p> <pre><code>for country in countries: ...
<p>You should use the <code>in</code> keyword, something like this:</p> <pre class="lang-py prettyprint-override"><code>for country in countries: if country.attributes['adm0_a3'] in ['USA', 'FRA', 'GBR', 'JPN']: ax.add_geometries(country.geometry, ccrs.PlateCarree(), facecolor=(0,...
python|cartopy
2
4,853
52,381,301
Testing for non-strict inequality with np.testing
<p><code>np.testing.assert_array_less()</code> tests for strict inequality:</p> <pre><code>In [1]: np.testing.assert_array_less(1., 1.) --------------------------------------------------------------------------- AssertionError Traceback (most recent call last) &lt;ipython-input-1-ea8ee0b762c...
<p>As you note, apparently non-strict inequality is not among the defined test cases in <code>numpy.testing</code>. Also, there is no <em>documented</em> way to extend <code>numpy.testing</code> with more test cases.</p> <p>Looking at the source, it is clear that it is possible to roll your own test cases, using <code...
python|numpy|testing
2
4,854
54,297,429
argument after * must be an iterable, not int
<p>I have a small script that takes in a list and a value that represents what size sublists to break the list into:</p> <pre><code>def chunk(alist, n): i = 0 j = n while j &lt; (len(alist) + 2): sub = alist[i:j] i += n j += n print(sub) chunk([1, 2, 3, 4, 5], 2) </code></p...
<p>Your <code>sub</code> variable holds only a slice of the list. It should instead be appended to a list of lists as the returning value of the <code>chunks</code> function:</p> <pre><code>def chunks(alist, n): i = 0 j = n output = [] while j &lt; (len(alist) + 2): output.append(alist[i:j]) ...
function|python-3.6
2
4,855
54,271,452
How to fix the freezing cv2.imshow(from opencv) in django
<p>What I want to do is when the user click the buttom , django will run the python code and detect people. I use VideoStream from imutils.video but it just popup the window and freeze. It works prefectly when I test for the face recognition but once I put the same code to django. I mean it can still detect people but ...
<p>Try this:</p> <pre><code>while True: frame = vs.read() cv2.imshow("Frame", frame) if cv2.waitKey(1) &amp; 0xFF == ord("q"): break cv2.destroyAllWindows() vs.stop() </code></pre> <p>Honestly I dont really understand what you want to do. You want to wait every 30s before you taking another picture...
python|django|opencv|live-streaming|face-recognition
0
4,856
52,507,723
Allow foreign key fields in Django Admin forms
<p>Right now I have two models: Inventory and Item</p> <p>An Item can have multiple Inventory transactions (you can think of these essentially as batches), but an Inventory transaction can have only one item, so one-to-many relationship, right? Anyway, I'm using a foreign key field like so:</p> <p><strong>models.py</...
<p>use the double underscore to traverse the foreign key tree</p> <pre><code>list_display = ('id', 'item', 'item__description', 'item__brand', 'active', 'description') </code></pre>
python|django|django-models|django-forms|django-views
-1
4,857
47,585,820
I must plot each function for each item in my list, not working
<pre><code>import matplotlib.pyplot as plt import numpy as np fig = plt.figure xvals = np.linspace(0.4, 2, 100) # generate x-values def f1(xvals): return (1. / 3.) * (-1. + xvals**3) def f2(xvals): return (1. / 2.) * (-1. + xvals**2) def f3(xvals): return -1. + xvals def f4(xvals): return 2.303...
<p>You need to create subplots. Now, all your plots are happening on a single set of axes so each one overwrites the last.</p> <pre><code>fig1 = plt.figure(figsize=(7, 10)) #you can set figure sizes too!! #create axes for sub plots ax1 = plt.subplot(221) ax2 = plt.subplot(222) ax3 = plt.subplot(223) ax4 = plt.subplot(...
python|plot|graph
0
4,858
47,776,745
Timeseries yearly boxplot with TimeGrouper : ValueError
<p>I am trying to represent yearly box splot with TimeGrouper</p> <pre><code>from pandas import Series from pandas import DataFrame from pandas import TimeGrouper from matplotlib import pyplot series = Series.from_csv('test4.csv', header=0) groups = series.groupby(TimeGrouper('A')) years = DataFrame() for name, group ...
<p>I just found an issue... When TimeGrouper('A') is used, dataset must have exactly 365 days per year... but with leap years, some years of my dataset have 366 days... You have just to delete one row (one day) per leap year.</p>
python|excel|pandas|csv|time-series
0
4,859
47,851,495
Import Error: DLL load failed The specified procedure could not be found (WinDBG on XP)
<p>I am using a package called pykd(<a href="https://pykd.codeplex.com/" rel="nofollow noreferrer">https://pykd.codeplex.com/</a>) which is an extension for Windbg. I downloaded this on windows and everything works fine. However, when downloading this on a Windows XP everything is normal. It is installs ok, and everyth...
<p>What is pykd version? The last pykd builds don't support XP, sorry. The error means pykd.pyd module cannot be loaded on WinXP. </p> <p>You can try note old pykd version to install:</p> <pre><code>pip install pykd&lt;0.3.1.0 </code></pre>
python|windows|windbg|pykd
1
4,860
34,240,763
Guess the number game ( Client - Server)
<p>Server:</p> <pre><code>import socket import random randnumber = random.randrange(1,20) ip = '127.0.0.1' port = 5000 n = 1 tries = 0 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((ip,port)) s.listen(5) print("...&lt;&lt;") while True : (c,a) = s.accept() print("Sundedemenos me ton...
<p>This is an always true loop because <code>gues</code> is never changing!</p> <pre><code>while (gues): if not gues: break else: value = input() s.send(value.encode()) </code></pre> <p>Also, I think both <code>while</code> loops are in the wrong places:</p> <ul> <li>In the client, the while loop never...
python-3.x
1
4,861
28,107,404
`map.scatter` on basemap not displaying markers
<p>I have a map of Germany, and the coords of a few cities. <code>plot</code> displays the dots properly. I would like to use <code>scatter</code> instead, in order to be able to color the markets with respect to an other variable and then display a <code>colorbar</code>. The code runs in the console, but the dots are ...
<p>try adding "zorder" so that the points show up above the map:</p> <pre><code> map.fillcontinents(color='lightgray',zorder=0) </code></pre>
python|colorbar|scatter|matplotlib-basemap
15
4,862
19,875,985
Python 2.6.6 Ubuntu Server os.environ not unicode
<p>I'm trying to write a simple chat system that accepts various languages and translates them automatically, printing both the original language and a second language (e.g, English) next to it. </p> <p>But, I've encountered no end of problems, and the reason, I think, is because Python reads os.environ as a byte stri...
<p><code>os.environ</code> is <strong>always</strong> bytes only, as are URLs and query strings.</p> <p>You need to decode such information in your own code:</p> <pre><code>print u'{0}: {}'.format(key, value.decode('utf8')) </code></pre> <p>This is fundamental to how streams (network connections, files, pipes, etc.)...
python|apache|unicode|utf-8
0
4,863
58,463,867
Function not returning the correct amount of observations
<p>I am trying to create a function to show the <code>n</code> number of movies most rated by a user in a given dataframe. I have been able to extract the movies the user provided rating for but I cannot return the correct amount of rows - instead it prints all the movies with rating from the user.</p> <p>I have tried...
<p>I'm not sure what exactly, you want to achieve, but check this:</p> <pre><code>import pandas as pd df = pd.DataFrame( { 'user_id': [1, 1, 1, 2, 2, ], 'title': ['t1', 't2', 't3', 't1', 't5'], 'rating': [25, 25, 35, 25, 30,], }) df.sort_values(by='rating', ascending=Fals...
python|pandas
0
4,864
58,192,338
Finding consecutive and identical integer into a vector
<p>I have vectors with 0 and 1.</p> <pre><code>a = np.array([1,1,0,0]) b = np.array([1,0,0,1]) c = np.array([0 1 1 0]) d = np.array([0 1 0 1]) </code></pre> <p>I would like to implement a function checking if the 1 are consecutive in the vector by disregarding the end of the vector, i.e. last element wih first elemen...
<p>You could use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.roll.html" rel="nofollow noreferrer">np.roll</a> + <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.logical_and.html" rel="nofollow noreferrer">np.logical_and</a> + <a href="https://docs.scipy.org/doc/numpy/reference...
python|numpy
1
4,865
65,230,805
How to install Python 3.8 along with Python 3.9 in Arch Linux?
<p>I'm working with tensorflow. Recently Arch replaced Python 3.8 with 3.9 and at the moment there is no tensorflow build for Python 3.9. Downgrading Python version for the whole system for that single reason do not looks like good idea for me. My goal is to create virtual environment with python 3.8. Is there a way to...
<p>Go for package <code>python38</code> in AUR, if you have an AUR helper like yay just use <code>yay -S python38</code>. Otherwise, just download the <a href="https://aur.archlinux.org/packages/python38/" rel="noreferrer">PKGBUILD</a> and install manually with <code>makepkg</code>.</p> <p>You can also update python wi...
python|linux|tensorflow|virtualenv|archlinux
16
4,866
45,407,290
forming a list of dictionary from a list in python
<p>I have a <code>list</code> in <code>python</code> whose sample data looks like this:</p> <pre><code>list_str = ['1. Option 1', '2. Option 2 ', '3. Option 3', '4. Option 4'] </code></pre> <p>Now what I want to do is form a <code>list of dictionary</code> using items from this <code>list</code>. The output <code>lis...
<p>You can try:</p> <pre><code>dictionaries = [] for x, y in enumerate(list_str, 1): dictionaries.append({'text': y, 'value': str(x) }) </code></pre> <p>Or make it a one liner:</p> <pre><code>dictionaries = [{'text': y, 'value': str(x)} for x, y in enumerate(lis...
python|list|dictionary
2
4,867
14,545,128
Issue with socket module?
<p>I can't import socket module into my program. When I import it said, <code>"AttributeError: 'module' object has no attribute "AF_INET'</code>. I think there is a problem with my python virtual machine.</p>
<p>Mostly It is looking like Either naming problem or path problem.You can try to run your program from another location as did by this <a href="http://ubuntuforums.org/showthread.php?t=464541" rel="nofollow noreferrer">Python Socket Problem</a></p> <p>Or if it is a naming problem then maybe you are using some standar...
python|python-2.7
0
4,868
41,664,171
Add images on wxComboBox (wx.python)
<p>I'm making a currency-converter and I want my coin-choice box (Dropdown box) to have mini-flags of each country (images) before the name of the country. </p> <p>Does anybody know how this can be accomplished? </p>
<p>If you are using wxpython Phoenix (that is, version 3 and above), you can use <a href="https://wxpython.org/Phoenix/docs/html/wx.adv.BitmapComboBox.html#wx-adv-bitmapcombobox" rel="nofollow noreferrer">BitmapComboBox</a> from the collection of advanced widgets.</p>
python|wxpython
0
4,869
56,979,461
How to use multi-gpu during inference in pytorch framework
<p>I am trying to make model prediction from unet3D built on pytorch framework. I am using multi-gpus</p> <pre><code>import torch import os import torch.nn as nn os.environ['CUDA_DEVICE_ORDER']='PCI_BUS_ID' os.environ['CUDA_VISIBLE_DEVICES']='0,1,2' model = unet3d() model = nn.DataParallel(model) model = model.to('cu...
<p>DataParallel handles sending the data to gpu.</p> <pre><code>import torch import os import torch.nn as nn os.environ['CUDA_DEVICE_ORDER']='PCI_BUS_ID' os.environ['CUDA_VISIBLE_DEVICES']='0,1,2' model = unet3d() model = nn.DataParallel(model.cuda()) result = model.forward(torch.tensor(input).float()) </code></pre>...
pytorch|multi-gpu
3
4,870
57,103,701
Python Selenium Printing Save-As-PDF Waiting for Filename Input
<p>I'm trying to save a website as PDF through printing dialog. My code allows me to save as pdf, but asks me to input a filename, which I don't know how to pass a filename to the pop up box. Attached is my code:</p> <pre><code>import time from selenium import webdriver import os class printing_browser(object): d...
<p>These days I had the same question. I solved it without using the pyautogui in these case, because I use different PCs and monitors and I didn't want to depend on the position of the click.</p> <p>I was able to solve it using the about:config... changing them with each necessary print (in PDF).</p> <p>The name of my...
python|selenium|pdf|printing|selenium-chromedriver
4
4,871
44,709,372
Accessing Neo4j Node property using cypher in python
<p>I'm trying to get the node property in python, which I earlier created with name property as Marco</p> <pre><code>student = db.labels.create("Student") u1 = db.nodes.create(name="Marco") student.add(u1) </code></pre> <p>When I queried on neo4j UI using query </p> <pre><code>MATCH (n:Student) where n.name="gaurav...
<p>As explained in <a href="https://marcobonzanini.com/2015/04/06/getting-started-with-neo4j-and-python/" rel="nofollow noreferrer">https://marcobonzanini.com/2015/04/06/getting-started-with-neo4j-and-python/</a> you can do this :</p> <pre><code>results = db.query("MATCH (a:Student) WHERE a.name = {} RETURN a ", {"na...
python|neo4j|cypher
0
4,872
23,602,412
Only download a part of the document using python requests
<p>I'm writing a web scraper using python-requests.</p> <p>Each page is over 1MB, but the actual data I need to extract is very early on in the document's flow, so I'm wasting time downloading a lot of unnecessary data.</p> <p>If possible I would like to stop the download as soon as the required data appears in the d...
<p>What you want to use here is called <code>Range</code> HTTP Header.</p> <p>See: <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html" rel="noreferrer">http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html</a> (<em>Specifically the bit on Range</em>).</p> <p>See also API Docs on <a href="http://docs.pyt...
python|http|python-requests
29
4,873
23,799,533
Mapping list of dict objects to a new list of dict objects
<p>I have a list of dict objects, like:</p> <pre><code>&gt;&gt;&gt; j = [{ "field": "dev_name", "value": ['dev_1', 'dev_2', 'dev_3']}, { "field": "dev_type", "value": ['p2p', 'Radwin', 'Talsima']}] </code></pre> <p>I want to create a new list of dict items, from above, like this:</p> <pre><code>&gt;&gt;&gt; k = [{ "...
<p>You can't really do key lookup on a list of dicts. Instead, I propose just making one big dict. Then you can do <code>k['dev_name']</code> and get the list of device names instead of having to awkwardly iterate through a list of dicts looking for the one with the key you want:</p> <pre><code>k = {d['field']: d['val...
python|list|python-2.7|dictionary
3
4,874
23,788,038
python compare "\n" escape chars with "\\n"
<p>Ok,</p> <p>I have two strings, <code>"Hello\nWorld!"</code> and <code>Hello\\nWorld!</code>. I have to compare those that way that <code>\n</code> and <code>\\n</code> equals.</p> <p>Thats not hard. I just <code>string1.replace("\n", "\\n")</code>.</p> <p>But what if I have to do it right for all escape chars inc...
<p>How about using <a href="https://docs.python.org/2/library/codecs.html#python-specific-encodings" rel="noreferrer"><code>unicode_escape</code></a> encoding?</p> <pre><code>&gt;&gt;&gt; 'hello\r\n'.encode('unicode_escape') == 'hello\\r\\n' True &gt;&gt;&gt; 'hello\r\n' == 'hello\\r\\n'.decode('unicode_escape') True ...
python|string|replace|escaping|backslash
10
4,875
24,111,980
How to change the colour of menu in Tkinter under windows?
<p>I'm using <strong>windows xp</strong>. I want to change menubar and labels foreground and background in TKinter. But, I'm unable to change. Can I change it in windows xp or I have to upgrade it to windows 7. </p> <pre><code>from Tkinter import * root = Tk() menubar = Menu(root) menubar.add_command(label = 'Label1'...
<p>There is nothing you can do. Tkinter uses a native menu object for the menus, which means they will have exactly the same look and feel of other windows menus. </p>
python|tkinter|menubar
2
4,876
24,195,815
Averaging time series of different lengths
<p>I have a number of lists (time series)</p> <pre><code>dictionary = {'a': [1,2,3,4,5], 'b': [5,2,3,4,1], 'c': [1,3,5,4,6]} </code></pre> <p>that I would like to average on another:</p> <pre><code>merged = {'m': [2.33,2.33,3.66,4.0,4.0]} </code></pre> <p>Is there a smart way to find this?</p> <p>What if the lists...
<p>Given that you tagged this with numpy and scipy, I'm assuming it's OK to use scientific python functions. A terse way to accomplish the first task is then</p> <pre><code>$ ipython --pylab &gt;&gt;&gt; dictionary = {'a': [1,2,3,4,5], 'b': [5,2,3,4,1], 'c': [1,3,5,4,6]} &gt;&gt;&gt; map(mean, np.array(dictionary.valu...
python|numpy|scipy
2
4,877
29,711,534
How to get num results in mysqldb
<p>I have the following query:</p> <pre><code>self.cursor.execute("SELECT platform_id_episode, title, from table WHERE asset_type='movie'") </code></pre> <p>Is there a way to get the number of results returned directly? Currently I am doing the inefficient:</p> <pre><code>r = self.cursor.fetchall() num_results = len...
<p>If you don't actually need the results,<sup>*</sup> don't ask MySQL for them; just use <a href="https://dev.mysql.com/doc/refman/5.7/en/counting-rows.html" rel="nofollow"><code>COUNT</code></a>:<sup>**</sup></p> <pre><code>self.cursor.execute("SELECT COUNT(*) FROM table WHERE asset_type='movie'") </code></pre> <p>...
python|mysql
3
4,878
29,452,443
python list from truncated data
<p>I have a text file which contains data of the form:</p> <pre><code>decimal=12668098908\ 75899080808908098 decimal=2987979878\ 757675765786686 ... etc </code></pre> <p>I want to make a vector A[i] where for each <em>i</em>, I shall get the <em>i</em>-th integer (without the \) from the previous data. </p> <p>...
<p>Assuming the dataset is sufficiently large that we can't just slice the string up in memory, perhaps the best way to do this would be to create a generator.</p> <pre><code>def nums(file_handle): # read the first line in as our initial string linestr = file_handle.readline()[8:].strip('\\\n') # loop ove...
python
1
4,879
49,523,145
Managing file open and close responsibilities with different objects
<p>In a main method, <code>my_object</code> needs access to several members of <code>passed_object</code>, including a file that is opened (<code>passed_file = passed_object.create_file()</code>. An example of this: </p> <pre><code>import os def main(): print('Start of program...') passed_object = PassedObj...
<p>Assuming the simplest situation (because details are missing):</p> <ul> <li><code>PassedObject.create_file</code> just opens a file, returns it and does not keep a reference to it</li> <li>Usage of the file is limited to the scope of <code>MyObject.use_passed_object</code></li> </ul> <p>The solution is simple: clo...
python|file|contextmanager
1
4,880
21,137,218
Append every 5 Seconds
<p>I want to append the letter X to a list every 5 Seconds. My code so far:</p> <pre><code>import threading def Seconds(): threading.Timer(5.0, Seconds).start() List = [] n = "X" List.append(n) print List Seconds() </code></pre> <p>I want to have ONE list which grows every 5 Seconds and...
<p>Is your embedded/battery powered system using Unix? This could be easier achieved with a bash script:</p> <pre><code>#!/bin/bash while true do cat /proc/uptime &gt; log.txt sleep 5 done </code></pre> <p>You then get the exact uptime. Note though in measuring this data you could be inadvertently using more...
python|list|timer|append
0
4,881
53,750,209
Detecting lines (vertical and horizontal) that are not straight and align image by it?
<p><strong>Hey,</strong></p> <p><strong>Is it possible to automatic align an image based on lines in the images that are not straight using Python? for example, if I have this image:</strong></p> <p><a href="https://i.stack.imgur.com/46LnP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/46LnP.png" ...
<p>You're on the right track with the Hough transform. Yes, there are a <em>lot</em> of lines. You failed to describe what differentiates the lines you want from the ones you don't (among various unspecified details), but let me try to extract a few ideas for you:</p> <ul> <li>slope "near" vertical or horizontal.</li...
python|opencv|alignment|surf|hough-transform
2
4,882
46,015,618
goldbach's conjecture algorithm shows "list index out of range" above a specific number
<p>I am creating a program where the user can enter an even number between 4 and 5000 and the program will output a list of pairs of prime numbers that sum up the number provided in the input.</p> <p>My program works fine to put all the prime numbers in a list and checks that the input is an even integer between 4 and...
<p>You are looping (in <code>goldbergs_conjecture()</code>) over <code>range(q)</code>, which can be anywhere from 4..5000.</p> <p>But you are looking for this value: <code>x=prime_numbers[i]</code> which is an index into the <code>prime_numbers</code> list. </p> <p>The <code>prime_numbers</code> list is not guarante...
python|list|goldbach-conjecture
2
4,883
45,987,272
Python function not being executed
<p>Hey I'm trying to create an evaluate function for this tic-tac-toe thing that I'm doing. Basically what it does is check whether a game board (testBoard is the sample game board I created) contains any win conditions.</p> <p>However, when I execute this code, nothing shows up in the terminal. Any advice would be ap...
<p>The <code>return</code> statement returns the value to the interpreter (or a variable if you're assigning the output of the function to a variable); it doesn't do anything with it unless you specify it.</p> <p>You can modify your function where it says <code>return</code> to say <code>print(10)</code> or whatever v...
python
1
4,884
73,825,545
Basic runtime script error on python with selenium
<p>I would like to point out that I am a beginner and that I started barely 48 hours ago.</p> <p>I want to code a script that runs a page, enters username and password, click in the login button and clicks in a tab once logged in.</p> <p>But I encounter an error, it only opens the page for me and does not enter any id/...
<p>From the Selenium docs <a href="https://www.selenium.dev/documentation/webdriver/elements/finders/" rel="nofollow noreferrer">Finding Web Elements</a> <br> So in your code,<br> import By <code>from selenium.webdriver.common.by import By</code> <br> and use <code>wb.find_element(By.XPATH,&quot;your_xpath&quot;)</code...
python|selenium
0
4,885
21,593,425
Python indexing a list
<p>I have a list as below: How do I do index in python. I want to fetch a value for "OS"? Please let me know.</p> <pre><code>[{'UserName': 'd699a1f25d9a3', 'BrowserVersion': None, 'PasswordMinLength': 0, 'SystemAutoLock': 0, 'OS': 'Windows 7 6.1 Build 7601 : Service Pack 1 64bit'}] </code></pre>
<pre><code> mylist = [{'UserName': 'd699a1f25d9a3', 'BrowserVersion': None, 'PasswordMinLength': 0, 'SystemAutoLock': 0, 'OS': 'Windows 7 6.1 Build 7601 : Service Pack 1 64bit'}] OS = mylist[0]['OS'] print OS </code></pre>
list|python-2.7|indexing
1
4,886
21,439,510
Getting Type Error with Python
<p>I'm sort of new to Python and I was wondering how to fix this. I'm trying to make a currency converter for a school project for my computing class, however I'm getting an error.</p> <p>Here's the code:</p> <pre><code>## Currency conversion calculator Mk.2 ## # USD, JPY, EUR GBP = ["1.66","169.14","1.21"] # GBP, J...
<p>Change the line</p> <pre><code>output = user_input[3] * USD[0] </code></pre> <p>to</p> <pre><code>output = float(user_input[0]) * float(USD[0]) </code></pre> <p><strong>Note</strong></p> <p>As the Error suggests, you are trying to multiply a sequence (here a string ) with a string <code>can't multiply sequence ...
python
2
4,887
24,496,662
Random division of list to two complementary sublists
<p>I have a list which I want to randomly divide into two sublists of known size, which are complements of one another. e.g., I have <code>[1,5,6,8,9]</code> and I want to divide it to <code>[1,5,9]</code> and <code>[6,8]</code>. I care less about efficiency and just want it to work. Order does not matter.</p> <p>I st...
<p>How about something like this?</p> <p>Generate a list of indices and shuffle them:</p> <pre><code>&gt;&gt;&gt; indices = range(len(pop)) &gt;&gt;&gt; random.shuffle(indices) </code></pre> <p>Then slice the indices list and use <code>operator.itemegetter</code> to get the items:</p> <pre><code>&gt;&gt;&gt; from o...
python|list|python-2.7|random
4
4,888
40,856,429
Can Greek letters be added to Sphinx documents as glossary terms?
<p>I want to add variables that are defined as Greek letters to my glossary in a sphinx document. For example:</p> <pre><code>.. glossary:: :math:`{\alpha}` Definition for alpha </code></pre> <p>The goal is to have these variables appear in the document's index. Anyone have experience with this?</p>
<p>Glossary terms are automatically added to the index. But that does not work for the glossary entry in the question. Sphinx emits this warning: <code>WARNING: invalid single index entry ''</code> (at least it does for me). This feels like a bug.</p> <p>Here are two workarounds:</p> <ol> <li><p>Use a substitution</p...
python-sphinx|restructuredtext|glossary
2
4,889
38,222,407
Python Gtk 3 window is not defined, class instancing confusion
<p>I am just starting to get into python and I am utterly confused as to how object creation works. I am trying to create user interface with GTK. Here is an example of the problem I am having:</p> <pre><code>from gi.repository import Gtk def button_clicked(self, button): self.button_label = button.get_label() ...
<p>It is because you are starting the main loop (<code>Gtk.main()</code>) inside of <code>LoginWindow.__init__()</code>. That means that the <code>window = LoginWindow()</code> line doesn't finish executing until after the login window is closed. You should take <code>Gtk.main()</code> outside of the <code>__init__</...
python|gtk3
2
4,890
38,122,503
Tkinter - What is the time item, stored in the event object
<p>In Tkinter there is an object called event, usually passed to functions, which are called by buttons (or similar objects) in Tkinter.</p> <pre><code>tkinter.Event </code></pre> <p>This event.object has a bunch of items, like x-position or y-position, and also a time-stamp of sorts.</p> <p>What does this time-stam...
<p>The documentation of the <code>Event</code> class in tkinter source code only says this:</p> <blockquote> <p>time - when the event occurred</p> </blockquote> <p>I assume this comes from the <code>%t</code> substitution provided by the underlying tcl/tk interpreter, which is documented to be the following:</p> <...
python|tkinter
1
4,891
31,093,624
Union of values of two dictionaries merged by key
<p><br> I have two dictionaries:</p> <pre><code>d1 = {'a':('x','y'),'b':('k','l')} d2 = {'a':('m','n'),'c':('p','r')} </code></pre> <p>How do I merge these two dictionaries to get such result:</p> <pre><code>d3 = {'a':('x','y','m','n'),'b':('k','l'),'c':('p','r')} </code></pre> <p>This works when values of the dict...
<p>Your question is a little bit mangled with respect to variable names, but I think this does what you want:</p> <pre><code>d3 = dict([(i,d1.get(i,())+d2.get(i,())) for i in set(d1.keys()+d2.keys())]) d3 {'a': ('x', 'y', 'm', 'n'), 'b': ('k', 'l'), 'c': ('p', 'r')} </code></pre> <p>Note that you can add (ie extend) ...
python|python-2.7|dictionary
3
4,892
40,201,929
Python AttributeError: 'str' object has no attribute 'pop' Learnpythonthehardway
<p>I have this on-going problem with this error which I tried to solve as the tutorial has told me fix this code. Most of the code is spelling and math errors, however I cannot solve this AttributeError.</p> <p>Tutorial site: <a href="https://learnpythonthehardway.org/book/exercise26.txt" rel="nofollow">https://learnp...
<p>Use this:</p> <pre><code>print_first_word(words) </code></pre> <p>instead of this:</p> <pre><code>print_first_word(sentence) </code></pre>
python|string|list|attributes|attributeerror
0
4,893
40,000,663
Get celery beat trigger time on task
<p>I'm trying to find a way to get time time condition that triggered celery beat to fire a task. </p> <p>Getting <code>datetime.now()</code> often deviates from the time at which the task was queued by celery beat due to all celery workers being busy. For example: I set the task to be executed at 12:30 everyday but d...
<p>I faced the same kind of problem where I wanted to use task trigger time instead of execution time in periodic celery task. I couldn't find the exact field in the celery task which has task trigger time. As a way around I have used expires time of task.</p> <pre><code>task_expires_day =30 @app.on_after_configure.co...
python|django|celery|django-celery|celerybeat
0
4,894
29,229,735
django translation doesn't work but translation in templates works
<p>I try to translate my django site to another languages but translation in python doesn't work. But translation in templates using trans tag, works as expected.</p> <p>I have tried <code>ugettext</code>, <code>gettext</code>, <code>gettext_lazy</code> and <code>ugettext_lazy</code>, and every time I got original unt...
<p>The ugettext_lazy will not work if string contains non Latin symbols. So in my case the original strings must be the Unicode objects.</p>
python|django|internationalization|translation|gettext
0
4,895
52,031,482
If I have duplicates in a list with brackets, what should I do
<p>Suppose I have the following list:</p> <pre><code> m=[1,2,[1],1,2,[1]] </code></pre> <p>I wish to take away all duplicates. If it were not for the brackets inside the the list, then I could use:</p> <pre><code> m=list(set(m)) </code></pre> <p>but when I do this, I get the error:</p> <p>unhashable type 'set'.</p...
<pre> result = [] for i in m: flag = True for j in m: if i == j: flag = False if flag: result.append(i) </pre> <p>Result will be: <code>[1,2,[1]]</code></p> <p>There are ways to make this code shorter, but I'm writing it more verbosely for readability. Also, note that this method is O(n^2), so I w...
python-3.x|list|set|brackets
1
4,896
52,322,221
Using python 3 and Selenium to scrape a dynamicaly generated table
<p>I'm new to Python, and trying to scrape a dynamically generated table. I've got far enough to open the page, input a search, and have the results table show off. I'm having trouble scraping the results, and I noticed the specific text of the results isn't part of the HTML. Here's my code so far, thanks for any an...
<p>This will work perfectly:</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions from selenium.webdriver.support.ui import WebDriverWait firstName = input('Insert your first name: ') lastName = input('Insert your last nam...
python|selenium|web-scraping
0
4,897
52,088,973
trying to return value from dict.items() is not working
<p>There is a problem is have to solve here it is </p> <p>You are given a string of numbers between 0-9. Find the average of these numbers and return it as a floored whole number (ie: no decimal places) written out as a string. Eg:</p> <p>"zero nine five two" -> "four"</p> <p>here is my code </p> <pre><code>from ma...
<p>The result should be "four". But your average formula is wrong: you have to sum then <em>divide</em> not subtract.</p> <p>So when you're looping (what a strange idea?) in the dictionary, you don't find the value, so you reach the end of the function and python returns <code>None</code> in that case.</p> <p>So fix ...
python-3.x|list|dictionary|return
1
4,898
69,123,411
substract two ECDF time series
<p>Hi I have a ECDF plot by seaborn which is the following.</p> <p>I can obtain this by doing <code>sns.ecdfplot(data=df2, x='time', hue='seg_oper', stat='count')</code>.</p> <p><a href="https://i.stack.imgur.com/sBRfY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sBRfY.png" alt="enter image descri...
<p>So the first thing is to obtain what <code>seaborn</code> does, but manually. After that (because I need to) I can subtract one series from the other.</p> <h4>Cumulative Count</h4> <p>First we need to obtain a cumulative count per each series.</p> <pre><code>In [304]: df2['cum'] = df2.groupby(['seg_oper']).cumcount(...
python-3.x|pandas|time-series|seaborn|cumulative-sum
0
4,899
62,286,683
how to add random values to the column of a csv file?
<p>I want to append a column in a prefilled csv file with 3 million rows using python. Then, i want to fill the column with random values in the range of (1, 50). something like this:</p> <p>input csv file,</p> <p>awareness trip amount</p> <p>25 1 30</p> <p>30 2 35</p> <p>output csv f...
<p>Check out this answer: <a href="https://stackoverflow.com/questions/20273889/python-add-string-to-each-line-in-a-file">Python Add string to each line in a file</a></p> <p>I've found it much easier to use <code>with</code> for files instead of importing csv or other special filetype libraries unless my use case is v...
python|csv
0