input_text_instruct
stringlengths
282
37.9k
output_text
stringlengths
37
27.3k
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: GPFlow Multiclass classification with vector inputs causes value error on shape mismatch<p>I am trying to follow the Multiclass classification in GPFlow (using v2...
<p>When running your example I get a slightly different bug, but the issue is in how you define lengthscales and variances. You write:</p> <pre class="lang-py prettyprint-override"><code>lengthscales = [0.1]*num_classes variances = [1.0]*num_classes kernel = gpflow.kernels.Matern32(variance=variances, lengthscales=leng...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How to store the outcome of a method<p>I am trying to draw squares in random positions and random rgb values and I want 1000 of them to be created. The problem I'...
<p>Create a dot collection, then just draw that dot collection. Now you can update the dot positions separately, and they will redraw in the new positions. Here, I'm having each dot move a random amount in every loop.</p> <pre><code>import pygame import sys import random pygame.init() win = pygame.display.set_mode((8...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Subtraction assignment gives 0 and not a negative number<p>I'm messing around with probability and I'm simulating something where a user can bet <code>x</code> am...
<p>Introduce a new variable sum</p> <pre><code>def loop(possibilities, number, loop, bet): success = 0 fail = 0 sum = 0 for i in range(loop): if get_possible(x=possibilities) == number: success += 1 sum += bet * 8 else: fail += 1 sum -= bet...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: mean of a column in pandas dataframe when the 'count' value is total<p>I have a dataframe like this</p> <div class="s-table-container"> <table class="s-table"> <t...
<p>Let's load the data</p> <pre><code>from io import StringIO data = StringIO( &quot;&quot;&quot; A B yes 4 yes 3 yes 3 total nan yes 5 yes 5 total nan &quot;&quot;&quot;) df = pd.read_csv(data, delim_whitespace=True) df['B'] = df['B'].astype('float') </code></pre> <p>First we calculate the mean by group -- group...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Python subprocess terminal/space need to be adjusted to a value other than 80/24<p>I am working on invoking and executable as a part of script in python using su...
<p><code>subprocess.Popen(command,stdin=subprocess.PIPE, stdout=subprocess.PIPE)</code> executes a command and returns the result text.</p> <pre><code>import os command = &quot;some command&quot; res = os.popen(command).read() # get all content as text res = list(os.popen(command)) # get lines as array elements </code...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Dictionary of Words as keys and the Sentences it appears in as values<p>I have a text which I split into a list of unique words using set. I also have split the t...
<p>Here is an approach using list and dictionary comprehension</p> <p><strong>Code:</strong></p> <pre><code>text = 'i was hungry. i got food. now i am not hungry i am full' sents = ['i was hungry', 'i got food', 'now i am', 'not hungry i am full'] words = ['i', 'was', 'hungry', 'got', 'food', 'now', 'not', 'am', 'ful...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: efficient way to check every value in a 2d python array<p>I have a 2D numpy array of values, a list of x-coordinates, and a list of y-coordinates. the x-coordinat...
<p>You can use <a href="https://numpy.org/doc/stable/reference/generated/numpy.nonzero.html" rel="nofollow noreferrer"><code>np.nonzero</code></a> to get the indices of the elements you removed:</p> <pre><code>mask = a &lt; 1 i, j = np.nonzero(mask) </code></pre> <p>The fancy indices <code>i</code> and <code>j</code> c...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Tests in Python of a class that requests to REST API<p>I am working in a desktop client application that accesses the OneDrive (Microsoft Graph) REST API to downl...
<p>here's attached how you can improve the code above: </p> <ol> <li><p>First on constructor or <strong>init</strong> you don't need to access_token, refresh_token and expired date. To make it simple for any modules that consume this class, all of token related stuff is handled inside OneDrive Class. The class will si...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Converting a tensorflow object into a jpeg on local drive<p>I'm following the tutorial <a href="https://www.tensorflow.org/tutorials/generative/deepdream" rel="no...
<p>You can simply convert the &quot;img&quot; tensor into numpy array and then save it as you have eager execution enabled (its enabled by default in tf 2.0)</p> <p>So, the modified code for saving the image will be:</p> <pre><code>img = run_deep_dream_with_octaves(img=original_img, step_size=0.01) display.clear_outpu...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Pickleable partial class<p>I need to partially instantiate a class and later use in multiprocessing. Multiprocessing pickles classes to pass between processes. Ho...
<p>You are creating a <em>class</em>, not a 'partial instance'. Pickle doesn't serialise classes, as it assumes that all <em>code</em> can be loaded from source instead.</p> <p>Instead, produce <em>instances</em> of a utility class, one that can be pickled, and when called does the same thing as calling your generated ...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Panda dataframe conversion of series of 03Mar2020 date format to 2020-03-03<p>I'm not able to convert input</p> <pre><code>Dates = {'dates': ['05Sep2009','13Sep20...
<p>Currently the months are abbreviated and are not numeric, so you can't use <code>%m</code>. To convert abbreviated months and get the expected output use <code>%b</code>, like this:</p> <pre><code>df['dates'] = pd.to_datetime(df['dates'], format='%d%b%Y') </code></pre> <p><strong>Update:</strong> to convert the Data...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Add diagonal line to hist2d with matplotlib<p>I am analyzing the heights/widths of some ML label boxes by creating a 2D histogram with matplotlib:</p> <pre><code>...
<p>You should pass the coordinates of the line plot as a list of x values and a list of y values. For the transparency you can use the <code>alpha</code> parameter. So your code for the line should be</p> <pre><code>plt.plot([0, 0.1], [0, 0.1], marker=&quot;o&quot;, alpha=0.5) </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Python: separate utilities file or use static methods?<p>In python I have getters and setters, and calculate utilities. The getters return the property, the sette...
<p>You can achieve both <code>2</code> and <code>3</code> with this example of adding a static method to your class that is defined in a separate file.</p> <p><code>helper.py</code>:</p> <pre><code>def square(self): self.x *= self.x </code></pre> <p><code>fitter.py</code>:</p> <pre><code>class Fitter(object): d...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Problem loading a web app using flask, python, HTML and PostgreSQL; not able to connect python and html scripts plus Internal Server Error message<p>Recently, I h...
<p>You need to use <code>render_template</code> to connect Flask and your HTML code. <br> For example:</p> <pre><code>from flask import render_template @app.route(&quot;/&quot;, methods=['GET']) def index(): return render_template('index.html') </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How to use a list to print out a sentence in Python<p>I have this list of data</p> <pre><code>[ {&quot;type&quot;: &quot;Square&quot;, &quot;area&quot;: 150.5...
<p>If you want to print it then use <code>f string</code></p> <pre><code>listt = [ {&quot;type&quot;: &quot;Square&quot;, &quot;area&quot;: 150.5}, {&quot;type&quot;: &quot;Rectangle&quot;, &quot;area&quot;: 80}, {&quot;type&quot;: &quot;Rectangle&quot;, &quot;area&quot;: 660}, {&quot;type&quot;: &quot;...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: TypeError: 'type' object is not subscriptable during reading data<p>I'm pretty new importing data and I´m trying to make def that reads in the presented order. Th...
<p>Looks like the problem is right in the type hint of one of your function parameters: <code>dict[str, int]</code>. As far as Python is concerned, <code>[str, int]</code> is a <em>subscript</em> of the type <code>dict</code>, but <code>dict</code> can't accept that subscript, hence your error message.</p> <p>The fix i...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: instances.setMetadata() - nothing changes<p>I'm trying to add startup-script for an existing machine, when I do it from Google's tester ('Try this API') it works,...
<p>Solved. Gave it 'Owner' permissions and it worked. Means that I had wrong permissions. Thanks everyone! </p>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Load a gpx file on python<p>I'm a Mac user. I'm trying to load a .gpx file on python,using the following code:</p> <pre><code>import gpxpy import gpxpy.gpx gpx_fi...
<p>Obviously, one reason would be that the file does not, in fact, exist, but let us assume that it does.</p> <p>A relative filename (i.e, one that does not start with a <code>/</code>) is interpreted relative to the current working direcory of the process. You are apparently expecting that to be the user's home direct...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: 'Main' object has no attribute 'TabWidget' between parent Ui class "Ui_MainWindow" and child class "Ui_dialog_List"<p>According to the code below, when I try to t...
<p>I found a solution. It was necessary to make the following changes in the super method of the &quot;Dialoge_list&quot; classWas:</p> <pre><code>class Dialoge_list(QDialog, Ui_dialog_List): def __init__(self): super(Dialoge_list, self).__init__() </code></pre> <p>Became:</p> <pre><code>class Dialoge_list(...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Numpy masked array - find segment nearest to specific index<p>I have a series of small images, stored as 2d numpy arrays. After applying a threshold, I turn the i...
<p>Final result:<br /> <a href="https://i.stack.imgur.com/sKXyR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sKXyR.png" alt="enter image description here" /></a></p> <h2>4 steps involved here:</h2> <ol> <li>get index of the center and indices of non-masked points</li> <li>get the closest point to ...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Sort a dictionary depending of some value<pre><code>&quot;users&quot;: { &quot;673336994218377285&quot;: {&quot;votes&quot;: 5}, &quot;541388453708038165&...
<p>Dictionaries in Python (since 3.6) are sorted by their insertion order, so you have to create a new dictionary with the elements inserted in their sorted order:</p> <pre><code>users = { &quot;673336994218377285&quot;: {&quot;votes&quot;: 5}, &quot;541388453708038165&quot;: {&quot;votes&quot;: 1}, &quot;8...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How to set a new index<p>My df has the columns 'Country' and 'Country Code' as the current index. How can I remove this index and create a new one that just count...
<p>If you are using a pandas DataFrame and your DataFrame is called df:</p> <pre><code>df = df.reset_index(drop=False) </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: how to list a name n-times?<p>I have a pandas data frame named <code>df</code> and an integer variable named <code>n</code>.</p> <p>how can I create a list of <c...
<p>You can use a list comprehension to replicate the list <code>n</code> times:</p> <pre><code>l = [df for _ in range(n)] </code></pre> <p>Though note that, as mentioned in the comments, this creates <code>n</code> references to the same object, so a change in any of them will be reflected across all dataframes. If t...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: HTML Img Src Variable<p>I am trying to pass an array of image urls (in String format) from a python application to an HTML web page. In this HTML web page, I run ...
<p>Given an list of URLs, you can directly iterate over the list in jinja template. I have just made bit of correction according to the information you have provide.</p> <pre><code>{% for image_link in imgLinks%} &lt;div class=&quot;card&quot;&gt; &lt;div class=&quot;container&quot;&gt; &lt;img src={{ imag...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: CreateProcessW failed error:2 ssh_askpass: posix_spawn: No such file or directory Host key verification failed, jupyter notebook on remote server<p>So I was follo...
<p>If you need the DISPLAY variable set because you want to use VcXsrc or another X-Server in Windows 10 the workaround is to add the host you want to connect to your known_hosts file. This can be done by calling</p> <pre><code>ssh-keyscan -t rsa host.example.com | Out-File ~/.ssh/known_hosts -Append -Encoding ASCII; <...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How to create a matrix of lists?<p>I need to create a matrix MxN where every element of the matrix is a list of integers. I need a list so that I can append new e...
<p>The following function creates a 2D matrix of empty lists:</p> <pre><code>&gt;&gt;&gt; def create(row,col): ... return [[[] for _ in range(col)] for _ in range(row)] ... &gt;&gt;&gt; L = create(2,3) &gt;&gt;&gt; L[1][2].extend([1,2,3]) # add multiple integers at a location &gt;&gt;&gt; for row in L: ... print(...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Can I use the column name as condition?<p>I have a pandas dataframe which contains around a hundred columns. Most of these columns are dates and I want to iterate...
<p><em>Ensure your date columns are converted to datetime for this to work</em></p> <p>The basic steps I've used are:</p> <ol> <li>get pandas to identify the date columns</li> <li>shift the &quot;date&quot; column by nbDays</li> <li>compare the shifted date column to the dates in the columns</li> </ol> <pre><code>from ...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How to add 91 to all the values in a column of a pandas data frame?<p>Consider my data frame as like this</p> <div class="s-table-container"> <table class="s-tabl...
<p>Simplest would be comvert to string, add <code>91</code> to the beginning and slice to last 12 digits:</p> <pre><code>df['New Phone Number'] = df['Phone Number'].astype(str).radd(&quot;91&quot;).str[-12:] </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How to create an alphanumeric grid in a certain sequence allowing double digit numbers?<p>I have a grid feature class that varies in size and shape. My test shape...
<p>After you compute <code>numeric</code>, also do:</p> <pre><code>longest_num = len(str(max(numeric))) </code></pre> <p>and change your format statement to:</p> <pre><code>'{}{:0{}}'.format(x, y, longest_num) </code></pre> <p>This ensures that when you get to double digits you get the following result:</p> <pre><code>...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: python requests and bs4 how to navigate through the children of an element<p>so this is my code</p> <pre><code>from bs4 import BeautifulSoup import requests impor...
<p>Assuming html remains consistent across entries (I only checked a few) then when next text is found under the pinned listings at the top (I assume this to be a new book) then you need to extract the book url, visit that url, then you can use ``:-soup-contains<code>to target author and book title by specific text and...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Pandas group by values in list (in series)<p>I am trying to group by items in a list in DataFrame Series. The dataset being used is the <a href="https://insights....
<p>In the target column only data frame, decompose the language name and combine it with the salary. The next step is to convert the data from horizontal format to vertical format using melt. Then we group the language names together to get the median. <a href="https://pandas.pydata.org/docs/reference/api/pandas.melt.h...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Get first Tuesday of month every year<p>I want to use sql or python to get the first Tuesday in June for the current year. </p> <p>For example:</p> <ul> <li>The...
<p>Here's the python way.</p> <pre class="lang-py prettyprint-override"><code>import datetime def get_day(year): d = datetime.datetime(year, 6, 1) offset = 1-d.weekday() #weekday = 1 means tuesday if offset &lt; 0: offset+=7 return d+datetime.timedelta(offset) </code></pre> <p>Pass in the year...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How to declare a global variable of pySerial with Python<p>Using Python I need to call the 'configSerialPort' function several times and for that I have declared ...
<p>Whenever you want to access a global variable in a function, you should declare it as global</p> <pre><code>def configSerialPort(timeout): global serialPort ... def ping(): global serialPort ... </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How do I stop the code running the remember() function every time I use speakRemember() function?<p>I have this code for a remembering system:</p> <pre><code>def ...
<p>To elaborate on my comment:</p> <pre class="lang-py prettyprint-override"><code>class Remember: def __init__(self, to_remember=None): self.to_remember = to_remember def __call__(self): self.to_remember = input('What Should I remember? ') def __str__(self): return f&quot;this is wh...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Reading a (Wireshark) LiveCapture of USB keystrokes into python on Ubuntu 20.04?<h2>Context</h2> <p>The bluetooth of my keyboard is unstable, it's a known problem...
<h2>Solution</h2> <p>The following script called <code>live_capture_keystrokes.py</code> captures the <code>Leftover Capture Data</code> which contains the signals of the keystrokes, they are parsed live and continuously by the Python code.</p> <p>I think it is important to activate usb monitoring each time you reboot ...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Updating column-entries when using groupby+apply iteratively<p>I use the groupby+apply methods on a dataframe and store the return-Values of the applied function ...
<p>This is what I found works best. I use pandas.Series.update() which updates a single column of the Dataframe:</p> <pre><code>for key, item in grouped: series = grouped.get_group(key).apply(function,axis=1) if 'a+b' in df.columns : df['a+b'].update(series) else: df['a+b'] = series </code...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Calling a certain function based on a variable<p>I am trying to call certain functions based on a certain variable. If I have lots of functions based on this vari...
<p>Create an array of the functions, index with the variable and call the function.</p> <pre><code>[function_0, function_1, function_2][variable]() </code></pre> <p>Or do it via a dictionary</p> <pre><code>dd = {0 : function_0, 1 : function_1, 2 : function_2} dd[variable]() </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: What method do you use a lot when controlling p4 command with Python?<p>What method do you use a lot when controlling p4 command with Python?</p> <ol> <li>Use p4 ...
<p>I find the simplest way to translate from command line to P4Python is the <code>p4.run()</code> command. You just pass in the command you want to run as the first argument and then add each P4 argument after that.</p> <p>For example, in the terminal:</p> <p><code>p4 changes</code></p> <p>In Python would be:</p> <p><...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Need download voice message from Telegram on Python<p>I started developing a pet project related to telegram bot. One of the points was the question, <strong>how ...
<p>In the github of the project there is an <a href="https://github.com/eternnoir/pyTelegramBotAPI/blob/master/examples/download_file_example.py" rel="nofollow noreferrer">example</a> for that:</p> <pre><code>@bot.message_handler(content_types=['voice']) def voice_processing(message): file_info = bot.get_file(mess...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Broadcasting a M*D matrix to N*D matrix in python (D is greater than 1, M>N)<p>I would like to subtract the rows of a MXD matrix from a NXD matrix (D is greater t...
<p>Method 1:</p> <pre><code>def subtract(A, B): m = A.shape[0] n = B.shape[0] C = np.empty_like(A) for i in range(m // n): C[i*n : (i+1)*n] = A[i*n : (i+1)*n] - B return C </code></pre> <p>Method 2:</p> <pre><code>def subtract(A, B): m = A.shape[0] n = B.shape[0] return A - ...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: shutil.copy2 gives "SameFileError" altho files are not at all the same - why?<pre><code> File "C:\WPy64-3810\python-3.8.1.amd64\lib\shutil.py", line 239, in copy...
<p>It's a bug related to how shutil reads a Google Drive File Stream file system.</p> <p>See here: <a href="https://bugs.python.org/issue33935" rel="nofollow noreferrer">https://bugs.python.org/issue33935</a></p>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How to get xml elements which have childs with a certain tag and attribute<p>I want to find xml elements which have certain child elements. The child elements nee...
<blockquote> <p>I want to find all country elements which have a child element neighbor with attribute name=&quot;Austria&quot;</p> </blockquote> <p>see below</p> <pre><code>import xml.etree.ElementTree as ET data = &quot;&quot;&quot;&lt;?xml version=&quot;1.0&quot;?&gt; &lt;data&gt; &lt;country name=&quot;Liechte...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Append inner 0 & 1st index to all elements in 2nd index two-dimensional List of Lists - python<p>Hello new to python here... wondering what the best way is to sol...
<p>You may need to iterate over the values, and for each iterate over the several indices you have</p> <pre><code>values = [['October 17', 'Manhattan', '10024, 10025, 10026'], ['October 17', 'Queens', '11360, 11362, 11365, 11368']] result = [[int(idx), row[0], row[1]] for row in values f...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Pandas - calculate monthly average from data with mixed frequencies<p>Suppose I have a dataset consisting of monthly, quarterly and annual average occurrences of ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.date_range.html" rel="nofollow noreferrer"><code>date_range</code></a> in list comprehension for months values, create DataFrame and aggregate <code>sum</code>:</p> <pre><code>L = [(x, v) for (s, e), v in df[0].items() for x in pd.`(s, e, ...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: In R, Error for No Boto3 to connect Athena even though Boto3 Installed<p>I am trying to connect to Athena from R. After setup 'RAthena' and connection, I got this...
<p>really sorry to hear you are having issue with the <code>RAthena</code> package. Can you let me know what version of the package you are running. </p> <p>Have you tried setting which python you are using through <code>reticulate</code>? For example:</p> <pre><code>library(DBI) # specifying python conda environmen...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How to append value to list in a row based on another column python?<p>I have a dataframe that looks like:</p> <pre><code> body label the s...
<p>One option is to use <code>apply</code> on the Series and then directly append to list:</p> <pre><code>data.loc[data.body.str.contains('red|blue'), 'label'].apply(lambda lst: lst.append('color')) data body label 0 the sky is blue [noun, color] 1 the apple is red. [noun, color] 2 Let'...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Pandas: Splitting datetime into weekday, month, hour columns<p>I have a dataset with date-time values like this,</p> <pre><code> datetime 0 201...
<p>Create a custom function:</p> <pre><code># Use {i:02} to get a number on two digits cols = [f'weeday_{i}' for i in range(1, 8)] \ + [f'hour_{i}' for i in range(1, 25)] \ + [f'month_{i}' for i in range(1, 13)] def get_dummy(dt): l = [0] * (7+24+12) l[dt.weekday()] = 1 l[dt.hour + 6] = 1 ...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Resuming debug from the middle in pycharm<p>This should be a common issue and I believe it should have been asked somewhere! But I couldn't find a wording that le...
<p><strong>Proper way</strong>: You can accomplish this with the <a href="https://docs.python.org/3/library/pdb.html" rel="nofollow noreferrer">post-mortem functionality from pdb</a>. <a href="https://paris-swc.github.io/python-testing-debugging-profiling/07-debugging-post-mortem.html" rel="nofollow noreferrer">[more i...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Split a dictionary to explictly call out 'Key' : dict.keys() and "Value' : dict.values() for JSON data going into an API<p>I'm currently working with the Campaign...
<p>Try this:</p> <pre><code>d[&quot;CustomFields&quot;] = [{&quot;key&quot;: k, &quot;value&quot;: v} for k,v in d[&quot;CustomFields&quot;][0].items()] </code></pre> <p>output:</p> <pre><code>{'EmailAddress': 'fake@gmail.com', 'Name': 'John Smith', 'CustomFields': [{'key': 'Location', 'value': 'H6GO'}, {'key': 'lo...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: What is the most efficient way to edit the values in a list of dictionaries?<p>I have multiple dictionaries inside the list, what is an efficient and possible way...
<pre><code>for item in your_list: for key in item.keys(): item[key] = round(item[key], 2) </code></pre> <p>The main iteration is list, dict lookup is <code>O(1)</code>.</p>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How to get a column name to display even when there is no data for that column?<p><strong>I want to get the names of the columns of a pandas dataframe even when I...
<p>I am not sure of your need, but if you want to have a dataframe with column names, you can initialize it with the column names :</p> <pre class="lang-py prettyprint-override"><code> df = pd.DataFrame(columns=['A', 'B', 'C']) </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How to add hex bytes in a string?<p>I have this string of hex bytes, separated by spaces:</p> <pre><code>byteString = "7E 00 0A 01 01 50 01 00 48 65 6C 6C 6F" </...
<p>Considering that you have the <em>hex</em> sequence as a <em>str</em> (<em>bytes</em>), what you need to do is:</p> <ul> <li>Split the sequence in smaller strings each representing a byte (2 <em>hex</em> digits): "<em>7E</em>", "<em>00</em>", ...</li> <li>Convert each such string to the integer value corresponding ...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: ValueError building a neural network with 2 outputs in Keras<p>I tried to build a network having a single input X (a 2-dimensions matrix of size Xa*Xb) and 2 outp...
<p>Strangely enough, the error disappears when I add a <code>Flatten()</code> layer before the network splits... It has to do with the shape of the network but I still don't get the real reason behind all of this.</p> <p>I will mark this as correct answer as it solves the problem, unless someone else posts something. P...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: how do I pass the √ untouched<p>is it possible to pass the <code>√</code> through this untouched or am i asking too much</p> <pre><code>import urllib.request path...
<p>You need to quote Unicode chars in URL. You have file which contains list of urls you need to open, so you need to split each url <em>(using <a href="https://docs.python.org/3/library/urllib.parse.html#urllib.parse.urlsplit" rel="nofollow noreferrer"><code>urllib.parse.urlsplit()</code></a>)</em>, quote <em>(with <a...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Start index (under FIeld) from 1 with pandas DataFrame<p>I would like to start the index from 1 undes the &quot;Field&quot; column</p> <pre><code>df = pd.DataFram...
<p>I found a similar question here: <a href="https://stackoverflow.com/questions/32249960/in-python-pandas-start-row-index-from-1-instead-of-zero-without-creating-additi">In Python pandas, start row index from 1 instead of zero without creating additional column</a></p> <p>For your question, it would be as simple as ad...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: SQLite3 in python update where multiple possible matches<p>Perhaps you can help me. I am selecting the oldest # rows in a database, then want to update the date c...
<p>I would just use a single query here:</p> <pre><code>sql = """UPDATE players SET update_date = datetime("now") WHERE player_tag IN (SELECT player_tag FROM players ORDER BY update_date DESC LIMIT 2)""" cursor.execute(sql) </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: if an item in a list doesn't match a column name in a data frame, produce exception statement<p>I have the following code which creates a list, takes inputs of co...
<p>Try not to print, but to raise exception And you need to fix your indentation</p> <pre class="lang-py prettyprint-override"><code>lst = [] lst = [item for item in str(input(&quot;Enter your attributes here: &quot;)).lower().split()] for i in lst: if i not in df.columns: raise ValueError('Attrib...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Pandas - merge dataframe to keep all values on left and 'insert' values from right if 'no key on left' else 'update' existing 'key' in left<p>I have two dataframe...
<p>You can do it using merge function:</p> <pre><code>df = df1.merge(df2, on='key', how='outer') df key 2021 2022 0 A 1.764052 NaN 1 B 0.400157 1.867558 2 C 0.978738 NaN 3 D 2.240893 -0.977278 4 E NaN 0.950088 5 F NaN -0.151357 </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Tweepy, a bytes-like object is required, not str. How do i fix this error?<p>error: Traceback (most recent call last): File &quot;C:\Users\zakar\PycharmProjects\T...
<p>The problem is because you are encoding the text , and then replacing.</p> <p>here</p> <pre><code>c=tweet.text.encode('utf8') c=c.replace(&quot;im &quot;,&quot;&quot;) </code></pre> <p>encode() will return bytes not a string. So in replace also you need to use the bytes. Like</p> <pre><code>c=tweet.text.encode('utf8...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Remove python, can I still use the the virtual Environment<p>I created a virtual environment, for example on my computer, python3.9 -m venv myenv if I uninstall p...
<p>no you wont be able to run python applications anymore.</p> <p>refer <a href="https://docs.python.org/3/library/venv.html" rel="nofollow noreferrer">https://docs.python.org/3/library/venv.html</a> venv — Creation of virtual environments¶ New in version 3.3.</p> <p>Source code: Lib/venv/</p> <p>The venv module provi...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How to make python read input as a float?<p>I need to take an input in the following form "score/max" (Example 93/100) and store it as a float variable. The probl...
<p><strong>Note:</strong></p> <h2><code>input()</code></h2> <blockquote> <p>reads a line from input, converts it to a string (stripping a trailing newline), and returns that.</p> </blockquote> <p>You may want to try the following code,</p> <pre><code>string = input("Input the first test score in the form score/...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Using one column values as index to list type values in another in pandas<p>We have data representing temperature forecast for every 3 hours period from the momen...
<h3>Loop solution</h3> <pre><code>df['T_by_the_shift_start'] = [a[b - 1] for a, b in df.to_numpy()] </code></pre> <h3>Non-loop solution</h3> <p>** lists should have same length across all rows</p> <p>** This solution will perform around 2x better only on large data sets &gt;= 500K</p> <pre><code>df['T_by_the_shift_star...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Image is not updating in Django<p>Please help me. I am trying to update the profile in which username and email are updated but the image dose not. My code is.......
<p>I believe your issue lies in views.py.</p> <p>Firstly, you are checking to see if the method for retrieving the view is POST. If it is not, you are initializing a form with the POST data that is not present. I have simplified that for you below.</p> <p>Secondly, you are not passing the POST information to the second...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: get chained queryset ajax django<p>I want to get a queryset through ajax request and use it in the same way I can do with django queryset in template.</p> <p>I ha...
<p>I solved it by using Django Rest Framework. Here's how.</p> <p>Suppose I have the following models</p> <pre><code>class Employee(models.Model): number = models.CharField('사원번호', max_length=30, unique=True) dept = models.ForeignKey( 'config.Department', on_delete=models.SET_NULL, ...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How to stop tkinter canvas widget / after method from skipping elements in a list?<p>I'm trying to create a line that updates every second. This update needs to s...
<p>I ended up having to move the while loop outside the function and adding root.update_idletasks() and root.update() instead of having root.mainloop(). From <a href="https://stackoverflow.com/questions/29158220/tkinter-understanding-mainloop">this post</a> I learned that your program will basically stop at mainloop wh...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Pandas: rolling difference between rows based on alternating value changes in the other column<p>I have a dataframe:</p> <pre class="lang-python prettyprint-overr...
<p>First, we build an intermediate DataFrame that have nonzero grades. Since 1s and -1s always alternate, it suffices to analyze the difference between consecutive <code>grade</code> values.</p> <p>Again, since 1s and -1s alternate, the difference between consecutive <code>scores</code> can be either -2 or 2, so depend...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Is it possible to programmatically check for a new connection using PySerial?<p>I found <a href="https://stackoverflow.com/questions/21050671/how-to-check-if-devi...
<p>I suggest having a delay to allow time for the device to respond.</p> <pre class="lang-py prettyprint-override"><code>import time def serial_device_connected(serial_device: &quot;serial.Serial&quot;) -&gt; bool: try: serial_device.write(b&quot;\r&quot;) time.sleep(0.01) return bool(seria...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How to jump to the next line when defining a function in Python?<p>I am using a Mac terminal to learn Python basics at the moment and I can't figure out how to wr...
<p>Indentation indicates where blocks begin and end. Everything inside a function definition is indented:</p> <pre><code>&gt;&gt;&gt; def f(): ... a = 10 ... print(a) ... &gt;&gt;&gt; f() 10 </code></pre> <p>The first line that is <em>not</em> indented indicates the function is over.</p>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How to run a simulation of CAN messages on Python<p>I have am currently learning how to use libraries in python and I have a project in mind, which requires me to...
<p>I'm unfamiliar with <code>python-can</code> but if all you want to do is import the module, here's a snippet that imports the library and sends out a simple message (receiving them is a whole other matter). You might want to keep exploring the docs for ways to capture messages and do stuff with them.</p> <pre class...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Gevent monkey patching - OverflowError<p>I tried to run my Flask project with gevent on Python3.7 on Raspberry Pi with gevent.monkey.patch_all() on the first line...
<p>The problem was that I was running 32bit instead of 64bit Python3 on RPi.</p>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: searching for numbers greater than 60 in a list<p>i cant seem to get the second for loop to work correctly, nor the third. ive tried removing them and switching a...
<p>At the second for loop, you can get each score by specifying each score on the list with <strong>scores[z]</strong> on the condition. not only scores</p> <pre><code>if any(**scores[z]** &gt; passing for y in len(scores)): </code></pre> <p>all code :</p> <pre><code>scores = [] passed = 0 passing = 60 tests = int(inp...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Lineplot - plot a single legend for uneven number of subplots<p>I'm working on the following graph where I'd like to plot is single legend that applies to all, es...
<p>I found some sort of option based on this thread <a href="https://stackoverflow.com/questions/39500265/how-to-manually-create-a-legend">How to manually create a legend</a></p> <pre><code>legend_elements = [plt.Line2D([0], [0], color='skyblue', lw=2.5, label='ClientAB=0'), plt.Line2D([0], [0], colo...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Is there a way to solve import issues with __init__.py?<p>I have a package with this structure</p> <pre><code>framework/ __init__.py file0.py file1.py...
<p>What you want for your <code>__init__.py</code> is <code>from .file0 import file0</code>, or whatever content from <code>file0.py</code> you want to import.</p> <p>See <a href="https://docs.python.org/3/reference/import.html#package-relative-imports" rel="nofollow noreferrer">Package relative imports</a> in Python d...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Sympy: AttributeError: Multiply polynomial by complex constant<p>I'm trying to multiply a Sympy polynomial by the complex coefficient &quot;i&quot;. However I am ...
<p>You can try the domain &quot;EX&quot;:</p> <pre><code>&gt;&gt;&gt; p = Poly(1.0*x, x, domain='EX') &gt;&gt;&gt; p*I Poly(1.0*I*x, x, domain='EX') </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Fieldsets don't do anything in admin django<p>I'm learning Django and found that we can use fieldsets to customise the way admin creation form looks like. Here is...
<p>The UserAdmin separates the <code>add</code> action (user creation) form other actions. This is because it only wants to deal with username and password and then the rest of the fields.</p> <p>So the UserAdmin does some special work and you have both <code>fieldsets</code> and <code>add_fieldsets</code>.</p> <p>Be...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Error while importing Tensorflow. TypeError: expected bytes, descriptor found<p>I installed tensorflow only for CPU in windows 10 with</p> <pre><code>pip3 install...
<p>I installed probuf with</p> <pre><code>pip install protobuf-py3 </code></pre> <p>But another problem came up</p> <pre><code>import tensorflow as tf Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; File &quot;C:\Users\Eloy\anaconda3\lib\site-packages\tensorflow\__init__...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Pandas forward fill with scalar multiple of last value<p>Suppose I have the following DataFrame</p> <pre><code>import pandas as pd import numpy as np dict1 = {'...
<p>IIUC, try:</p> <pre><code>df1.fillna(df1.ffill().mul(.5)) </code></pre> <p>Output:</p> <pre><code> A B C 0 100.0 0.0 100.0 1 200.0 1.0 200.0 2 100.0 0.5 100.0 3 300.0 1.0 300.0 4 500.0 10.0 500.0 5 250.0 5.0 250.0 6 250.0 5.0 250.0 7 50.0 5.0 200.0 </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Repeat pattern using python regex<p>Well, I'm cleaning a dataset, using Pandas. I have a column called &quot;Country&quot;, where different rows could have number...
<p>In this situation, I will clean the data step by step.</p> <pre><code>df_str = ''' Country Australia1 Perú (country) 3Costa Rica United States of America ''' df = pd.read_csv(io.StringIO(df_str.strip()), sep='\n') # handle the data (df['Country'] .str.replace('\d+', '', regex=True) # remove number .str.split('\(...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Allocate an integer randomly across k bins<p>I'm looking for an efficient Python function that randomly allocates an integer across <code>k</code> bins. That is, ...
<p>Adapting Michael Szczesny's <a href="https://stackoverflow.com/questions/71888628/allocate-an-integer-randomly-across-k-bins?noredirect=1#comment127034648_71888743">comment</a> based on numpy's new paradigm:</p> <pre class="lang-py prettyprint-override"><code>def allocate(n, k): return np.random.default_rng().mu...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Python DataFrame Merging<p>I need to merge two dataframes. I create several of the below dataframe from reading files.</p> <p>What i need to do is pull the 'Dept...
<p>Try this:</p> <pre><code>depthDF = depthDF.merge(sigData[['Depth','Time']], on='Time', sort='True', how='right') </code></pre> <p>Same do for velocityDF.</p> <p>Hope it helps and will resolve your error..</p>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: List of max values in a sequence?<p>this is my first question in stackoverflow, I'm looking for this solution for days and it is very frustrating.</p> <p>Imagine...
<p>You need to clear your <code>lista_max_seq</code> at the beginning of each iteration:</p> <pre class="lang-py prettyprint-override"><code>while True: ... lista_max_seq = [] </code></pre> <p>Otherwise after the first iteration, your programm never passes <code>len(lista_max_seq) &lt; len(dt_seq)</code> chec...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Tensorflow: What's the best practice to get a section of a manual from a question?<p>I would like to use Tensorflow to create a smart faq. I've seen how to manage...
<p>An idea could be building <a href="https://en.wikipedia.org/wiki/Word_embedding" rel="nofollow noreferrer">embeddings</a> of your text using <a href="https://arxiv.org/abs/1810.04805" rel="nofollow noreferrer">Bert</a> or other pretrained models (take a look to <a href="https://github.com/huggingface/transformers" r...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Pandas dataframe change values in a column based on conditions<p>I have a large Dataframe below:</p> <p>The data used as the example here 'education_val.csv' can ...
<p>You can do it using the <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/categorical.html#categorical-data" rel="nofollow noreferrer">categorical data</a> like this:</p> <pre><code>df = pd.read_csv('https://raw.githubusercontent.com/ENLK/Py-Projects-/master/education_val.csv') eddtype = pd.Categoric...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Module installed but "ModuleNotFoundError: No module named <module_name>" while running gunicorn<p>I am trying to deploy this website using nginx. The site is con...
<p>You can see from the error message that the system installed gunicorn try to use the global Python environment in <code>/usr/local/lib/python3.8/dist-packages/</code>, not the project specific virtual environment in <code>/tmp/tmc_site/venv</code> directory.</p> <p>Install gunicorn in the <code>venv</code> virtual e...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How to transfer variable from python file to python flask<p>I want to transfer label_count and card_m to my main flask python file. How do I do that? I already tr...
<p>Ok based on you comments i think i can help you out now. So two things you should do to make this as clean as possible and to avoid bugs later on.</p> <p>Right now your code is in the global scope. You should avoid doing this at cost unless there is literally no other option. So first thing you should do is create a...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How to turn a list of lists into columns of a pandas dataframe?<p>I would like to ask how I can unnest a list of list and turn it into different columns of a data...
<p>You can try using <code>df.explode</code> and <code>df.apply</code>:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.DataFrame(data= {'Generation': 0, 'Route_set':[[[20., 19., 47., 56.], [21., 34., 78., 34.]]]}) df['route1']=df['Route_set'].apply(lambda x: x[0]) df['route2']=df['Rout...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Group and sum by week<p>I have a dataframe where the columns are by day in this format:</p> <pre><code>a b c 01/01/2020 01/02/2020 01/03/2020 ... 100...
<p>You can do:</p> <pre><code># move `a`, `b`, `c` out of columns df = df.set_index(['a','b','c']) # convert columns to datetime df.columns = pd.to_datetime(df.columns) # groupby sum: (df.groupby(df.columns.week, axis=1) .sum() .add_prefix('week_') .reset_index() ) </code></pre> <p>Output:</p> <pre><code...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Subtract column in DataFrame1 from matching indices in long-form DataFrame2<p>I have two dataframes, one with reference data and one with &quot;experimental&quot;...
<p>I would recommend that you merge the experimental data frame with the reference data frame on the Reaction Id.</p> <pre><code>import pandas as pd import numpy as np mergedData= pd.merge(ref,exp_sub, how='left' ,on='Reaction', suffixes=('_ref', '_exp'),indicator ='Exists') </code></pre> <p>since you have the colum...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How to ignore certain scripts while testing flask app using pytest in gitlab CI/CD pipeline?<p>I have a <code>flask-restx</code> folder with the following structu...
<p>As I understand it, <em>coverage</em> is about reporting how much of your codebase is tested, not which tests to run. What you're doing is excluding things from a report, not stopping the data for the report being created.</p> <p>What you should do is skip tests if you know they're going to fail (due to external con...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Score function in rock paper scissors python issue and others<p>I am new to programming &amp; trying to create a best of 5 RPS game for my class but running into ...
<p>Check the condition of your <code>while</code> loop:</p> <p><code>while YS or CS &lt;= 3:</code></p> <p>means that the loop is running as long as <code>YS != 0</code> or <code>CS &lt;= 3</code> and this is probably not what you wanted.</p> <p>You probably wanted the loop to run until one of the variables exceeds ...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Efficient HDF5 / PyTables Layout for saving and operating on large tensors<p>I am trying to figure out the best data layout for my use case (a research project). ...
<p>For anyone coming across this question, let me give you the result.</p> <p>The above works as intended using pyTables. It can be made reasonably fast. However, the logic rapidly produces files of humorously gigantic proportions, so I can only recommend to find a different way. In particular, disk space turned out t...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How to pass to a function that takes two arguments an element from one list together with each element of another list?<p>I am new to Python and I need help with ...
<p>You'd need a nested <code>for</code> loop:</p> <pre><code>a = range(1, 50, 10) b = [2, 4, 5, 8, 12, 34] for aval in a: for bval in b: print(aval, bval) # or any other function call </code></pre> <p>This just goes through all values in <code>b</code> for each value in <code>a</code>. (Note that you don...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Stacked barplot in seaborn using numeric data as hue<p>I have a simple pandas dataframe of 3 columns (month, amount, category) where each row represent an expense...
<p>Your initial method is complicated because you have unnecessary steps. You <code>groupby</code> and <code>pivot</code>, but the same aggregation and reshaping can be done at once with <code>pivot_table</code>. From your initial DataFrame:</p> <pre><code>df_pivot = pd.pivot_table(df, index='Month', columns='Category'...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Breakng the hash<p>I have to break 4 hash codes and find their number . but my code is not working</p> <p>these are the hash codes (in a csv file) :</p> <pre><cod...
<p>You're trying to read from a closed file, which is impossible.</p> <p>I don't know what your code is supposed to do, but here are the unlogical parts:</p> <p>This opens the file to parse it as CSV</p> <pre><code>with open('passwords.csv', newline='') as theFile: reader = csv.reader(theFile) </code></pre> <p>Then...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Scrape URL loop with BeautifulSoup<p>I want to scrap information on different pages of the same site, societe.com and I have several questions.</p> <p>first of al...
<p>To get data about the companies you can use next example:</p> <pre class="lang-py prettyprint-override"><code>import requests import pandas as pd from bs4 import BeautifulSoup urls = [ &quot;https://www.societe.com/societe/decathlon-france-500569405.html&quot;, &quot;https://www.societe.com/societe/go-spor...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Saving Tiff with specific Tiff Tags using PIL<p>I am trying to save a TIFF image using PIL with custom tags.</p> <pre><code>import numpy as np import PIL numrows=...
<p>I figured it out. You need to format the TIFF tags as follows:</p> <pre><code>custtifftags={262:(1,), 259:(0,), 258:(32,),\ 277:(1,), 339:(3,),257:(10,),\ 256:(10,), 284:(1,), 296:(2,)} </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Divide multiple columns by a fix number in pandas<p>How can I divide multiple columns by a fixed number?</p> <pre><code> A B C D 0 1 100 2000 ...
<p>You can use broadcasting:</p> <pre><code>df[['B','C']] /= 1000 </code></pre> <p>Output:</p> <pre><code> A B C D 0 1 0.1 2.0 10 1 2 0.2 3.0 0 2 3 0.3 4.0 20 3 4 0.4 5.0 40 4 5 0.5 4.0 24 5 6 0.6 2.0 23 </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: CIFAR-10 python architicture<p>I'm following this tutorial <a href="https://machinelearningmastery.com/how-to-develop-a-cnn-from-scratch-for-cifar-10-photo-classi...
<blockquote> <p>why is he using <code>kernel_initializer='he_uniform'</code>?</p> </blockquote> <p>The weights in a layer of a neural network are initialized randomly. How though? Which distribution should they follow? <code>he_uniform</code> is a strategy for initializing the weights of that layer.</p> <blockquote> <p...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How to Block Python ThreadPoolExecutor<p>I have a threadpool that i'd like to limit not only the max number of workers but the max number of jobs that can be subm...
<p>Looking at the <a href="https://github.com/python/cpython/blob/3.10/Lib/concurrent/futures/thread.py#L118" rel="nofollow noreferrer">implementation</a>, there seems to be a relatively non-intrusive way to define one yourself:</p> <pre><code>class BlockingThreadPoolExecutor(ThreadPoolExecutor): def __init__(self,...
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: as_completed identifying coroutie objects<p>I'm using asyncio to await set of coroutines in following way:</p> <pre><code># let's assume we have fn defined and th...
<blockquote> <p>Question is how can I know which coroutine failed and for which argument?</p> </blockquote> <p>You can't with the current <code>as_completed</code>. Once <a href="https://bugs.python.org/issue33533" rel="nofollow noreferrer">this PR</a> is merged, it will be possible by attaching the information to the ...