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
6,300
44,015,002
Training a classifier on mismatched length dataset SciKit Learn
<p>I am working with a dataset similar to the following: </p> <p>X_values (a list of x,y,z coordinates): </p> <pre><code>[ [(32.0, 22.0, -2.0), (32.0, 22.0, -2.0), (28.0, 50.0, 6.0), (28.0, 14.0, 56.0), (-26.0, 56.0, 6.0), (-18.0, 50.0, 4.0), (14.0, -36.0, 50.0), (-16.0, -70.0, -6.0), (-14.0, -6.0, 4.0), (18.0, -...
<p>I consider the best way to model your problem is separating the coordinate and treat them as multiple features. Let me use Linear Regression to explain how can it help.</p> <p>Suppose that your features are <code>X</code>, <code>Y</code>, <code>Z</code> then you would have for the first training example (32.0, 22.0...
python|machine-learning|scikit-learn
0
6,301
44,300,997
Python I want to print one thing if 2 things are true. and another if either is false
<p>Just messing around trying to learn things.<br> Made this dumb program. Just want tp and socks to both be true for you to be able to get the if thing. Or idk.</p> <pre><code>def shit_supplies(tp, socks, time): print "Time: %d minutes" % time print "Soks on? %r" % socks print "Butt-Wipies? %r" % tp if ...
<p>There is just a few small mistakes within your attempt.</p> <pre><code> def poop_supplies(tp, socks, time): print("Time: %d minutes" % time) print("Soks on? %r" % socks) print("Bottom-Wipies? %r" % tp) if tp and socks: print("Hurry up only %d minutes to pinch it off!!!" %...
python
3
6,302
14,317,243
Boto - Uploading file to a specific location on Amazon S3
<p>This is the code I'm working from</p> <pre><code>import sys import boto import boto.s3 # AWS ACCESS DETAILS AWS_ACCESS_KEY_ID = '' AWS_SECRET_ACCESS_KEY = '' bucket_name = AWS_ACCESS_KEY_ID.lower() + '-mah-bucket' conn = boto.connect_s3(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) bucket = conn.create_bucket(bucket_...
<p>All you should have to do is prepend the virtual directory path to the key name prior to uploading. For example:</p> <pre><code>key_name = 'my test file' path = 'images/holiday' full_key_name = os.path.join(path, key_name) k = bucket.new_key(full_key_name) k.set_contents_from_filename(...) </code></pre> <p>You ma...
python|amazon-web-services|amazon-s3|boto
54
6,303
34,728,595
Get the n-th double number from a given double in python
<p>This question is similar to <a href="https://stackoverflow.com/questions/34713612/how-to-compute-the-n-th-floating-point-from-0-in-python">another question</a> but I do not see how to extend the answer to that question in an easy way. </p> <p>Here, I want to calculate the n-th <code>double</code> from a given <co...
<p>The <a href="https://stackoverflow.com/questions/34713612/how-to-compute-the-n-th-floating-point-from-0-in-python">answer of the question you pointed to</a> is exactly the answer to your question. The answer solved the problem for for 64 bits float that are the python equivalent of C double.</p> <hr> <p>Well, if y...
python|floating-point
1
6,304
351,821
destroying a Toplevel tk window in python
<p>I was trying to write code that would auto-close a Toplevel Tk window in Python.</p> <p>I ended up getting it to work, but ran into a little problem along the way that I wasn't able to figure out.</p> <p>The second two buttons work, but the first one doesn't and I don't understand why...</p> <p>Any ideas?</p> <p...
<p>Because it returns a function and not its result.</p> <p>You should put:</p> <pre><code>command=TL.destroy </code></pre> <p>or if you used lambda:</p> <pre><code>command=lambda: TL.destroy() </code></pre>
python|tkinter
8
6,305
392,349
Modify bound variables of a closure in Python
<p>Is there any way to modify the bound value of one of the variables inside a closure? Look at the example to understand it better.</p> <pre><code>def foo(): var_a = 2 var_b = 3 def _closure(x): return var_a + var_b + x return _closure localClosure = foo() # Local closure is now "return 2...
<p>It is quite possible in python 3 thanks to the magic of <a href="http://jeremyhylton.blogspot.com/2007/02/nonlocal-implemented.html" rel="noreferrer">nonlocal</a>.</p> <pre><code>def foo(): var_a = 2 var_b = 3 def _closure(x, magic = None): nonlocal var_a if ...
python|functional-programming|closures
50
6,306
41,876,550
pyQt5 create pushbutton from dict connect to a function with add value
<p>i have a problem to connect my pushbutton. I tried different way but i don't arrive to. Sometimes my GUI doesn't show up, stocked in the buffer. sometimes i have as output Qt.ConnectionType expected, not 'method' or argument 1 has unexpected type 'NoneType'</p> <p>This script is to download files from the web. In d...
<p>When you connect a signal to its slot you should not pass it the function evaluated but only the name of the function. I also recommend that the connection be within the class environment that inherits from QWidget, QMainWindow, etc.</p> <p>This example I can not reproduce completely, but if I can generalize it, so...
python|python-3.x|pyqt|pyqt5
1
6,307
47,163,143
How to make a Format Check for registration plates
<pre><code>def FormatCheck(choice): while True: valid = True userInput = input(choice).upper() firstPart = userInput[:2] secondPart = userInput[2:4] thirdPart = userInput[4:] firstBool = False secondBool = False thirdBool = False if firstPart.i...
<p>What you are looking for is regular expressions. Python has built-in module for expressions. Here is the documentation - <a href="https://docs.python.org/2/library/re.html#module-re" rel="nofollow noreferrer">Regular expression operations</a>. To use this module and regular expressions you should at first try to und...
python|validation|format
2
6,308
11,538,483
Is it possible to introspect actual attributes/methods of an object which overrides `__dir__` and `__getattribute__`?
<p>Some answers from <a href="https://stackoverflow.com/questions/11536961/python-object-atributes-and-methods/11537394#comment15254706_11537394">this question</a> bring very silly ways to cripple the ability to access methods and attributes for instances of objects overriding <code>__dir__</code> and <code>__getattrib...
<p>For instances of a new-style class you could do something like this:</p> <pre><code>object.__getattribute__(instance, '__dict__') </code></pre> <p>I got the idea while reading a section titled <a href="http://docs.python.org/reference/datamodel.html#more-attribute-access-for-new-style-classes" rel="nofollow"><em>M...
python|introspection
1
6,309
11,801,658
traversing daily dump directories
<p>I have 6 months of data to go through, looking like this</p> <pre><code>0101 0102 . . 0131 0201 0202 . . all the way to 0630 </code></pre> <p>I want to fo through each directory, and execute an awk file on the contents, or do it in a weekly manner (each 7 directories will make one week of data</p> <p>is there an...
<p>You can use <code>find</code> to walk your tree and <code>xargs</code> to apply your awk script:</p> <pre><code>find . -type f | xargs awk -f awkfile </code></pre> <p>EDIT: awk syntax corrected thanks to input from @nya. I Am Not An AWK Expert.</p>
python|awk|directory
1
6,310
46,919,360
How to use Pandas to find the strongest month of sale for a product
<p>I am new to python pandas, and I am trying to find the strongest month within a given series of timestamped sales data. The question to answer for n products is: when is the demand for the given product the highest?</p> <p>I am not looking for a complete solution but rather some ideas, how to approach this problem....
<p>I don't have 50 reputation to add comment hence adding answer section. Some insight about your required solution would be great, because to me it's not clear about your requirement. BTW Coming to the idea, if your can split and load the time series data as the timestamp and demand then you can easily do it using reg...
python|pandas
0
6,311
37,634,492
python3 how do i convert my string into a list then count the number of occurrences of a character I'm searching for?
<p>I have this so far:</p> <pre><code>def char_count(string, search): newList = list(string) return newList.count(search) </code></pre> <p>When I run it, I get:</p> <blockquote> <p>TypeError: list() takes 0 positional arguments but 1 was given</p> </blockquote> <p>This is bizarre to me because I thought t...
<p>The <code>list</code> constructor can indeed take one positional argument (an iterable like a string). I guess, you shadowed the name <code>'list'</code> somewhere in your code. You should avoid naming your variables like built-ins (<code>int</code>, <code>list</code>, etc.) or commonly used modules (e.g. <code>stri...
python|string|list|count
3
6,312
67,961,706
How to improve pandas indexing and setting value speed
<p>I need to combine two large dataframes, which now takes hours. I wonder whether there is a faster way to do this. Below is the example: df1 contains some info about shirts, and df2 contains info about pants. I want to merge them into a new dataframe that shows all valid combinations. What is considered valid is that...
<p>Avoid loop with <code>pandas</code>.</p> <p>Input data:</p> <pre><code>&gt;&gt;&gt; df_shirts Color Size Gender Price 0 black S M 11 1 black S F 12 2 black L M 13 3 black L F 14 4 white S M 15 5 white S F 16 6 white L M 17...
pandas
4
6,313
30,134,023
Why selenium webdriver recognizes the <ins> instead of the input box itself?
<p>I'm using Selenium Webdriver with Python. On the a webpage, I have an input checkbox :</p> <pre><code>&lt;input class=“theme1" type="checkbox" value="1" name=“sale_enabled"&gt; &lt;ins class=“theme-helper" style="position: absolute; top: 0%; left: 0%; display: block; border: 0px none; opacity: 0;"/&gt; </code></pre...
<p>Your selenium selectors look correct (though the class <code>theme1-helper</code> doesn't exist in your html).</p> <p>Looks like your problem might be your HTML using a strange character, causing it to parse incorrectly.</p> <pre><code>&lt;input class=“theme1" type="checkbox" value="1" name=“sale_enabled"&gt; ...
python|selenium|webdriver
2
6,314
57,168,830
Python calculate co-occurrence of tuples in list of lists of tuples
<p>I have a big list of lists of tuples like </p> <pre class="lang-py prettyprint-override"><code>actions = [ [('d', 'r'), ... ('c', 'e'),('', 'e')], [('r', 'e'), ... ('c', 'e'),('d', 'r')], ... , [('a', 'b'), ... ('c', 'e'),('c', 'h')] ] </cod...
<p>I think there is no hope for a faster algorithm: you have to compute the combinations to count them. However, if there is threshold of co-occurrences under which you are not interested, you can rty to reduce the complexity of the algorithm. In both cases, there is a hope for less space complexity.</p> <p>Let's take...
python|list|dictionary|tuples|find-occurrences
1
6,315
27,885,946
sniffing network packets using python
<pre><code>#!/usr/bin/env python import struct import sys,os import socket import binascii rawSocket=socket.socket(socket.PF_PACKET,socket.SOCK_RAW,socket.htons(0x0800)) #ifconfig eth0 promisc up receivedPacket=rawSocket.recv(2048) #Ethernet Header... ethernetHeader=receivedPacket[0:14] ethrheader=struct.unpack("!6s6...
<p>Take a look at the output here:</p> <pre><code>x = struct.pack('!2s2s16s', '12', '34', '5678901234567890') tcpHdr=struct.unpack("!2s2s16s", x) print tcpHdr print tcpHdr[0] --output:-- ('12', '34', '5678901234567890') 12 </code></pre> <p>Now read this:</p> <blockquote> <p>socket.<strong>inet_ntoa(packed_ip)</st...
python|sockets
1
6,316
65,633,932
Find cases of List["str"] but not List[str] = ["a"]
<p>I'm trying to check for outdated type hints syntax in a Python codebase.</p> <p>I would like to catch cases such as</p> <pre><code>List[&quot;str&quot;] </code></pre> <p>which could just be</p> <pre><code>List[str] </code></pre> <p>I've written the following regular expression:</p> <pre><code>List\[.*\&quot;.+\&quot...
<p>Just change the dots to a character class excluding only <code>]</code>:</p> <p><code>List\[[^\]]*\&quot;.+?\&quot;[^\]]*\]</code></p>
python|regex
2
6,317
43,129,587
Parse Json data
<pre><code>a= [{ "data" : { "check": true, }, "AMI": { "status": 1, "firewall":{ "status": enable }, "d_suffix": "x.y.com", "id": 4 }, "tags": [ #Sometime tags could be like "tags": ["default","auto"] "default" ], "host...
<p>Use <code>in</code> to test if something is in a list. You also need to put <code>default</code> in quotes to make it a string.</p> <pre><code>for i in a: if 'default' in i['tags']: output = i['hostname'] break </code></pre> <p>If you only need to find one match, you should break out of the loo...
python|json|python-2.7|parsing
1
6,318
36,863,072
Plotting unique dates using matplotlib
<p>I have data like <code>date = '2015-12-12'</code> and corresponding <code>y = [0 - 100]</code> and <code>date = '2015-03-12'</code> and <code>y = [0 - 431]</code>. How can I plot a bar graph for each unique date against the y column and label the x column with each date value. I also need to slice through the <code>...
<p>You don't need to define y values as ranges, a single number for each date (signifying the height) will do. So you'll have your x array, which is date strings, and y array, which is heights.</p> <pre><code>import matplotlib.pyplot as plt import matplotlib.dates as mdates x = ['2015-12-12', '2015-12-13', '2015-12-1...
python|matplotlib
0
6,319
66,979,995
Move first 5 files out of 100 from one directory to another using Python code
<p>Is it possible to move the first 5 files from one directory to another using python code? I have to run the code on the data bricks notebook.</p> <p>The scenario is: I have to pick any first 5 files present in the directory (total files is 100) and move those 5 files to another directory, this process will be repeat...
<p><em>r''</em> - rawstring literal (to ignore backslashes in the string)</p> <pre><code>import os import shutil source = r'C:\Python38-32' # files location destination = r'C:\New Folder' # where to move to folder = os.listdir(source) # returns a list with all the files in sour...
python|azure-databricks
2
6,320
69,537,816
How to delete rows based on two fields?
<p>I have a df with lots of ids and dates, I need to delete from this df rows with id = 4 where date != '2021-01-01' This expression, I assume won't work</p> <pre><code>df_2 = df_2[df_2['id'] != 4 &amp; df_2['date'] != '2021-01-01'] </code></pre> <p>How else can I write the condition?</p> <p>E.g.</p> <pre><code>4 2020-...
<p>Add parantheses and chain mask by <code>|</code> for bitwise <code>OR</code> and swap <code>==</code> with <code>!=</code>:</p> <pre><code>df_2 = df_2[(df_2['id'] != 4) | (df_2['date'] == '2021-01-01')] print (df_2) id date 1 5 2021-05-01 2 4 2021-01-01 </code></pre> <p>Your solution should be change...
pandas
0
6,321
48,282,371
Getting tensorboard to work with keras
<p>I have an issue that seems to have no straight forward solution in Keras. My server runs on ubuntu 14.04, keras with backend tensorflow.</p> <p>Here's the issue:</p> <p>I wanted to use tensorboard to plot the histograms, other training metrics graphs. I followed the following procedure to do so.</p> <ol> <li><p>I...
<p>The following line in terminal did the trick!! Currently situated in /home/tharun/Desktop/ directory</p> <pre><code>tensorboard --logdir=./ /home/tharun/anaconda2/lib/python2.7/site-packages/h5py/__init__.py:34: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is depreca...
tensorflow|deep-learning|keras|tensorboard|keras-2
1
6,322
51,411,327
How To read/iterate through a Datastream in Python
<p>I have a stream created at port 9999 of my computer. <a href="https://i.stack.imgur.com/OS4Xk.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OS4Xk.jpg" alt="enter image description here"></a></p> <p>I have to implement DGIM Algorithm on it. However I am not able to read the bits in the Data...
<p>I used the following code:</p> <pre><code> streams.foreachRDD(lambda c: function(c)) function(c): c.collect() </code></pre> <p>This makes an rdd out of each stream and the function collects all the streams</p>
python-2.7|spark-streaming|data-stream
0
6,323
51,457,393
How can I select only certain values in an array?
<p>I have an array and I want to apply this transformation to only the 1st and 3rd of the value positions. </p> <p>so values such as </p> <pre><code>( -0.23685953, -0.23685953,0.12831355 | 0.94160742, 0.67673782, 0.27031023) X = np.array([[-0.23685953, 0.04296864, 0.94160742], [-0.23685953, 1....
<p>I'm assuming that you want to apply this transformation to 1st and 3rd columns. You can achieve this by using MinMaxScaler from sklearn</p> <pre><code>from sklearn.preprocessing import MinMaxScaler import numpy as np X = np.array([[-0.23685953, 0.04296864, 0.94160742], [-0.23685953, 1.05043547, 0.6767...
python|pandas|numpy
0
6,324
51,225,370
python decoding Non-English to use as url?
<p>I have a variable such as <code>title</code>:</p> <pre><code>title = "révolution_essentielle" </code></pre> <p>I could encode and decode it like this for other purposes:</p> <pre><code>title1 = unicode(title, encoding = "utf-8") </code></pre> <p>But how do I preserve the Non-English and use it as part of a url s...
<p>To summarize what we've talked about in the comments: there is a function for quoting URLs (replacing special characters with <code>%</code> prefix escape sequences. </p> <p>For Python 2 (as used in this case), it's <a href="https://docs.python.org/2.7/library/urllib.html#urllib.quote" rel="nofollow noreferrer"><co...
python|unicode|utf-8|io|decode
0
6,325
64,213,222
Linear regression using gradient descent; having trouble with cost function value
<p>I'm coding linear regression by using gradient descent. By using for loop not tensor.</p> <p>I think my code is logically right, and when I plot the graph theta value and linear model seems to be coming out good. But the value of cost function is high. Can you help me?</p> <p><a href="https://i.stack.imgur.com/eHCk6...
<p>I think the dataset itself is quite widespread and that's why the best fit line shows a large amount for the cost function. If you scale your data - you would see it drop significantly.</p>
python|machine-learning|linear-regression|gradient-descent
2
6,326
70,479,164
Cannot find index.html when it exists (Flask Python)
<p>In the near end of creating my server, I created a homepage and attached it to the python file, But when I tried to access the homepage from my phone, On the log it returned this:</p> <blockquote> <p>jinja2.exceptions.TemplateNotFound: /index.html - - [25/Dec/2021 20:27:57] &quot;GET / HTTP/1.1&quot; 500 -</p> </blo...
<p><code>index.html</code> should be inside a directory called <code>templates</code></p> <p>Also you could do without the forward-slash in the argument to <code>render_template</code>:</p> <pre><code> return render_template('index.html') </code></pre>
python|flask|server
0
6,327
72,901,754
PySpark: Generate timestamp string from available data
<p>How can I transform a malformed timestamp string into one that is represented as days, hours, minutes, seconds?</p> <p>Consider the following example:</p> <pre><code># create df df = spark.createDataFrame(sc.parallelize([['1970-01-13T22:05:38.391+0000', '12.22:05:38.3910000']]), [&quot;ts&quot;, &quot;expectedValue&...
<p>There are some problems in your code</p> <p>below code I think should suffice your requirements</p> <pre><code># create df df = spark.createDataFrame(sc.parallelize([['1970-01-13T22:05:38.391+0000',]]), [&quot;ts&quot;]) # try to remove a day df = df.withColumn(&quot;ts_altered_minus1&quot;, F.col('ts').cast('times...
python|pyspark
1
6,328
55,740,060
how to minimize the code using python django
<p>i have a nested if condition to check the conditions.how can i minimize the code?what should i do shorten the code? I have created a funtion and inside thet function i am checking the id of meter which the user has given and updating the table in the database.</p> <p>def updatereport(meterdetails_id, indicator='inr...
<pre><code>def updatereport(meterdetails_id, indicator='inr'): if meterdetails_id == 1: proper_function_name('happycount', indicator) elif meterdetails_id == 3: proper_function_name('disappointedcount', indicator) elif meterdetails_id == 2: proper_function_name('depressedcount', indi...
python-2.7|django-rest-framework
0
6,329
64,688,971
Python pandas replace by None actually replaces with previous value
<p><code>pandas</code>' <code>replace</code> function replaces targeted values with another, as expected:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; &gt;&gt;&gt; &gt;&gt;&gt; t = pd.Series([10,20,30]) &gt;&gt;&gt; t 0 10 1 20 2 30 dtype: int64 &gt;&gt;&gt;...
<p>This is because <code>to_replace</code> is a scalar and <code>value</code> is None. That behaviour is described in the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.replace.html" rel="nofollow noreferrer">documentation</a>:</p> <blockquote> <p>The method to use when for replace...
python|pandas
1
6,330
64,964,804
pip install pyarrow failing in Linux / Inside a docker
<p>I tried installing pyarrow and it's failing with the below error. I also tried the option --no-binary :all: and still the same problem. Any help to resolve this will really help me.</p> <p>Python version: 3.7 Linux version: python:3.7-alpine Below is the stack trace of the install.</p> <pre><code>**sudo pip install ...
<p>The most likely guess here is that you are missing <code>cmake</code>. As you are probably on a Linux distribution that doesn't support <code>manylinux</code> wheels, you need all the build dependencies for <code>pyarrow</code> as listed on <a href="https://arrow.apache.org/docs/developers/python.html#using-pip" rel...
python-3.x|pip|pyarrow
5
6,331
53,035,977
Multiple list comprehensions from a single CSV file source
<p>I'm trying to use list comprehensions to get specific columns from a CSV file source. </p> <p>Here's some code that simulates the CSV file data that I see: </p> <pre><code>import pandas as pd import numpy as np # Setup of simulated data seconds = [1,2,3] values = [0.5,0.4,0.3] non_relevant_data = [8,6,7] nanos = ...
<p>Try this instead:</p> <pre><code>table=pd.read_csv('data.csv', header=None) secs = np.array([row[0] for row in table.itertuples(index=False,name=None)]) vals = np.array([row[1] for row in table.itertuples(index=False,name=None)]) nano = np.array([row[3] for row in table.itertuples(index=False,name=None)]) </code><...
python|pandas|csv|list-comprehension
0
6,332
71,997,213
How to scrape all data from first page to last page using beautifulsoup
<p>I have been trying to scrape all data from the first page to the last page, but it returns only the first page as the output. How can I solve this? Below is my code:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import numpy as np import requests from bs4 import BeautifulSoup from time impo...
<p>The page is loaded dynamically using the API. Therefore, with a regular GET request, you will always get the first page. You need to study how the page communicates with the browser and find the request you need, I wrote an example for review.</p> <pre><code>import json import requests def get_info(page): url ...
python|web-scraping|beautifulsoup
1
6,333
68,478,327
Split txt file by Year and ID and rename each new txt file as "Year_ID.txt"
<p>I have a bunch of txt files (comma separated) and I want to split the file into separate text files by using common group identifiers from Column 1(Year) and Column 3(ID). Also, I would like to save the new filenames as &quot;Column1_Column3.txt&quot;.I do not want to keep any header for these files. I have tried ma...
<p>Assumptions:</p> <ol> <li>All entries are uniform</li> <li>Entries are housed in a 2d list</li> <li>All entries have at least length 3 (to include both delimiting fields)</li> </ol> <p>Slight concern:</p> <ul> <li>In File1, is the second entry supposed to have '2055791 ' in front of it? This would mean that the list...
python|csv|split|txt
1
6,334
61,954,871
Scraping Yahoo Finance with Python3
<p>I'm a complete newbie in scraping and I'm trying to scrape <a href="https://fr.finance.yahoo.com" rel="nofollow noreferrer">https://fr.finance.yahoo.com</a> and I can't figure out what I'm doing wrong. </p> <p>My goal is to scrape the index name, current level and the change(both in value and in %) <a href="https:...
<p>I think you need to fix your element selection.</p> <p>For example the following code:</p> <pre><code>import urllib.request from bs4 import BeautifulSoup url = 'https://fr.finance.yahoo.com' request = urllib.request.Request(url) html = urllib.request.urlopen(request).read() soup = BeautifulSoup(html,'html.parser...
python|python-3.x|web-scraping|beautifulsoup
1
6,335
63,569,336
Python: Multiprocessing in a simple loop
<p>My objective is to get the <strong>source code of various web pages</strong> with the Selenium Driver Package. To use idle time while opening pages, I would love to <strong>make use of multiprocessing</strong>. However, as I am new to multiprocessing, I do not manage to make my code work.</p> <p>This is a <strong>si...
<p>When using <code>multiprocessing.pool</code>, use the <code>apply_async</code> method to map a function to a list of parameters. Note that since the function is run asynchronously, you should pass some sort of index to the function and have it returned with the result. In this case, the function returns the URL alon...
python|selenium-webdriver|web-scraping|multiprocessing
2
6,336
56,482,747
Extract text within quotation marks on webpage
<p>Is there a simple way to extract all text on a webpage that is within quotation marks? Simply parsing the HTML code as string doesn't do the trick it seems.</p>
<p>Replace the yahoo link with any link you want. This will return a list of all sentences and words between double quotes. </p> <pre><code>from bs4 import BeautifulSoup from bs4.element import Comment import urllib import re def tag_visible(element): if element.parent.name in ['style', 'script', 'head', 'title...
python|web-scraping
1
6,337
56,654,952
How to mark cells in matplotlib.pyplot.imshow (drawing cell borders)
<p>I have a small 2d vector to display:</p> <pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt import numpy as np img = np.random.rand(4,10) plt.imshow(img, cmap='Reds') </code></pre> <p>As folllow:</p> <p><a href="https://i.stack.imgur.com/ZWTQS.png" rel="noreferrer"><img src="https://...
<p>Put a rectangle at the position of the pixel you want to highlight.</p> <pre><code>import matplotlib.pyplot as plt import numpy as np def highlight_cell(x,y, ax=None, **kwargs): rect = plt.Rectangle((x-.5, y-.5), 1,1, fill=False, **kwargs) ax = ax or plt.gca() ax.add_patch(rect) return rect img = ...
python|matplotlib
14
6,338
68,117,742
Command for posting user's avatar
<pre class="lang-py prettyprint-override"><code>@bot.command(aliases=['av']) async def avatar(ctx, *, avamember : discord.Member = None): userAvatarUrl = avamember.avatar_url await ctx.send(userAvatarUrl) </code></pre> <p>I would like the command to post the mentioned user's avatar. If no user is mentioned, it...
<p>You can check if <code>member</code> is <code>None</code>, then use the avatar of the <code>ctx.author</code>:</p> <pre class="lang-py prettyprint-override"><code>@bot.command(aliases=['av']) async def avatar(ctx, *, member : discord.Member = None): if member == None: user_avatar_url = ctx.author.avatar_url els...
python|discord|discord.py|bots
1
6,339
59,558,460
Merge two tensor in pytorch
<p>Tensor a:</p> <pre><code>tensor([[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]) </code></pre> <p>Tensor b:</p> <pre><code>tensor([4,4,4,4]) </code></pre> <p>Question 1:</p> <p>How to merge two tensors and get result c:</p> <pre><code>tensor([[1, 2, 3, 4], [1, 2, 3, 4], [1,...
<p>Question 1: Merge two tensors - </p> <pre class="lang-py prettyprint-override"><code>torch.cat((a, b.unsqueeze(1)), 1) &gt;&gt;&gt; tensor([[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]) </code></pre> <p>First, we use <a href="https://pytorch.org/docs/stable/torch.ht...
pytorch
1
6,340
25,070,940
How to insert string into another string with same multiple occurrences
<p>How the following syntax can be simplified?</p> <pre><code>three='Three' result='One-Two-%s, One-Two-%s, One-Two-%s'%(three,three,three)) </code></pre> <h1>Edited later:</h1> <p>Another surprise: getting <code>KeyError: 'border'</code> on this:</p> <pre><code>color='#262626' style="QProgressBar{background-color:...
<pre><code>&gt;&gt;&gt; three = 'Three' &gt;&gt;&gt; result = 'One-Two-{ph:s}, One-Two-{ph:s}, One-Two-{ph:s}'.format(ph=three) &gt;&gt;&gt; print result One-Two-Three, One-Two-Three, One-Two-Three </code></pre> <p><strong>Edit</strong>:</p> <pre><code>&gt;&gt;&gt; style="QProgressBar{{background-color: {ph:s}}}".for...
python
2
6,341
30,565,493
Read from stdin in Python Process?
<p>I'm trying to read from sys.stdin from inside of a Python Process object, but I keep getting a "ValueError: I/O operation on closed file" result. Here's a quick example:</p> <pre><code>import sys from multiprocessing import Process def do_something(input_data): for x in input_data: print x input=sys....
<p>This is because before the Process is started, <code>stdin</code> is closed. Otherwise it could happen that both the parent and child process (or multiple child processes) try to read from the same stdin, which is a bad idea.</p> <p>In the child process <code>sys.stdin</code> is actually redirected to <code>/dev/nu...
python|process|stdin
4
6,342
66,934,445
Filling Dataframe with data from For-Loop
<p>I am trying to fill an DataFrame with every second word from another element, but that doesn't work:</p> <pre><code>import pandas as pd output[0] = &quot;Word 1&quot; output[2] = &quot;Word 2&quot; output[4] = &quot;Word 3&quot; tab = pd.DataFrame(index=5, columns=1) tab = tab.fillna(0) f=0 for i in range(1,le...
<p>It is not very clear what you are trying to achieve, please review <a href="https://stackoverflow.com/help/minimal-reproducible-example">this</a> and edit your question</p> <p>But going out on a limb here, suppose you have a list <code>output</code>:</p> <pre><code>output = [f'Word {n}' for n in range(10)] print(out...
python|dataframe
0
6,343
42,998,989
Batch_size in tensorflow? Understanding the concept
<p>My question is simple and stright forward. What does a batch size specify while training and predicting a neural network. How to visualize it so as to get a clear picture of how data is being feed to the network.</p> <p>Suppose I have an autoencoder</p> <pre><code>encoder = tflearn.input_data(shape=[None, 41]) enc...
<p>The batch size is the amount of samples you feed in your network. For your input encoder you specify that you enter an unspecified(None) amount of samples with 41 values per sample. </p> <p>The advantage of using None is that you can now train with batches of 100 values at once (which is good for your gradient), an...
python-3.x|tensorflow|tflearn
13
6,344
45,218,671
getattr - Exception Value: module 'django.db.models' has no attribute 'model_name''
<p>I have a probleme for use a variable in model name, i want to take this command :</p> <pre><code>MyVar.objects.all().delete() </code></pre> <p>and in the same way i have to a probleme for take this : </p> <pre><code>class MyCsvModel(CsvDbModel): class Meta: dbModel = MyVar ...
<pre><code>import models model_name = "X" getattr(models, model_name).objects.all().delete() class MyCsvModel(CsvDbModel): class Meta: dbModel = getattr(models, model_name) delimiter = delimiter_csv </code></pre>
python|django|variables|getattr
0
6,345
45,255,752
Plot 2 Dataframes in one Figure in Pandas
<p>Hey I want to plot 2 DataFrames in one Figure in Pandas.</p> <p>My DataFrame(s) look like this(excerpt from DataFrame):</p> <pre><code> Timestamp Distance Speed Heart Rate Pace 1 0.0 3.02 2.353079 89 425.0 2 1.0 5.10 1.847000 92 541.0 3 2.0 ...
<p>Consider the following approach:</p> <pre><code>import matplotlib.pyplot as plt fig, axes = plt.subplots(nrows=3, ncols=1) plt.subplots_adjust(wspace=0.5, hspace=0.5); x = dataframe1.set_index('Timestamp').rename_axis(None) x['Speed'].plot(ax=axes[0], title='Speed in m/s', legend=True) x['Heart Rate'].p...
python|pandas|matplotlib|plot
4
6,346
56,043,160
Problems running ev3 mindstorms on visual studio code
<p>Whenever I try running the default main program I get</p> <p><code>/usr/bin/env: 'pybricks-micropython': No such file or directory</code></p> <p>Anyone know what this means?</p>
<p>It's likely your MicroSD card image is not the correct one for Lego micropython. Try creating the MicroSD card again from this site: <a href="https://education.lego.com/en-us/support/mindstorms-ev3/python-for-ev3" rel="nofollow noreferrer">https://education.lego.com/en-us/support/mindstorms-ev3/python-for-ev3</a></...
python|visual-studio-2010|lego-mindstorms|lego-mindstorms-ev3
1
6,347
69,423,395
Python move pictures from one folder to another ignoring case
<p>I am trying to create a script to move all the picture files from one folder to another. I have found the script that works for this, except it doesn't work if the extensions are in capitals. Is there an easy way around this?</p> <p>Current code:</p> <pre><code>import shutil import os source = &quot;C:/Users/Tonel...
<p>You could lowercase the extension before checking it:</p> <pre class="lang-py prettyprint-override"><code>if os.path.splitext(f)[1].lower() in (&quot;.jpg&quot;, &quot;.gif&quot;, &quot;.png&quot;): # Here --------------^ </code></pre>
python|windows|scripting
1
6,348
55,278,053
Approaching way for Many To Many Intermediate Model in Django Rest Framework
<ul> <li>I would like to get your opinions is this approaching way correct? </li> <li>How can I do serializing m2m intermediate model better ?</li> <li>I would like to know how to combine <code>Display</code> and <code>Create</code> serializers..</li> <li><code>models.py</code></li> </ul> <pre class="lang-py prettypri...
<p>You can use <code>RetrieveAPIView</code> for display and <code>CreateAPIView</code> for create which is builtin features and can make things simpler and for other developers to work with your code easier because all they need to be familiar with is the way DRF works not the way you wrote the code. Basically it's bet...
python|django|django-rest-framework|django-serializer
1
6,349
25,728,255
How much request volume can Microsoft Web Ngram API handle?
<p>I currently have a list of 200 words from which I need to create semantically correct permutations. Unfortunately, permutating through a list of that size will lead to something like a trillion permutations. </p> <p>What I am planning to do is utilize the Microsoft Web Ngram service and a yield function to find n...
<p>There is no limit on the number of queries you can make. However, the terms of use disallow threaded access, and the server response is relatively slow (between 0.12 and 0.22 s each query). So you could get at most 720k queries in a 24 hour period. I'm using PHP's file_get_contents(...). There may be a faster way.</...
python-3.x|n-gram
0
6,350
49,702,634
data dictionary to html table
<p>I have the following data dictionary, I would like to convert this to HTML table - tried different things but no success.</p> <pre><code>data = {'102 Not Out': "('75', '04 May 2018'),N/A",'2.0': "('84', 'Expected in January 2019'),8.5",'3 Dev': "('0', '11 May 2018'),No IMDB Info Available",'Adityam': "('34', '27 A...
<p>Using Python 3 - <code>literal_eval()</code> and <code>.items()</code></p> <p>Your value contains a <code>tuple</code> and a <code>str</code>. So you need to split it.</p> <p>So should be like:</p> <pre><code>from ast import literal_eval for key, value in data.items(): message += '&lt;tr&gt;' values = valu...
python|python-3.x
1
6,351
49,367,756
How to add a list of lists as one row to dataframe, with each list in one cell? - Python
<p>I have a lists of lists, that I want to convert to one row in a DataFrame. Each list should come in a cell in the DataFrame. When completed, I want to add the next list of lists in the same way.</p> <p>This is what I do:</p> <pre><code>import pandas as pd lst1 = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']] ...
<p>So is this what you need ? </p> <pre><code>pd.DataFrame([lst1,lst2]) Out[500]: 0 1 2 0 [a, b, c] [d, e, f] [g, h, i] 1 [j, k, l] [m, n, o] [p, q, r] </code></pre>
python|list|pandas
1
6,352
46,036,324
Pyspark: selecting data in remote Hive Server
<p>Trying to read and write data stored in remote Hive Server from Pyspark. I follow this example:</p> <pre><code>from os.path import expanduser, join, abspath from pyspark.sql import SparkSession from pyspark.sql import Row # warehouse_location points to the default location for managed databases and tables warehou...
<p> You can call the table directly using </p> <pre class="lang-py prettyprint-override"><code>spark.sql("SELECT * FROM mytest.iris") </code></pre> <p>Or specify the database you want to work with with </p> <pre class="lang-py prettyprint-override"><code>spark.sql("use mytest") spark.sql("SELECT * FROM iris) </code>...
python|hadoop|hive|pyspark
0
6,353
30,807,230
ValueError: error during iteration "Pysam"
<p>I have ran into this error and I am having trouble resolving it. Here is it what I get:</p> <pre><code>Traceback (most recent call last): File "afile.py", line 100, in &lt;module&gt; for col in bam.pileup( chrm, ps1, ps1+1,truncate=True): File "pysam/calignmentfile.pyx", line 2060, in pysam.calignmentfile.Iter...
<p>i hit this recently. the root cause in my case was that the <code>.bai</code> bam index file was out of date. after i regenerated it with <code>samtools index XXX.bam</code>, the pysam crash went away.</p>
python|pysam
1
6,354
52,058,971
Python Tkinter Window and Widget Size Measurements
<p>Does anyone know in what units are the measurements made in tkinter objects?</p> <p>For example:</p> <pre><code>ws='400' #i am assuming these are in pixels hs='400' root=tk.Tk() root.geometry(ws+'x'+hs) </code></pre> <p>...</p> <pre><code>self.w1=tk.Label(self.parent,width=int(int(ws)*5/8) #The width here probab...
<p>It depends on the widget, and also on how the widget is configured. For <code>Label</code> and <code>Button</code> widgets the <code>width</code> and <code>height</code> refer to a number of average sized characters (internally, I believe it uses the width and height of the character zero). If you add an image to th...
python|tkinter|size|measurement
3
6,355
32,405,117
Limit Choices to Foreign Key based on lookups that span relationships
<p>This is what I have so far.</p> <p><strong>models.py</strong></p> <pre><code>class Company(models.Model): company_name = models.CharField('Company', max_length=40, unique=True) company_type = models.CharField('Type', max_length=20, null=True, blank=True) class MyUser(AbstractBaseUser): email = models....
<p>There is no way to define it dynamically on the database level using <code>limit_choices_to</code>. You simply need to define it on your form/view etc. i.e Use a <a href="https://docs.djangoproject.com/en/dev/ref/forms/fields/#modelchoicefield" rel="nofollow">modelchoicefield</a>.</p>
python|django|django-models|foreign-keys
1
6,356
28,047,561
Binding ip address to urllib2 is not working for me
<p>I am newb to urllib2. I tried binding ip address to URL request using urllib2,it does not works for ip address given by tor.</p> <pre><code>import socks import socket import urllib2 true_socket = socket.socket def make_bound_socket(source_ip): def bound_socket(*a, **k): sock = true_socket(*a, **k) ...
<p>You are asking to bind to the interface corresponding with IP address <code>123.108.224.70</code>. If there is no corresponding interface on your machine, then the socket can't be bound, and you'll see an error. Here is a simplified example:</p> <pre><code>&gt;&gt;&gt; import socket &gt;&gt;&gt; s = socket.socket()...
python|binding|urllib2|tor
1
6,357
44,370,861
Python sort strings with dot/separated numbers and strings at the end
<p>I have an array of dicts like:</p> <p><code>array_x = [{'title': 'Copy -- @1.1 true files'}, {'title': 'Copy -- @1.11 true files'}, {'title': 'Copy -- @1.3 true files'}, {'title': 'Copy -- @1.2 true files'}, {'title': 'Copy -- @1.12 true files'}, {'title': 'Copy -- @1.22 true files'}, {'title': 'After -- @1.1 copy...
<p>How about this: discard everything before and including the <code>@</code> sign, then convert each period-separated section into ints. That should fix the problem of the digit sequences being sorted lexicographically.</p> <pre><code>&gt;&gt;&gt; array_x = [{'title': 'Copy -- @1.1'}, {'title': 'Copy -- @1.11'}, {'ti...
python|sorting
1
6,358
44,345,139
python asyncio add_done_callback with async def
<p>I have 2 functions: The first one, <code>def_a</code>, is an asynchronous function and the second one is <code>def_b</code> which is a regular function and called with the result of <code>def_a</code> as a callback with the <code>add_done_callback</code> function.</p> <p>My code looks like this:</p> <pre><code>imp...
<p><code>add_done_callback</code> is considered a &quot;low level&quot; interface. When working with coroutines, you can <a href="https://docs.python.org/3.6/library/asyncio-task.html#example-chain-coroutines" rel="nofollow noreferrer">chain them</a> in many ways, for example:</p> <pre><code>import asyncio async def...
python|python-3.x|async-await|python-asyncio|coroutine
32
6,359
32,993,775
Python nose/unittests: where to define constants such as credentials
<p>I use nose and unittest to test my code, some of which involves interacting with external (web) API's that require some form of authentication (OAuth, for example). What, and where, is the proper way to define/retrieve constants that are a) <strong>required for running the tests</strong>, and b) <strong>not OK to ex...
<p>If this is for integration testing, the way I've done this before is setting environment variables on the machine and importing them in python. </p> <pre><code>import os password = os.environ['PASSWORD'] username = os.environ['USERNAME'] </code></pre> <p>This keeps any password or usernames out of your code base</...
python|unit-testing|nose|python-unittest
2
6,360
27,018,998
python rotating file handler callback
<p>I'm using the RotatingFileHandler (<a href="https://docs.python.org/2/library/logging.handlers.html" rel="nofollow">https://docs.python.org/2/library/logging.handlers.html</a>) in Python to log messages - is there anyway to do a function callback when the RotatingFileHandler switches to a new file?</p> <p>For examp...
<p>There's not really a callback, but you can easily subclass the RotatingFileHandler and override your own "rotation", by implementing the <a href="https://docs.python.org/2/library/logging.handlers.html#logging.handlers.RotatingFileHandler.doRollover" rel="nofollow">doRollover method</a>:</p> <pre><code>MyFileHandle...
python|logging|file-handling
2
6,361
33,558,871
Error while calling class instances
<p>this program I am making in Python 2.7 with Pygame. It's my first attempt to create a game using classes. I am trying to initialize a class with stats for the hero, such as hp, speed, etc named 'archer'. When I try to run the code, it gives me this error:</p> <p><code>Traceback (most recent call last): File "C:/P...
<p><code>archer</code> is a local variable, and thus isn't visible to the global scope that the last line of your program is operating on. You probably want to make <code>heroSelect()</code> return the Hero object that is created, and then have the <code>preStuff()</code> method return that as well.</p>
python|class|pygame
0
6,362
29,950,035
Get data from cell in pandas and user it in calculations
<p>I've got a CSV file which I am loading in to a table using pandas.</p> <pre><code> Rank Player Nat Tot MtchWin-Loss Tie BrkWin-Loss \ 0 1 Novak Djokovic SRB 5-0 0-0 1 2 Roger Federer SUI 1-1 0-1 2 ...
<p>What is returned is a Series, if you want just the value:</p> <pre><code>firstServePecentage = df[df['Player'] == 'Novak Djokovic']['1st Srv'] firstServePecentage.values[0] </code></pre>
python|python-2.7|pandas
2
6,363
43,075,872
How to use BeautifulSoup to find all the next links
<p>I'm currently scraping all the page of a specific website by presetting a variable called number_of_pages. Presetting this variable works until a new page is added that I don't know about. For example the code below is for 3 pages, but the website now has 4 pages. </p> <pre><code>base_url = 'https://securityadviso...
<p>There are several different ways to approach the pagination. Here is one of them.</p> <p>The idea is to <em>initialize an endless loop and break it once there is no "next" link</em>:</p> <pre><code>from urllib.parse import urljoin from bs4 import BeautifulSoup import requests with requests.Session() as session:...
python|python-3.x|web-scraping|beautifulsoup
4
6,364
64,198,347
Python Anywhere - No module named 'sklearn.linear_model._stochastic_gradient'
<p>I want to use the <strong>pickle</strong> module and serialize the model learned on my computer:</p> <pre><code>pickle.dump(clf, open(os.path.join(dest, 'classifier.pkl'), 'wb'), protocol=4) </code></pre> <p>When I open it <strong>on my computer as well</strong>, everything works fine:</p> <pre><code>clf = pickle.lo...
<p>You can create a <code>requirement.txt</code> file where you define all the necessary dependencies with versions. Or you can make a virtual environment like they have in the <a href="https://help.pythonanywhere.com/pages/InstallingNewModules/" rel="noreferrer">docs</a>. Or you can try running <code>pip install sciki...
python|scikit-learn|pickle|pythonanywhere
6
6,365
64,275,105
Installation of pythonnet on Ubuntu 18.04 - problems with nuget.exe
<p>I try to install the <code>pythonnet</code> library on linux, but I can have trouble with nuget/mono.</p> <p>I tryed to run the following (<a href="https://stackoverflow.com/questions/55058757/install-pythonnet-on-ubuntu-18-04-python-3-6-7-64-bit-mono-5-16-fails">Install pythonnet on Ubuntu 18.04, Python 3.6.7 64-bi...
<p>I had the same problem and needed to install mono first:</p> <blockquote> <p>sudo apt-get install mono-complete</p> </blockquote>
linux|mono|nuget|python.net
3
6,366
64,481,368
Change date in Dataframe when midnight reached
<p>I've got a Dataframe with a column 'Date_and_time' which is in datetime format. Unfortunately, when midnight is reached (line 15235: 2020-08-02 00:00:00.000000), the date doesn't change accordingly. So, 2020-08-02 00:00:00.000000 should go to 2020-08-03 00:00:00.00000 when midnight (00:00:00.000000) is reached. On l...
<p>This is essentially another question requiring the &quot;diff-cumsum&quot; trick to accumulate the number of negative changes. In this case, however, <code>.diff()</code> does not support datetime difference so it would be more tricky to do.</p> <p>Here is a quick and dirty showcase on <code>df[&quot;Date_and_time&q...
python|pandas
0
6,367
70,706,244
How to get file ID from box.com by passing the file name in python
<p>How to obtain file_id from &quot;file name&quot; in Box.com API</p> <p>Not sure which call will I make from this <a href="https://developer.box.com/reference/#searching-for-content" rel="nofollow noreferrer">https://developer.box.com/reference/#searching-for-content</a>.</p> <p>I want to pass filename and get file i...
<p>The method to retrieve file information is found in the <a href="https://developer.box.com/reference/get-files-id/" rel="nofollow noreferrer">documentation here</a></p> <p>So if you are using python, it should look something like this according to the API documentation:</p> <pre><code>file_id = '11111' file_info = c...
python-3.x|django|box
-1
6,368
55,584,860
Contributions of variables to PC in python
<p>I used PCA to find 60 PC's:</p> <pre><code>N_comp=60 from sklearn.decomposition import PCA pca = PCA(n_components = N_comp) X_pca=pca.fit_transform(X_scale) #lower dimension data eigenvalues=pca.components_ </code></pre> <p>Now, I'm trying to find the contributions of my features (the columns of X data) to PC1 an...
<p>First off, please consider the comments and what you can do to improve on the quality of your question. Critical components of a "good" question around here are (1) reproducible sample data, (2) a genuine code attempt, and (3) a <em>specific</em> coding question rather than a post asking "how to implement XYZ".</p> ...
python|plot|bar-chart|pca|feature-extraction
1
6,369
49,883,570
Looping through an object's (class instance) properties in python and printing them
<p>In python, how can an object's properties be accessed without explicitly calling them? And print those properties?</p> <p>Ex:</p> <pre><code>class MyClass: def __init__(self): self.prop1 = None self.prop2 = 10 def print_properties(self): # Print the property name and value example_a = My...
<p>I found for a basic object, the following internal function accomplishes the task:</p> <pre><code>def print_properties(self): for attr in self.__dict__: print(attr, ': ', self.__dict__[attr]) </code></pre> <p>All together:</p> <pre><code>&gt;&gt;class MyClass: def __init__(self): self.prop...
python|oop|properties
2
6,370
66,539,555
Cross entropy IndexError Dimension out of range
<p>I'm trying to train a GAN in some images, I followed the tutorial on pytorch's page and got to the following code, but when the crossentropy function is applyed during the training it returns the error below the code:</p> <pre><code>import random import torch.nn as nn import torch.optim as optim import torch.utils.d...
<p>Your model's output is not consistent with your criterion.</p> <p><strong>If you want to keep the model and change the criterion:</strong></p> <p>Use <a href="https://pytorch.org/docs/stable/generated/torch.nn.BCELoss.html#torch.nn.BCELoss" rel="nofollow noreferrer"><code>BCELoss</code></a> instead of <code>CrossEnt...
python|image-processing|pytorch|cross-entropy
2
6,371
64,979,044
Filter all rows based on one specific index value, python and pandas
<p>I am trying to output a filtered list based on the input of the index. In my case, I want to make the Location the index, and only show all the results whose location is 'Switzerland'. I am using jupyter-notebook</p> <p>I have an xlsx file called Book1 containing [here.][1] , I type this in.</p> <pre><code>import pa...
<p>I believe this is an off-by-one error</p> <p>You are assuming <code>Pandas</code> is 0-indexing their arrays, but it looks like they are 1-indexing it.</p> <p>Using the 2nd column as the index should solve this.</p>
python|pandas|dataframe|jupyter-notebook
0
6,372
63,948,320
Python Selenium fails to select search bar
<p>I am trying to use selenium to search for courses on <a href="https://catalog.swarthmore.edu/" rel="nofollow noreferrer">https://catalog.swarthmore.edu/</a> and scrape the results. All the selectors I have attempted to use fail, and when I print them out they return empty arrays. Why did these selectors fail, and wh...
<p>The page has multiple elements with id=keyword so the results is a list. To send the keys, select the first element from the list:</p> <p>Try this code:</p> <pre><code>search = css('keyword')[0] #(&quot;span.show.clearfix input&quot;)#css(&quot;#keyword&quot;)#get search field </code></pre> <p>You should probably c...
python|html|css|selenium|selenium-webdriver
2
6,373
52,980,249
Mastermind Python with String.split()
<p>How can you make this program make the user input 5 digits at once, instead of asking separate numbers each time? I know I have to use string.split() but where would I place the code and execute the code. </p> <pre><code>Heading from random import randint n1 = randint(1,9) n2 = randint(1,9) n3 = randint(1,9) n4 =...
<p>You just have to split the numbers in a single input and convert them into integers using a list comprehension. You can also create your <code>random_n</code> using a similar method.</p> <pre><code>from random import randint random_n = [randint(1,9) for i in range(4)] c = 1 while True: print(random_n) use...
python
1
6,374
52,933,229
Django - combining two models serializer into one JSON response
<p>I have two models List and Card. I'm trying to combine these two and make a single JSON response</p> <p>My List JSON response</p> <pre><code>[ { "id": 1, "name": "List of things to do" }, { "id": 2, "name": "one more" } ] </code></pre> <p>My Card JSON response</p> ...
<p>You can also use SerializerMethodeField <a href="https://www.django-rest-framework.org/api-guide/fields/#serializermethodfield" rel="nofollow noreferrer">https://www.django-rest-framework.org/api-guide/fields/#serializermethodfield</a>.</p> <pre><code>class ListSerializer(serializers.ModelSerializer): cards = s...
python|django|django-rest-framework
4
6,375
53,294,759
How to install package using pip when you have 2 Python versions
<p>I have <code>2</code> anaconda in my system: <code>one with python 2.7</code> &amp; and <code>another with python 3.5</code>.</p> <p>My command prompt is showing python version as <code>2.7</code>. </p> <p>I need to install one package for <code>Python 3.5</code> using <code>pip</code> only,not conda install. I in...
<p>To install a package in specific version, try this:</p> <h3>A specific version of python:</h3> <pre><code>$ python-3.5 -m pip install &lt;pkg-name&gt; </code></pre>
python
2
6,376
53,285,358
CodecRegistryError: incompatible codecs in module "encodings.ascii" when running Nosetests in PyCharm
<p>I am attempting to run Nosetests through PyCharm using a virtual environment, and am running into the following error. </p> <p><code>encodings.CodecRegistryError: incompatible codecs in module "encodings.ascii" (/Users/Environments/work_dir/lib/python2.7/encodings/ascii.pyc)</code></p> <p>This is only happening in...
<p>I had special character in the project path. When removed &quot;–&quot; it started working.</p>
python|runtime-error|codec
0
6,377
52,943,572
How to keep the last value in Pandas without removing the rows
<p>I am working on a dataset in which I want to attribute the last action of a user to a certain goal. In the process I arrive at below tableset.</p> <pre><code>table date | action_id | u_id | goal 2016-01-08 | CUID22 | 586758 | 'Goal#1' 2017-03-04 | CUID45 | 586758 | ...
<p>I beleive you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.duplicated.html" rel="nofollow noreferrer"><code>duplicated</code></a>:</p> <pre><code>cols = ['u_id','goal'] df.loc[df.duplicated(cols, keep='last'), cols] = np.nan </code></pre> <p>Or:</p> <pre><code>cols = ['u_id...
pandas
0
6,378
53,234,370
pytest-xdist generate random & uniqe ports for each test
<p>I'm using pytest-xdist plugin to run some test using the <code>@pytest.mark.parametrize</code> to run the same test with different parameters.</p> <p>As part of these tests, I need to open/close web servers and the ports are generated at collection time.</p> <p>xdist does the test collection on the slave and they ...
<p>I figured that I did not give enough information regarding my issue.</p> <p>What I did was to create one parameterized test using <code>@pytest.mark.parametrize</code> and before the test, I collect the list of parameters, the collection query a web server and receive a list of "jobs" to process.</p> <p>Each test ...
python|pytest|xdist|pytest-xdist
0
6,379
65,196,721
Coditioning in python loops
<pre><code>import time import pyautogui location = pyautogui.locateOnScreen('ok.png') pyautogui.click(location) </code></pre> <p>HOW DO I WRITE THE FOLLOWING STATEMENT AS CODE?</p> <p><strong>If image is no found on screen, keep running <code>location</code> until the image is found.</strong></p> <p>otherwise the co...
<p>Try using <code>while</code> like this:</p> <pre><code>while location is not None: pyautogui.click(location) </code></pre>
python|loops|screen|screenshot|pyautogui
2
6,380
71,570,596
What is the command for starting a WSGI server for Django?
<p>I've developed an application in Django that I usually run in development mode:</p> <p><strong>python manage.py runserver</strong></p> <p>I do the same for my deployed instances - obviously a security issue that I now want to resolve.</p> <p>From the Django docs, its not clear to me how to:</p> <ul> <li>For simplici...
<p>The <code>wsgi.py</code> file just gives you a WSGI compatible application that a WSGI HTTP server (such as Gunicorn) can run.</p> <p>I guess you have to run <code>gunicorn project.wsgi</code> from the root folder (that one containing the <code>project</code> module).</p> <p>Typically, the directory containing manag...
python|django
0
6,381
5,390,752
How to reliably process web-data in Python
<p>I'm using the following code to get data from a website:</p> <pre><code>time_out = 4 def tryconnect(turl, timer=time_out, retries=10): urlopener = None sitefound = 1 tried = 0 while (sitefound != 0) and tried &lt; retries: try: urlopener = urllib2.urlopen(turl, None, timer) ...
<p>You can avoid some boilerplate code in the first function too:</p> <pre><code>time_out = 4 def tryconnect(turl, timer=time_out, retries=10): for tried in xrange(retries): try: return urllib2.urlopen(turl, None, timer) except urllib2.URLError: pass return None </code>...
python|web|urllib2|urlopen
6
6,382
62,524,960
Blacklist a role in Discord.py
<p>after trying so many thing I came up with the idea to ask you intelligent people out there! I want to blacklist 3 roles for a single command. But everything I tried failed.</p> <p>Here's the code I wrote:</p> <pre><code>member = ctx.message.author roleA = get(member.guild.roles, name=&quot;Rote Birdys&quot;) roleB =...
<p>This is just the <code>has_any_role</code> check but backwards. I also created a new error like <code>MissingAnyRole</code>:</p> <pre><code>from discord.ext.commands import check, CheckFailure import discord.utils class HasForbiddenRole(CheckFailure): def __init__(self, forbidden_roles): self.forbidden_...
python|discord|discord.py
0
6,383
62,793,482
Module not found issue in pydroid3
<p>I recently upgrade my pydroid3 to version 3.8.3, after that i successfully installed my self made third party module but trying to importing it gives following error:</p> <p><strong>Module Not Found Error</strong></p> <p>In previous version, i didn't got such error.In google play store previous version doesn't avail...
<p>Following a similar thread here -<a href="https://www.sololearn.com/Discuss/1062655/pydroid-3-no-module-named-pyqt5-kivy-form-solved" rel="nofollow noreferrer">Pydroid 3 'No Module Named PyQt5' Kivy Form</a></p> <p>You can try to either uninstall and do a fresh install of your module to see if it works. If not,rever...
python|compiler-errors|pydroid
0
6,384
61,986,084
W.r.t. GUI, what's the difference between Jupyter Notebook and Google Colaboratory?
<p>This question might be a duplicate of <a href="https://stackoverflow.com/questions/49478228/tclerror-no-display-name-and-no-display-environment-variable-in-googles-colab">this</a>, but no solution has been given yet, so let me make it clear.</p> <p>I've just tried to create a GUI with Tkinter on Google Colaboratory...
<p>Google Colab runs code on server which doesn't use GUI (Windows, XWin, X11) and it doesn't have monitor but <code>tkinter</code> (and any GUI framework) can works only with monitor connected directly to computer - in Google Colab this means monitor connected directly to server. </p> <p><code>tkinter</code> (and any...
python|user-interface|tkinter|jupyter-notebook|google-colaboratory
1
6,385
60,507,973
Python: Extend Class / Object returned from a third party package that uses factory method
<p>I'm trying to determine the best approach to wrap a third party class in another class, so I can provide a consistent internal API. The third party class is created using a fairly complicated factory method, and so is never instantiated directly. The other classes being wrapped are created directly.</p> <p>Under n...
<p>If the other class goes out of normal collaborative inheritance for its instances creation process, and even for picking the classes which to instantiate, then your best approach there will certainly not be inheritance.</p> <p>You will be better creating an association with one instance of the object in that other ...
python|api|inheritance|factory
4
6,386
71,408,140
Read json key and value as a variables to pass to another function in python
<p>I have a json config file like this</p> <pre><code>{ &quot;sources&quot;:[ { &quot;name&quot;:&quot;tbl1&quot;, &quot;var&quot;:&quot;L100&quot;, &quot;query&quot;:&quot;select c1,c2 from tbl1 where c1=L100&quot; }, { &quot;name&quot;:&quot;...
<p>You can directly get the <code>sources</code> key then iterate with each dictionary and get the required keys</p> <pre><code>for x in json_data['sources']: name, var, query = x['name'], x['var'], x['query'] # do something </code></pre>
python
1
6,387
70,366,400
count number of occurrences in csv file
<p>I want to be able to make a bar chart with the number of occurrences of a certain room (stored in a csv file). the number of rooms is not defined in the beginning.</p> <p>this is the data stored in the csv file:</p> <p><img src="https://i.stack.imgur.com/q09Qz.png" alt="csv data" /></p> <p>this is the type of graph ...
<p>Since you tagged Pandas, you can do:</p> <pre><code># read dataframe from csv df = pd.read_csv('calls.csv') # count the values in the first column counts = df.iloc[:,0].value_counts() # plot the count counts.plot.bar() </code></pre> <p>That said, you can certainly use <code>csv</code> package, but you should proba...
python|pandas|csv|matplotlib
0
6,388
11,326,348
SyntaxError: invalid syntax href = 'http://maps.google.com' + href
<pre><code>def download_if_dne(href, filename): if os.path.isfile(filename): # print 'already downloaded:', href return False else: if not href.startswith('http://' href = 'http://maps.google.com' + href print 'Fixed url :', href try: print 'dow...
<p><code>if not href.startswith('http://'</code> should be <code>if not href.startswith('http://'):</code> </p>
python|compiler-errors
2
6,389
70,667,569
Changing certain column type to date from datetime
<p>I have a <code>df</code> in which I want to change certain columns type to <code>date</code> from <code>datetime</code>:</p> <pre><code>field category 2022-01-10 00:00:00 2022-01-17 00:00:00 2022-01-24 00:00:00 A 10 500 700 500 B 15 6...
<p>In your column index you mix string ('field' and 'category') and timestamp (other columns) so your column index is an <code>Index</code> not a <code>DatetimeIndex</code>.</p> <pre><code>&gt;&gt;&gt; df.columns Index([ 'field', 'category', 2022-01-10 00:00:00, 2022-01-17 00:00:00, 2022-01-2...
python|pandas|datetime
1
6,390
55,732,083
How can I perform arithmatic operations between elements of two lists with no common key in Python 2.7
<p>I have two lists with different attributes. However the final result is calculated based on a combination of two attributes picking one from each List. There is no common key between them. The following is my code--</p> <pre><code>import math import json # First list with open("acc.json") as data_file: list1...
<p>What you call <code>my_dict</code> is not a dictionary, so it does not have a <code>iteritems</code> method. It's a list, which you iterate properly with:</p> <pre><code>for acce in my_dict: ... </code></pre> <p>To iterate on the two lists together use</p> <pre><code>for acce, gyro in zip(my_dict, my_dict2):...
python|python-2.7|list|calculation
1
6,391
56,657,312
TypeError: string indices must be integers from iterating through nested dictionaries
<p>I am trying to pull some configuration information out of a json api response. It does loop through parent keys, but will not retrieve values nested beneath them.</p> <p>I have tried iterating through it by </p> <p>The JSON response looks like this:</p> <pre><code>{ "Id": null, "result": { "method...
<p>In your loop, <code>item</code> is just the dictionary key, i.e. <code>"1"</code> or <code>"2"</code>.</p> <p>But what you really want is the <em>value</em> of that key. Try this:</p> <pre><code>for config_id in out["result"]["methodName"]["config_2"]: item = out["result"]["methodName"]["config_2"][config_id]...
python|json|python-3.x
0
6,392
18,037,605
Fast membership in slices of lists
<p>I have a very large list called 'data' and I need to answer queries equivalent to</p> <pre><code>if (x in data[a:b]): </code></pre> <p>for different values of a, b and x.</p> <p>Is it possible to preprocess data to make these queries fast</p>
<h1>idea</h1> <p>you may create a <code>dict</code>. For every element store the sorted list of positions where it occurs.</p> <p>To answer query: binary search first element that greater or equal <code>a</code>, check if it exists and less than <code>b</code></p> <h1>Pseudocode</h1> <p>Preprocessing:</p> <pre><code>fr...
python|performance
4
6,393
17,821,212
a cleaner way to approach try except in python
<p>So, let say I have 3 different calls called <code>something</code>, <code>something1</code> and <code>something2</code>.</p> <p>and right now, im calling it like</p> <pre><code>try: something something1 something2 except Keyerror as e: print e </code></pre> <p>Note that in the above code, if something...
<p>You could try this, assuming you wrap things in functions:</p> <pre><code>for func in (something, something1, something2): try: func() except Keyerror as e: print e </code></pre>
python|exception|try-catch
9
6,394
61,072,172
Keyword-Based Classification of Tweets
<p>I have a data set of around 40,000 Tweets. I also have 5 text files all corresponding to different categories I would like to classify the Tweets into (travel, work, vacation, etc.) Each of these text files contains certain specific keywords for the category.</p> <p><strong>For example</strong>, the text file for v...
<p>There can be multiple ways.</p> <p>If you are just doing keyword search to label the data then I don't think that is a better approach.</p> <ol> <li><p>Keyword approach. You will count the number of keywords match and then will assign labels accordingly, but here you will have to work on feature selection to make ...
python|machine-learning|twitter|classification
0
6,395
68,951,623
Scrape complete information of all companies using API, requests in python
<p>I have a doubt and I am not getting answers for it. Using this <a href="https://www.spacresearch.com/api" rel="nofollow noreferrer">API</a> How can I get the information for All companies which are displayed <a href="https://www.spacresearch.com/symbol?s=live-deal&amp;sector=&amp;geography=" rel="nofollow noreferrer...
<p>So, for this</p> <ol> <li>Open the URL for companies using Selenium</li> <li>Wait for the table of companies to show up</li> <li>Get the list of all companies in a list.</li> <li>Use the list in the <code>get_company</code> method to get the response.</li> </ol> <p>This is the code that I think so should work, provi...
python|selenium-webdriver|web-scraping
1
6,396
69,110,639
My webpage scraper works until I use it with a for loop
<pre class="lang-py prettyprint-override"><code>def hit_scraper(link): url = str(link) options = Options() options.add_argument('--headless') options.add_argument('--disable-gpu') driver = webdriver.Chrome(executable_path=r&quot;/Users/christianfreeman/Desktop/Social_Media/chromedriver&quot;,chrome_...
<p>If you're not navigating on the site I'd use requests instead of chromedriver:</p> <pre><code> import requests def hit_scraper(link): page = requests.get(link).text soup = BeautifulSoup(page, 'html.parser') container = soup.find_all('span',attrs={&quot;class&quot;:&quot;ng-star-insert...
python-3.x
0
6,397
72,758,484
Optimize Pandas Memory Usage
<p>I'm trying to import the data. I'm getting <code>Memory Error</code>. I increased the virtual memory, and the data size is 2.71 GB. I thought about setting the data types in advance to optimize memory consumption, so I found this site: <a href="https://link.medium.com/tMf8l7rv1qb" rel="nofollow noreferrer">Optimize ...
<p>First off, <code>df.append</code> is deprecated and <code>pd.concat</code> should be used instead.</p> <pre><code>base_path = pathlib.Path('dataset') base_airbnb = [] for file in base_path.iterdir(): base_airbnb.append(pd.read_csv(rf'dataset\{file.name}', dtype={'a': np.float64, 'b': np.int32, 'c': 'Int64'}) b...
python|pandas|database
1
6,398
68,214,339
varibles declared outside __init__ Python
<p>Why variables declared outside <strong>init</strong> method do not posses additivity property? For example i have the following class:</p> <pre><code>class Trade: allTrades = [] netPosition = 0 def __init__(self, qty): self.quantity = qty self.allTrades.append(self.quantity) sel...
<p>Your <code>__init__</code> function creates two object variables which are references to the class variables of the same name. So far so good.</p> <p>When you call <code>self.allTrades.append</code> you are modifying (or <em>mutating</em>) your <code>allTrades</code> object, which is shared between all the objects ...
python-3.x|class|variables|init
1
6,399
59,072,361
how can i send JS data to django?
<pre><code>var typingTimer; var doneTypingInterval = 500; var searchedValue; $("#trackName").focusin(function(){ $(this).keyup(function(){ clearTimeout(typingTimer); if($(this).val()){ typingTimer = setTimeout(doneTyping, doneTypingInterval); } }); }); function doneTyping...
<p>To communicate with django you have two choices, one would be to use a custom template tag, in which you can pass the variable you want and make it do a database fetch for example in this case.</p> <p><a href="https://docs.djangoproject.com/en/2.2/howto/custom-template-tags/" rel="nofollow noreferrer">Here</a> you ...
javascript|python|django
1