content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
How to compute a weighted loop?
This is a portion of my data frame:
df = pd.DataFrame({
'IBI_msec': [652, 618, 654],
'rate': [92.02, 97.09, 91.74]
})
I need to compute a loop that enables me to compute this logic:
if 652 > 500, then bin = 92.02, and the remaining (652 - 500) goes to the next bin;
because... | How to compute a weighted loop? | This is a portion of my data frame:
df = pd.DataFrame({
'IBI_msec': [652, 618, 654],
'rate': [92.02, 97.09, 91.74]
})
I need to compute a loop that enables me to compute this logic:
if 652 > 500, then bin = 92.02, and the remaining (652 - 500) goes to the next bin;
because the bin2 contains the 152, remaining... | [
"This does what you want: that said, there will be a problem if (when) remainder goes over 500, so you should complete your rules to deal with that case.\nimport pandas as pd\n\ndf = pd.DataFrame({\n 'IBI_msec': [652, 618, 654],\n 'rate': [92.02, 97.09, 91.74]\n})\n\nbins = []\nremainder = 0\nfor i in range(l... | [
2
] | [] | [] | [
"loops",
"python",
"weighted"
] | stackoverflow_0074408628_loops_python_weighted.txt |
Q:
Is there a way to make a while loop repeat itself?
I am trying to make this guessing game using rudimentary python. It looks like this:
secret_number = 9
guess_count = 0
guess_limit = 3
while guess_count < 3:
guess_count += 1
guess = int(input('Guess: '))
if guess == secret_number:
print('You ... | Is there a way to make a while loop repeat itself? | I am trying to make this guessing game using rudimentary python. It looks like this:
secret_number = 9
guess_count = 0
guess_limit = 3
while guess_count < 3:
guess_count += 1
guess = int(input('Guess: '))
if guess == secret_number:
print('You got it!')
I want to set it up so it asks the user if th... | [
"You could either place the whole thing in a while loop or create a function such as below and call the function if your repeat condition is met. This has the added bonus of your being able to call this part of the game from other parts of your code.\ndef game():\n secret_number = 9\n guess_count = 0\n gue... | [
1,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0070840557_python.txt |
Q:
Use joblib to check whether an integer is a prime number or not. If it is, calculate its square; otherwise, append None to the returned value
import joblib
def is_prime(n):
for i in range(2, n):
if n % i == 0:
return False
return True
def square_if_prime(n):
if is_prime(n):
... | Use joblib to check whether an integer is a prime number or not. If it is, calculate its square; otherwise, append None to the returned value | import joblib
def is_prime(n):
for i in range(2, n):
if n % i == 0:
return False
return True
def square_if_prime(n):
if is_prime(n):
return n * n
return None
primes = joblib.Parallel(n_jobs=4)(joblib.delayed(square_if_prime)(n) for n in range(2, 100000))
primes = [prime fo... | [
"try this:\ndef is_prime(n):\n for i in range(2,int(n**0.5)+1):\n if n%i==0:\n return False\n return True\n\n"
] | [
0
] | [] | [] | [
"joblib",
"python"
] | stackoverflow_0074408921_joblib_python.txt |
Q:
How would I add another shape to the code for pygame so that it moves like one of the other rectangles?
import pygame, sys, time
from pygame.locals import *
# Set up pygame.
pygame.init()
# Set up the window.
WINDOWWIDTH = 400
WINDOWHEIGHT = 400
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT)... | How would I add another shape to the code for pygame so that it moves like one of the other rectangles? | import pygame, sys, time
from pygame.locals import *
# Set up pygame.
pygame.init()
# Set up the window.
WINDOWWIDTH = 400
WINDOWHEIGHT = 400
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT), 0, 32)
pygame.display.set_caption('Animation')
# Set up direction variables.
DOWNLEFT = 'downleft'
DOWNRIG... | [
"See pygame.draw.circle. A circle is defined by its center and the radius. e.g.:\nb2 = {'rect':pygame.Rect(200, 200, 20, 20), 'color':GREEN, 'dir':UPLEFT}\n\npygame.drw.circle(windowSurface, b2['color'], b2['rect'].center, b2['rect'].width//2)\n\nHowever an ellipse is defined by the bounding rectangle (pygame.draw.... | [
0
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0074408902_pygame_python.txt |
Q:
Is there a way to use a lambda/reduce function to find the highest value in my elements?
I am given a bunch of tuples inside a 2d-list. Given (x,y,z), find the tuple with the highest y*z and return the corresponding x.
Example:
[[1,...("9744", 9, 44.95)],
[2, ... ("9744", 9, 44.95)]...]
Multiply 9 and 44.95:
[[... | Is there a way to use a lambda/reduce function to find the highest value in my elements? | I am given a bunch of tuples inside a 2d-list. Given (x,y,z), find the tuple with the highest y*z and return the corresponding x.
Example:
[[1,...("9744", 9, 44.95)],
[2, ... ("9744", 9, 44.95)]...]
Multiply 9 and 44.95:
[[1,...("9744", 9, 44.95)],
[2, ... ("9744", 9, 44.95)]...]
[[1,...("9744", 809.1)],
[2, ... ... | [
"You can just take max and then list the result: list(max(<your code>))\ncleaning up a bit, that would be:\nlist(max(map(lambda p: (max(map(lambda t: (t[0], 2*t[1]*t[2]), p[1:]))), orders)))\n\nor using generator comprehension:\nlist(max( max( (k, 2 * v*w) for k, v, w in tps ) for _, *tps in orders ))\n\n"
] | [
0
] | [] | [] | [
"lambda",
"python"
] | stackoverflow_0074407124_lambda_python.txt |
Q:
How to parse user_defined_macro in regular function or PythonOperator in Airflow
We use managed Airflow inside a GCP project.
When I used BigQueryInsertJobOperator to execute queries in a query file, it used to automatically replace user_defined_macros in those files with the set value.
from airflow import DAG
fro... | How to parse user_defined_macro in regular function or PythonOperator in Airflow | We use managed Airflow inside a GCP project.
When I used BigQueryInsertJobOperator to execute queries in a query file, it used to automatically replace user_defined_macros in those files with the set value.
from airflow import DAG
from datetime import datetime
from airflow.providers.google.cloud.operators.bigquery impo... | [
"In Airflow operators, only the arguments defined in template_fields attribute are rendered by jinja, and in the PythonOperator (the operator used in your case), jinja renders op_args and op_kwargs arguments, and if your version is 2.4.1+, the argument templates_dict is rendered too. (PR which fixed the problem)\nF... | [
1,
1
] | [] | [] | [
"airflow",
"google_bigquery",
"google_cloud_platform",
"python"
] | stackoverflow_0074406449_airflow_google_bigquery_google_cloud_platform_python.txt |
Q:
I think I screwed up my python installation
I'm sort of a beginner to python right now. I work in VScode. After I downloaded python 3.11, I was experiencing issues in VScode (importing and installing libraries wasn't working). I realized I had multiple python versions on my disk, so I decided to do a purge to see ... | I think I screwed up my python installation | I'm sort of a beginner to python right now. I work in VScode. After I downloaded python 3.11, I was experiencing issues in VScode (importing and installing libraries wasn't working). I realized I had multiple python versions on my disk, so I decided to do a purge to see if the issue would fix itself.
-What I Did-
I loo... | [
"pip install pygame==2.1.3.dev8\nCurrent version is not compatible with python > 3.7 so you have to use the dev builds.\n",
"What command did you use to install pygame?\nTwo suggestions:\n1. use the following command\npip install setuptools==58.2.0\n\n2. Use a virtual environment\n\nCreate a virtual environment\n... | [
0,
0,
0
] | [] | [] | [
"environment",
"installation",
"pip",
"python",
"visual_studio_code"
] | stackoverflow_0074210793_environment_installation_pip_python_visual_studio_code.txt |
Q:
I need a sympy function to turn into a symbol
So i'm working on automating FEM for ODE and i managed to create the matrix with all the unknown values that i need so i can put them on a "solve" function from sympy.
But i have one small issue: all the unknown values are a function "F".
import numpy as np
import symp... | I need a sympy function to turn into a symbol | So i'm working on automating FEM for ODE and i managed to create the matrix with all the unknown values that i need so i can put them on a "solve" function from sympy.
But i have one small issue: all the unknown values are a function "F".
import numpy as np
import sympy as sp
x = sp.Symbol('x')
xa = sp.Symbol('xa')
xb... | [
"Your xa and xb are the element boundaries (which you identify in your for loop). There is no need to handle them symbolically. Your quadratic function has a constant 2nd derivative (of -10) so when you add 10 to it, the result is 0 and the integration of 0 gives 0, too. I suggest doing the calculation for h=5 by h... | [
0
] | [] | [] | [
"python",
"sympy"
] | stackoverflow_0074394535_python_sympy.txt |
Q:
Why is not my discord code working? When i run the progam, it gives an error saying: TypeError: 'module' object is not callable
Here is my code:
import discord
from discord.ext import commands
bot = discord.bot(command_prefix="!", help_command=None)
@bot.event
async def on_ready():
print(f"Bot logged in as {... | Why is not my discord code working? When i run the progam, it gives an error saying: TypeError: 'module' object is not callable | Here is my code:
import discord
from discord.ext import commands
bot = discord.bot(command_prefix="!", help_command=None)
@bot.event
async def on_ready():
print(f"Bot logged in as {bot.user}")
bot.run("TOKEN")
The error i am getting:
File "c:\Users\user\OneDrive\Desktop\coding\d... | [
"yeah, you need to specify intents\nhere is the code to it works\nimport discord\nfrom discord.ext import commands\n\nintents = discord.Intents.all()\nbot = commands.Bot(command_prefix=\"!\", help_command=None, intents = intents)\n\n\n@bot.event\nasync def on_ready():\n print(f\"Bot logged in as {bot.user}\")\n@... | [
1,
0
] | [] | [] | [
"discord",
"discord.py",
"python",
"python_3.11"
] | stackoverflow_0074407038_discord_discord.py_python_python_3.11.txt |
Q:
Calculating column value based on previous row and column using lambda function
I have this pandas dataframe that looks like this:
index up_walk down_walk up_avg down_avg
0 0.000000 17.827148 0.36642 9.06815
1 1.550781 0.000000 NaN NaN
2 0.957031 0.000000 NaN NaN
... | Calculating column value based on previous row and column using lambda function | I have this pandas dataframe that looks like this:
index up_walk down_walk up_avg down_avg
0 0.000000 17.827148 0.36642 9.06815
1 1.550781 0.000000 NaN NaN
2 0.957031 0.000000 NaN NaN
3 0.000000 2.878906 NaN NaN
I wanted to calculate the missing valu... | [
"you can use np.roll instead of shift. Also, if you are using apply, you must specify an axis:\n#keep going until there is no nan value left\nstatus=True\nwhile status:\n df['up_avg'] = np.where((np.isnan(df.up_avg)==True), np.roll(df.up_avg,1) * 12 +df.up_walk ,df.up_avg)\n if df['up_avg'].isnull().sum() == ... | [
1,
0
] | [] | [] | [
"dataframe",
"lambda",
"pandas",
"python"
] | stackoverflow_0074408119_dataframe_lambda_pandas_python.txt |
Q:
Partition pandas dataframe into equal parts based on common ID
Given an id in a pandas dataframe, how can I create a new column that has an additional id that maxes out at a count of 5 for each ID. almost like "batches" of rows
df = pd.DataFrame([[1, 1],
[2, 1],
[3, 1],
... | Partition pandas dataframe into equal parts based on common ID | Given an id in a pandas dataframe, how can I create a new column that has an additional id that maxes out at a count of 5 for each ID. almost like "batches" of rows
df = pd.DataFrame([[1, 1],
[2, 1],
[3, 1],
[4, 1],
[5, 1],
... | [
"I would start by getting all the points where you know the transition will happen:\ndf[1].diff() \\ # Show where column 1 differs from the previous row\n .astype(bool) # Make it a boolean (true/false)\n\nWe can use this selection on the index of the dataframe to get the indices of rows that change:\ndf.ind... | [
0
] | [] | [] | [
"dataframe",
"group_by",
"pandas",
"python"
] | stackoverflow_0074408804_dataframe_group_by_pandas_python.txt |
Q:
Finding the numbers of length between(8 to 16) in the Data frame of URL’s in python
I am trying to find the numbers in the Data frame of URL’s which are 8 to 16 digits in length. There are 1000’s of URL's and there is no pattern. The number sometimes appears in between sometimes at the end. The only pattern I see ... | Finding the numbers of length between(8 to 16) in the Data frame of URL’s in python | I am trying to find the numbers in the Data frame of URL’s which are 8 to 16 digits in length. There are 1000’s of URL's and there is no pattern. The number sometimes appears in between sometimes at the end. The only pattern I see is the there is always an "=" before the number. I want to save the the extracted results... | [
"import re\n\nPATTERN = re.compile(r\"\\w*=(\\d{8,16})\")\n\ndef find_numbers(url):\n return PATTERN.findall(url)\n\n# update your dataframe \ndf[\"values\"] = df[\"URL\"].map(lambda x: find_numbers(x))\n\n"
] | [
0
] | [] | [] | [
"numbers",
"partition",
"python",
"url"
] | stackoverflow_0074408828_numbers_partition_python_url.txt |
Q:
I'm new to coding and i was trying to make a discord bot but im getting error
(Error is bellow)
I'm bad at coding at i was trying to make a discord bot but i keep getting this error.
anyone know how to fix this?
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix="!")
@bot.event
asy... | I'm new to coding and i was trying to make a discord bot but im getting error | (Error is bellow)
I'm bad at coding at i was trying to make a discord bot but i keep getting this error.
anyone know how to fix this?
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix="!")
@bot.event
async def on_connect():
print ("Bot is online")
bot.command()
async def test(ctx):
... | [
"There is a well made video on how to set up a chat bot\nhttps://youtu.be/1yLfjMtsV9s\n"
] | [
0
] | [] | [] | [
"bots",
"discord",
"python"
] | stackoverflow_0074408714_bots_discord_python.txt |
Q:
Scraping based on class name
From here I would like to extract the address "Calle Tiera Del Soconusco No. 252".
<td class="type-address"><span>Calle Tiera Del Soconusco No. 252 </span></td>
I have tried the following codes but I fail to get the necessary information.
infor = response2.xpath("td[2]/td[contains(@cl... | Scraping based on class name | From here I would like to extract the address "Calle Tiera Del Soconusco No. 252".
<td class="type-address"><span>Calle Tiera Del Soconusco No. 252 </span></td>
I have tried the following codes but I fail to get the necessary information.
infor = response2.xpath("td[2]/td[contains(@class,'type-address')]").get()
infor... | [
"So the parent element is a <td> with a class of \"type-address\", then the parent element has a child <span> element that actually contains the text.\nSo try:\ninfo = response.xpath('//td[@class=\"type-address\"]/span/text()').get()\n\n# or if there is more than 1\n\ninfo = response.xpath('//td[@class=\"type-addre... | [
0
] | [] | [] | [
"python",
"scrapy",
"screen_scraping"
] | stackoverflow_0074404786_python_scrapy_screen_scraping.txt |
Q:
How to save string and float together in the same np.savetxt?
I have a list, in python, which is given by:
inputs = ["eos", 5, 60, 2000, 3]
where only eos is a string, the rest are numbers (int). I tried to save this list as follows:
np.savetxt(path + '/inputs.txt', inputs, delimiter=" ", header = 'Eos Pressure R... | How to save string and float together in the same np.savetxt? | I have a list, in python, which is given by:
inputs = ["eos", 5, 60, 2000, 3]
where only eos is a string, the rest are numbers (int). I tried to save this list as follows:
np.savetxt(path + '/inputs.txt', inputs, delimiter=" ", header = 'Eos Pressure Radius Nt Sigma')
but it gave an error:
TypeError: Mismatch between ... | [
"The problem is that numpy arrays have a single data type. You mix strings and numbers, and thus the error. In addition, You should make this a 2D array so that you are writing a single row with multiple columns. To get it to work you could\nimport numpy as np\n\ninputs = [\"one\", 2.0, 3]\nnp.savetxt(\"test.txt\",... | [
0
] | [] | [] | [
"arrays",
"database",
"numpy",
"python"
] | stackoverflow_0074408736_arrays_database_numpy_python.txt |
Q:
Cloud Resume Challenge - ' Build Failed / Error: PythonPipBuilder:ResolveDependencies - pip executable not found in your python environment'
I would appreciate any guidance here. I have been stuck on this issue for the last week, trying to find out how to resolve this error.
I am trying to run 'SAM Build' but gett... | Cloud Resume Challenge - ' Build Failed / Error: PythonPipBuilder:ResolveDependencies - pip executable not found in your python environment' | I would appreciate any guidance here. I have been stuck on this issue for the last week, trying to find out how to resolve this error.
I am trying to run 'SAM Build' but getting an error saying I don't have the pip executable folder in my python environment. I've been trying to figure this out on Stack, but no luck.
I'... | [
"You're missing pip to resolve dependencies.\nTry to add pip with:\nsudo apt-get install python3-pip\n\n"
] | [
0
] | [] | [] | [
"amazon_web_services",
"aws_sam_cli",
"docker",
"linux",
"python"
] | stackoverflow_0074408775_amazon_web_services_aws_sam_cli_docker_linux_python.txt |
Q:
How do I make join see my objects as strings?
I am trying to build a program in an object oriented fashion. My Phrase object can contain one or more Noun objects. When you cast the Phrase to string, join the nouns list together like this
@property
def nouns_text(self) -> str:
return ' '.join(self.nouns)
But t... | How do I make join see my objects as strings? | I am trying to build a program in an object oriented fashion. My Phrase object can contain one or more Noun objects. When you cast the Phrase to string, join the nouns list together like this
@property
def nouns_text(self) -> str:
return ' '.join(self.nouns)
But this raises the error
Traceback (most recent call la... | [
"' '.join([str(x) for x in self.nouns])\n\nThis is good, and it's what you should do. There's one slight optimization you can do. Rather than constructing an intermediate list, you can use a generator expression.\n' '.join(str(x) for x in self.nouns)\n\nOr, if you prefer map calls,\n' '.join(map(str, self.nouns))\n... | [
0
] | [] | [] | [
"python",
"string",
"text"
] | stackoverflow_0074409141_python_string_text.txt |
Q:
pandas split values in column
I'm new to pandas (version 1.1.5) and have tried str.split() and str.extract() to split column POS of numerical values with no success. My dataframe is about 3000 lines and is structured like this (note _ and - delimiters in subset):
df.head()
SAMPLE CHROM POS REF ALT
1 ... | pandas split values in column | I'm new to pandas (version 1.1.5) and have tried str.split() and str.extract() to split column POS of numerical values with no success. My dataframe is about 3000 lines and is structured like this (note _ and - delimiters in subset):
df.head()
SAMPLE CHROM POS REF ALT
1 Sample1 7 105121514 C... | [
"This is not the most popular solution, but you can try.\ndf.POS = df.POS.str.replace(\"-\", \" \")\ndf.POS = df.POS.str.replace(\"_\", \" \")\ndf.POS = df.POS.str.split()\ndf.POS = [x[0] for x in df.POS]\n\n",
"A possible solution, based on the idea of replacing all characters after _ or - (inclusive) with the e... | [
1,
0,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074409033_pandas_python.txt |
Q:
Why am I getting "asynchronous comprehension outside of an asynchronous function"?
I'm using Python 3.7.4 and this block of code (MWE):
import asyncio
async def foo(x):
await asyncio.sleep(1)
return [i for i in range(10)]
async def big_foo():
dict_of_lists = {'A': [i for i in range(10)], 'B': [i for ... | Why am I getting "asynchronous comprehension outside of an asynchronous function"? | I'm using Python 3.7.4 and this block of code (MWE):
import asyncio
async def foo(x):
await asyncio.sleep(1)
return [i for i in range(10)]
async def big_foo():
dict_of_lists = {'A': [i for i in range(10)], 'B': [i for i in range(10)]}
return {
key: [
item
for list_ite... | [
"I have found the answer. Quoting a co-worker:\n\nThe interior comprehension is asynchronous. The exterior one isn't. The function is asynchronous. The error is triggered because you are defining as an asynchronous comprehension inside of a non-asynchronous context - the error message is indeed wrong and it's a kno... | [
5,
1
] | [] | [] | [
"list_comprehension",
"python",
"python_3.x",
"python_asyncio"
] | stackoverflow_0060041883_list_comprehension_python_python_3.x_python_asyncio.txt |
Q:
Python start browser with current user directory on Windows
I want to open web browser with url my python script.
I have a more than 100+ user. I want to run the my python script with every user desktop portable chrome for ex. C:\Users\user1\Desktop\chrome\chrome.exe
My code;
import webbrowser import os url = 'htt... | Python start browser with current user directory on Windows | I want to open web browser with url my python script.
I have a more than 100+ user. I want to run the my python script with every user desktop portable chrome for ex. C:\Users\user1\Desktop\chrome\chrome.exe
My code;
import webbrowser import os url = 'http://example.com/' webbrowser.register('chrome', None, webbrowser.... | [
"Try the following solution, all it does, is simply using os.getlogin() function which returns the username of the current user and assign it to username variable, then the username variable is being used as part of the path.\nimport webbrowser\nimport os\n\nusername = os.getlogin()\nurl = 'http://example.com/'\nwe... | [
0
] | [] | [] | [
"python",
"python_webbrowser",
"windows"
] | stackoverflow_0074408922_python_python_webbrowser_windows.txt |
Q:
on_member_join not working for welcome message
Trying to make a simple welcome print when a user joins:
@bot.event
async def on_member_join(member) :
print ("new member joined")
bot.run("token bwahahhaha")
ALL INTENTS ARE ENABLED, INCLUDING ON THE DEV PORTAL
intents = discord.Intents().all()
bot = commands.B... | on_member_join not working for welcome message | Trying to make a simple welcome print when a user joins:
@bot.event
async def on_member_join(member) :
print ("new member joined")
bot.run("token bwahahhaha")
ALL INTENTS ARE ENABLED, INCLUDING ON THE DEV PORTAL
intents = discord.Intents().all()
bot = commands.Bot(command_prefix='!', intents=intents)
and I'm ge... | [
"if you want it shows in a channel you should go to settings/settingschannels and choose the channel\nthen\nyou should to use a await not a print\nfrom discord.ext import commands\n\nintents = discord.Intents.all()\nbot = commands.Bot(command_prefix=\"!\", intents = intents)\n\n@bot.event\nasync def on_member_join(... | [
1
] | [] | [] | [
"discord.py",
"pycord",
"python"
] | stackoverflow_0074396735_discord.py_pycord_python.txt |
Q:
How to select element using XPATH syntax on Selenium for Python?
consider following HTML:
<div id='a'>
<div>
<a class='click'>abc</a>
</div>
</div>
I want to click abc, but the wrapper div could change, so
driver.get_element_by_xpath("//div[@id='a']/div/a[@class='click']")
is not what I want
i tried:
dr... | How to select element using XPATH syntax on Selenium for Python? | consider following HTML:
<div id='a'>
<div>
<a class='click'>abc</a>
</div>
</div>
I want to click abc, but the wrapper div could change, so
driver.get_element_by_xpath("//div[@id='a']/div/a[@class='click']")
is not what I want
i tried:
driver.get_element_by_xpath("//div[@id='a']").get_element_by_xpath(.//a[... | [
"HTML\n<div id='a'>\n <div>\n <a class='click'>abc</a>\n </div>\n</div>\n\nYou could use the XPATH as :\n//div[@id='a']//a[@class='click']\n\noutput\n<a class=\"click\">abc</a>\n\nThat said your Python code should be as :\ndriver.find_element_by_xpath(\"//div[@id='a']//a[@class='click']\")\n\n",
"In the late... | [
63,
1
] | [
"Check this blog by Martin Thoma. I tested the below code on MacOS Mojave and it worked as specified. \n> def get_browser():\n> \"\"\"Get the browser (a \"driver\").\"\"\"\n> # find the path with 'which chromedriver'\n> path_to_chromedriver = ('/home/moose/GitHub/algorithms/scraping/'\n> ... | [
-2
] | [
"python",
"selenium",
"xpath"
] | stackoverflow_0019035186_python_selenium_xpath.txt |
Q:
Python/Tkinter: How can I prevent this function from returning None prematurely?
The following function accepts a list as input and then waits for the user to enter chars in an entry widget. Each time chars are entered, a listbox widget displays all of the items from the input list that include those characters, t... | Python/Tkinter: How can I prevent this function from returning None prematurely? | The following function accepts a list as input and then waits for the user to enter chars in an entry widget. Each time chars are entered, a listbox widget displays all of the items from the input list that include those characters, thus filtering the input list to only selected items. When the user is satisfied with t... | [
"If you're trying to create what is in essence a modal dialog box, tkinter has special functions to wait for specific events. For example, you can call a function that waits until a variable has been set, or you can wait until a widget has been destroyed. While waiting, events will be processed as usual.\nIn your c... | [
1
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074408572_python_tkinter.txt |
Q:
A callback function is called multiple times in event loop
I am trying to understand the behavior of the code below. I tried to register a callback function trampoline to be called in an event loop using asyncio module. The trampoline got itself is called multiple times, which I am sure why that happened please. M... | A callback function is called multiple times in event loop | I am trying to understand the behavior of the code below. I tried to register a callback function trampoline to be called in an event loop using asyncio module. The trampoline got itself is called multiple times, which I am sure why that happened please. My expectation was the callback trampoline will call itself only ... | [
"The issue is that trampoline schedules a callback to itself when called.\nThat means that trampoline will be called after 0.5 seconds, rescheduling again a callback to itself for 0.5 seconds later\nTo have it only called once, you should remove .call_later from inside trampoline and move it outside:\n...\ndef tram... | [
1
] | [] | [] | [
"python",
"python_asyncio"
] | stackoverflow_0074408388_python_python_asyncio.txt |
Q:
Exception closing connection using sqlalchemy with asyncio and postgresql
I have an API server using Python 3.7.10. I am using the FastAPI framework with sqlalchemy, asyncio, psycopg2-binary, asyncpg along with postgresql. I am deploying this using aws elasticbeanstalk. The application seems to work fine but every... | Exception closing connection using sqlalchemy with asyncio and postgresql | I have an API server using Python 3.7.10. I am using the FastAPI framework with sqlalchemy, asyncio, psycopg2-binary, asyncpg along with postgresql. I am deploying this using aws elasticbeanstalk. The application seems to work fine but everytime my frontend calls an endpoint, it seems like the connection is not closing... | [
"generally I had similar issue when using:\n@app.middleware(\"http\")\nasync def add_process_time_header(request: fastapi.Request, call_next):\n\nDisabling middleware helped. Still trying to figure this out :)\n",
"My problem was fixed by using NullPool class.\nfrom sqlalchemy.pool import NullPool\nfrom sqlalchem... | [
0,
0
] | [] | [] | [
"asyncpg",
"fastapi",
"python",
"python_asyncio",
"sqlalchemy"
] | stackoverflow_0072468241_asyncpg_fastapi_python_python_asyncio_sqlalchemy.txt |
Q:
Issues running PLY Python
I am having issues running PLY in python. I have already installed PLY by downloading the install file online and running it from command prompt. The installation was successful. However, I keep getting the error that "no module named ply". I have put the code below:
VS_Code keeps putting... | Issues running PLY Python | I am having issues running PLY in python. I have already installed PLY by downloading the install file online and running it from command prompt. The installation was successful. However, I keep getting the error that "no module named ply". I have put the code below:
VS_Code keeps putting squiggly lines under the ply a... | [
"I'd lay odds that what's happened is that you don't have the \"ply\" folder in the folder where you have your language source file and you haven't added the location of ply to your sys.path. That will lead to the exact behavior you're indicating with the squiggly line. I suspect you'll also see an \"Import \"ply\"... | [
0
] | [] | [] | [
"ply",
"python"
] | stackoverflow_0074169232_ply_python.txt |
Q:
What's the best way to get a list/array of element-wise means between an array and a constant?
Suppose I have my_array = np.array([2, 4, 6]) and I want to get another array that represents the mean of each element in my_array and a constant, say, 2. So I want to return returned_array = [2, 3, 4]. What is the best ... | What's the best way to get a list/array of element-wise means between an array and a constant? | Suppose I have my_array = np.array([2, 4, 6]) and I want to get another array that represents the mean of each element in my_array and a constant, say, 2. So I want to return returned_array = [2, 3, 4]. What is the best way to do this?
When I try np.mean(my_array, 2) I get TypeError: only size-1 arrays can be converted... | [
"How about this:\nimport numpy as np\n\nmy_array = np.array([2, 4, 6])\nother = 2\n(my_array + other) / 2\n# [2. 3. 4.]\n\nIt's just the element-wise average of two numbers, which is the same as just dividing by two.\n"
] | [
1
] | [] | [] | [
"arrays",
"mean",
"numpy",
"python"
] | stackoverflow_0074409277_arrays_mean_numpy_python.txt |
Q:
Labeling one bar in altair
I'd like to label one exact bar in bar chart made up by altair, but I can't find the information about that option - only labeling the whole plot, which I'm not interested at. May be there is something like altair.condition for coloring, for example? So I can label a bar according to the... | Labeling one bar in altair | I'd like to label one exact bar in bar chart made up by altair, but I can't find the information about that option - only labeling the whole plot, which I'm not interested at. May be there is something like altair.condition for coloring, for example? So I can label a bar according to the condition. Thank you!
| [
"Labeling one bar is doable, there are just a few extra steps. I'll be using the built-in airports dataset to demonstrate.\nfrom vega_datasets import data\nimport altair as alt\n\nairports = data.airports().query(\"country == 'USA'\").dropna()\n\nairports['label'] = False # create new column\nairports.loc[airports... | [
1
] | [] | [] | [
"altair",
"bar_chart",
"label",
"python"
] | stackoverflow_0074193704_altair_bar_chart_label_python.txt |
Q:
can't find all occurrences of a string in a 2d array and then put each row in said 2d array into a 1d array
A program is required to sort sentences from an input file. The sentences may contain the word ‘ERROR’, ‘INFORMATION’, or neither. Sentences with ‘ERROR’ go to an error log. Sentences with ‘INFORMATION’ go t... | can't find all occurrences of a string in a 2d array and then put each row in said 2d array into a 1d array |
A program is required to sort sentences from an input file. The sentences may contain the word ‘ERROR’, ‘INFORMATION’, or neither. Sentences with ‘ERROR’ go to an error log. Sentences with ‘INFORMATION’ go to an information log. Sentences that contain neither are not processed. The original input file should not be ch... | [
"Let's start by fixing the loadData() function:\ndef loadData():\n sentences = []\n theFile = open(FILENAME, \"r\")\n for line in theFile:\n line = line.strip()\n theFields = line.split(\".\")\n sentences += theFields\n theFile.close()\n return sentences\n\nNow on to the check() ... | [
0
] | [] | [] | [
"matrix",
"python",
"python_3.x",
"search"
] | stackoverflow_0074409030_matrix_python_python_3.x_search.txt |
Q:
How to return to a different loop python
I am making a black jack game and I want to make it so that you can try again, but to do that you would have to access a loop that was already broken out of, how can I replay an old loop, here is the code (The highlighted loop is the one I am reffering to.):
import random
... | How to return to a different loop python | I am making a black jack game and I want to make it so that you can try again, but to do that you would have to access a loop that was already broken out of, how can I replay an old loop, here is the code (The highlighted loop is the one I am reffering to.):
import random
playerIn = True
dealerIn = True
name = input(... | [
"import random\n\nplayerIn = True\ndealerIn = True\n\nname = input(\"What is your name? \")\n\n# Deck of cards.\ndeck = [2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11]\ncardTypes = [\"Hea... | [
0
] | [] | [] | [
"blackjack",
"loops",
"python"
] | stackoverflow_0074409177_blackjack_loops_python.txt |
Q:
Summing integers in a list of dictionaries
How do I use the Loop Summing Pattern to calculate and print the total score of all the games in this list of dictionaries? The Sum function is not allowed, nor is importing functions:
games = [
{"Name": "UD", "Score": 27, "Away?": False},
{"Name": "Clemson", "Sco... | Summing integers in a list of dictionaries | How do I use the Loop Summing Pattern to calculate and print the total score of all the games in this list of dictionaries? The Sum function is not allowed, nor is importing functions:
games = [
{"Name": "UD", "Score": 27, "Away?": False},
{"Name": "Clemson", "Score": 14, "Away?": True},
{"Name": "Pitt", "S... | [
"You have a list of dictionaries that you can iterate. Once you get a single game, the Score is easy to grab.\ngames = [\n {\"Name\": \"UD\", \"Score\": 27, \"Away?\": False},\n {\"Name\": \"Clemson\", \"Score\": 14, \"Away?\": True},\n {\"Name\": \"Pitt\", \"Score\": 32, \"Away?\": True},\n]\n\ntotal = 0\... | [
-1
] | [
"You may want to write it this way (same method Tim Roberts mentioned in the comment):\ngames = [\n{\"Name\": \"UD\", \"Score\": 27, \"Away?\": False},\n{\"Name\": \"Clemson\", \"Score\": 14, \"Away?\": True},\n{\"Name\": \"Pitt\", \"Score\": 32, \"Away?\": True},]\n\nsum_hold = 0\n\nfor i in games:\n sum_hold += ... | [
-1
] | [
"python"
] | stackoverflow_0074409291_python.txt |
Q:
How to iterate faster?
I'm iterating 4 million times (for a project). This is taking forever to do. I was wondering how I can go faster.
numbers = [0,1]
evenNumbers = []
y = 0
l = 0
for x in range (1,4000000):
l = numbers[x-1] + numbers[x]
numbers.append(l)
for k in numbers:
if k % 2 ==0:
evenNumbe... | How to iterate faster? | I'm iterating 4 million times (for a project). This is taking forever to do. I was wondering how I can go faster.
numbers = [0,1]
evenNumbers = []
y = 0
l = 0
for x in range (1,4000000):
l = numbers[x-1] + numbers[x]
numbers.append(l)
for k in numbers:
if k % 2 ==0:
evenNumbers.append(k)
for n in evenN... | [
"This is going to be very slow regardless due to the how big the numbers are getting, but you can speed it up significantly by just not storing all the intermediate values:\nm, n = 0, 1\ny = 0\nfor _ in range(1, 4000000):\n m, n = n, m + n\n if n % 2 == 0:\n y += n\n\nprint(y)\n\n",
"You should just ... | [
2,
0
] | [] | [] | [
"list",
"loops",
"python"
] | stackoverflow_0074409199_list_loops_python.txt |
Q:
JNI_CreateJavaVM() runs O.K. 1x, but after that: failed with result: -5 (Win64, Cython, Python)
Error:
Does not occur on run 1, but on any subsequent run, Python kernel dies and has to be restarted:
JNI_CreateJavaVM() failed with result: -5
[SpyderKernelApp] WARNING | No such comm: aa125bd78d0711ebb9a2001a7dda7113... | JNI_CreateJavaVM() runs O.K. 1x, but after that: failed with result: -5 (Win64, Cython, Python) | Error:
Does not occur on run 1, but on any subsequent run, Python kernel dies and has to be restarted:
JNI_CreateJavaVM() failed with result: -5
[SpyderKernelApp] WARNING | No such comm: aa125bd78d0711ebb9a2001a7dda7113
Environment:
All current as of 3/2021
Win64
Anaconda (actually mini-anaconda)
Java runtime for Wi... | [
"Per Java's Chapter 5: The Invocation API DestroyJavaVM() documentation (bolding mine):\n\nDestroyJavaVM\njint DestroyJavaVM(JavaVM *vm);\n\nUnloads a Java VM and reclaims its resources.\nAny thread, whether attached or not, can invoke this function. If the\ncurrent thread is attached, the VM waits until the curren... | [
1,
0
] | [] | [] | [
"cpython",
"java_native_interface",
"python",
"windows"
] | stackoverflow_0066895522_cpython_java_native_interface_python_windows.txt |
Q:
Scrapy spider starts fast and slows down gradually
I'm scraping 28M pages and my scrapy spider starts fast and slows down gradually.
I doubt it the server blocking me since I can run a second spider and it will start fast again.
Not the hardware, is running on a nice vps with 24gb RAM. Allowed domains is just that... | Scrapy spider starts fast and slows down gradually | I'm scraping 28M pages and my scrapy spider starts fast and slows down gradually.
I doubt it the server blocking me since I can run a second spider and it will start fast again.
Not the hardware, is running on a nice vps with 24gb RAM. Allowed domains is just that site.
What could be the cause of the slowdown?
If I sto... | [
"It isn't actually slowing down, it just appears that way because of the number of concurrent procedures it is managing at a time.\nAutoThrottle can help mitigate this behavior but it only effects one end of the scrapy workflow. There is also the output/feeds end of the spider that is also asynchronous and can ofte... | [
0
] | [] | [] | [
"python",
"scrapy"
] | stackoverflow_0074403037_python_scrapy.txt |
Q:
Sorting a list of uneven lists based on the third column of the 1st row of each uneven list
I have a csv file where I group rows together if they share the same address. These groups contain around 1 - 10 rows. I need to sort these groups based on a date in the fourth column in the first row of each group.
Below i... | Sorting a list of uneven lists based on the third column of the 1st row of each uneven list | I have a csv file where I group rows together if they share the same address. These groups contain around 1 - 10 rows. I need to sort these groups based on a date in the fourth column in the first row of each group.
Below is a pseudo illustration of my data and below that is my code.
list_of_parcel_groups = [ [ [ [0,1,... | [
"If I've correctly understood the construction of your raw data, then this should give you what you're looking for - no?\nfrom datetime import datetime\n\nlist_of_parcel_groups = [[[0,1,2,'11/22/2022'], [0,1,2,'1/01/2001']] , \n [[0,1,2,'3/11/2022'], [0,1,2,'3/04/2016'], [0,1,2,'5/18/2011'],... | [
1
] | [] | [] | [
"date",
"datetime",
"list",
"python",
"sorting"
] | stackoverflow_0074407894_date_datetime_list_python_sorting.txt |
Q:
combining sublists created from regex expressions
I used a regex expression which extracted numbers from some line and this created some list which i combined using the append function how do i combine these sublists into one list
fname=input('Enter file name:')
if len(fname)<1:
fname='regex_sum_42.txt'
fhand=... | combining sublists created from regex expressions | I used a regex expression which extracted numbers from some line and this created some list which i combined using the append function how do i combine these sublists into one list
fname=input('Enter file name:')
if len(fname)<1:
fname='regex_sum_42.txt'
fhand=open(fname)
total=0
numlist=list()
for line in fhand:
... | [
"One solution to flatten your list of lists.\nsum(numlist, [])\n\n",
"You are working too hard: why process the file line by line when you can process the whole file at once?\n# Assume file_name is defined\n\nwith open(file_name) as stream:\n contents = stream.read()\n \nnumbers_list = re.findall(r\"\\d+\",... | [
1,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0074408260_list_python.txt |
Q:
Deploying Flask application with Apache2 Proxy Server
I'm trying to deploy a Flask application with Gunicorn with a Proxy Server in Apache2. The Flask application is running in a Docker container but not the Apache2 server.
Here is the configuration for Apache2.
<Macro DemoSubdomain $subdomain_name $proxy_pass_pro... | Deploying Flask application with Apache2 Proxy Server | I'm trying to deploy a Flask application with Gunicorn with a Proxy Server in Apache2. The Flask application is running in a Docker container but not the Apache2 server.
Here is the configuration for Apache2.
<Macro DemoSubdomain $subdomain_name $proxy_pass_proto $proxy_pass_to>
<VirtualHost *:443>
ServerName $subd... | [
"If your goal is to setup a simple website with https, I can offer the steps I've taken.\nAssumptions:\n\nServer is a \"New Ubuntu Image\" (ie. on a Raspberry Pi)\nYou have a Python Flask app\nYou want the server to host https traffic\nYou own a domain name (ie. example.com)\n\n\nStep 0.\n\nConfigure the server to ... | [
0
] | [] | [] | [
"apache2",
"flask",
"gunicorn",
"proxy",
"python"
] | stackoverflow_0071294518_apache2_flask_gunicorn_proxy_python.txt |
Q:
Why isn't this Pandas pivot table working?
My code takes a bank statement from Excel and creates a dataframe that categorises each transaction based on description:
import pandas as pd
import openpyxl
import datetime as dt
import numpy as np
dff = pd.DataFrame({'Date': ['20221003', '20221005'],
... | Why isn't this Pandas pivot table working? | My code takes a bank statement from Excel and creates a dataframe that categorises each transaction based on description:
import pandas as pd
import openpyxl
import datetime as dt
import numpy as np
dff = pd.DataFrame({'Date': ['20221003', '20221005'],
'Tran Type': ['BOOK TRANSFER CREDIT', 'ACH DEBI... | [
"Add this line before executing (untested):\nimport numpy as np\ndff['category'] = [x[0] if not x.isempty() else np.nan for x in dff['category']]\n\nThis will make sure your category is not a list (which can't be hashed).\n"
] | [
0
] | [] | [] | [
"pandas",
"pivot_table",
"python"
] | stackoverflow_0074409021_pandas_pivot_table_python.txt |
Q:
Creating separate sets from file in python
Below is a sample input file:
A, B, C
Location:London
A, 46
B, 93
C, 32
Location:Amsterdam
A, 83
B, 21
C, 92
Location:Paris
A, 29
B, 91
C, 10
The output should be as follows:
name_set = { A, B, C }
location_set = {London, Amsterdam, Paris}
Generate a dictonary that ma... | Creating separate sets from file in python | Below is a sample input file:
A, B, C
Location:London
A, 46
B, 93
C, 32
Location:Amsterdam
A, 83
B, 21
C, 92
Location:Paris
A, 29
B, 91
C, 10
The output should be as follows:
name_set = { A, B, C }
location_set = {London, Amsterdam, Paris}
Generate a dictonary that maps name to number and calculate total
dic = {A: ... | [
"It is unclear what you want as a result, as you seem to want to produce a dictionary with duplicate keys. This isn't supported by a standard Python dictionary, and usually isn't what you want anyway. Just think...how would you tell Python which key value to look up in a dictionary that had duplicate keys?\nHere'... | [
1
] | [] | [] | [
"python",
"set",
"split"
] | stackoverflow_0074409356_python_set_split.txt |
Q:
Why doesn't my for-loop work as i want it to work?
import random
def calculate_score():
worplist = [1, 1, 5]
for worp in worplist:
if worp == 1:
worplist.remove(worp)
if worp == 6:
worplist.append(worp)
print(sum(worplist))
calculate_score()
I want e... | Why doesn't my for-loop work as i want it to work? | import random
def calculate_score():
worplist = [1, 1, 5]
for worp in worplist:
if worp == 1:
worplist.remove(worp)
if worp == 6:
worplist.append(worp)
print(sum(worplist))
calculate_score()
I want every 1 to be removed but it only removes the first one. ... | [
"Have you tried using an \"else if\" instead of another \"if\" statement?\nimport random\n\ndef calculate_score():\n worplist = [1, 1, 5]\n for worp in worplist:\n if worp == 1:\n worplist.remove(worp)\n elif worp == 6:\n worplist.remove(worp)\n print(sum(worplist))\n\nc... | [
0
] | [] | [] | [
"for_loop",
"python"
] | stackoverflow_0074409517_for_loop_python.txt |
Q:
How to append ones to a list?
I have the following list -
pts1_list = [
[224.95256042, 321.64755249],
[280.72879028, 296.15835571],
[302.34194946, 364.82437134],
[434.68283081, 402.86990356],
[244.64321899, 308.50286865],
[488.62979126, 216.26953125],
[214.77470398, 430.75869751],
... | How to append ones to a list? | I have the following list -
pts1_list = [
[224.95256042, 321.64755249],
[280.72879028, 296.15835571],
[302.34194946, 364.82437134],
[434.68283081, 402.86990356],
[244.64321899, 308.50286865],
[488.62979126, 216.26953125],
[214.77470398, 430.75869751],
[299.20846558, 312.07217407],
[... | [
"This can be solved using list addition. Out of the other answers, this is the most commonly used, easiest, and simplest. Read up on nested list comprehension.\npoints1_list = [i + [1] for i in pts1_list]\n\n",
"Just loop through the matrix and append 1 to each list\nfor arr in pts1_list:\n arr.append(1)\n ... | [
1,
1,
1
] | [] | [] | [
"list",
"python"
] | stackoverflow_0074409520_list_python.txt |
Q:
stop python in terminal on mac
Using python in terminal on a Mac, type
ctrl-z
will stop the python, but not exit it, giving output like this:
>>>
[34]+ Stopped python
As you can see, I have stopped 34 python calls.
Although I could use
>>> exit()
to exit python, the questions are:
Is there ... | stop python in terminal on mac | Using python in terminal on a Mac, type
ctrl-z
will stop the python, but not exit it, giving output like this:
>>>
[34]+ Stopped python
As you can see, I have stopped 34 python calls.
Although I could use
>>> exit()
to exit python, the questions are:
Is there a short-key to really exit (not just... | [
"CTRL+d -> Defines EOF (End of File).\nCTRL+c -> Will terminate most jobs.\nIf, however you have written a python wrapper program that calls other python programs in turn, Ctrl-c will only stop the the job that is currently running. The wrapper program will keep running. Worst case scenario, you can do this:\nO... | [
32,
1,
0
] | [
"You can type CTRL + D to quit python.\n"
] | [
-1
] | [
"macos",
"python",
"terminal"
] | stackoverflow_0018047657_macos_python_terminal.txt |
Q:
Adding data to HDF5 Dataset
import numpy as np
import h5py
x1 = [0, 1, 2, 3, 4]
y1 = ['a', 'b', 'c', 'd', 'e']
z1 = [5, 6, 7, 8, 9]
namesList = ['ID', 'Name', 'Path']
ds_dt = np.dtype({'names': namesList, 'formats': ['S32'] * 4})
rec_arr = np.rec.fromarrays([x1, y1, z1], dtype=ds_dt)
test = [[], [], []]
hdf5_fi... | Adding data to HDF5 Dataset | import numpy as np
import h5py
x1 = [0, 1, 2, 3, 4]
y1 = ['a', 'b', 'c', 'd', 'e']
z1 = [5, 6, 7, 8, 9]
namesList = ['ID', 'Name', 'Path']
ds_dt = np.dtype({'names': namesList, 'formats': ['S32'] * 4})
rec_arr = np.rec.fromarrays([x1, y1, z1], dtype=ds_dt)
test = [[], [], []]
hdf5_file = h5py.File("test.h5", "w")
st... | [
"We can add the data directly to the .h5 file when creating the new dataset. The following code worked for me to write rec_arr to the file, and I added the 'with' statement to ensure it is closed properly.\nimport numpy as np\nimport h5py\n\nx1 = [0, 1, 2, 3, 4]\ny1 = ['a', 'b', 'c', 'd', 'e']\nz1 = [5, 6, 7, 8, 9]... | [
0,
0
] | [] | [] | [
"h5py",
"hdf5",
"python"
] | stackoverflow_0074224057_h5py_hdf5_python.txt |
Q:
Python pandas dataframe, column names appear as strings and cannot be involved
i m using the an csv file of the following format:
"LatD", "LatM", "LatS", "NS", "LonD", "LonM", "LonS", "EW", "City", "State"
41, 5, 59, "N", 80, 39, 0, "W", "Youngstown", OH
42, 52, 48, "N", 97, 23, 23,... | Python pandas dataframe, column names appear as strings and cannot be involved | i m using the an csv file of the following format:
"LatD", "LatM", "LatS", "NS", "LonD", "LonM", "LonS", "EW", "City", "State"
41, 5, 59, "N", 80, 39, 0, "W", "Youngstown", OH
42, 52, 48, "N", 97, 23, 23, "W", "Yankton", SD
46, 35, 59, "N", 120, 30, 36, "W", "Yakima", WA
... | [
"You can try to replace \" with empty string (as long as columns doesn't contain other \" as data, it will work):\nfrom io import StringIO\n\nwith open(\"cities.csv\", \"r\") as f_in:\n df = pd.read_csv(\n StringIO(f_in.read().replace('\"', \"\")), sep=r\"\\s*,\\s*\", engine=\"python\"\n )\n\nprint(df[... | [
1,
0
] | [] | [] | [
"csv",
"dataframe",
"pandas",
"python"
] | stackoverflow_0074409512_csv_dataframe_pandas_python.txt |
Q:
can't modify copy of array without changing original array
I tried modifying the array "newTab" but without use tab.copy() but it always modifies the original array.
tab = [[1]*2]*3
newTab = [None] * len(tab)
for i in range(0, len(tab)):
newTab[i] = tab[i]
newTab[0][0] = 2
print(tab)
[[2, 1], [2, 1], [2, 1]]
... | can't modify copy of array without changing original array | I tried modifying the array "newTab" but without use tab.copy() but it always modifies the original array.
tab = [[1]*2]*3
newTab = [None] * len(tab)
for i in range(0, len(tab)):
newTab[i] = tab[i]
newTab[0][0] = 2
print(tab)
[[2, 1], [2, 1], [2, 1]]
print(newTab)
[[2, 1], [2, 1], [2, 1]]
I also tried using somet... | [
"You could use the copy library.\nimport copy\n\ntab = [[1] * 2] * 3\nnewTab = [None] * len(tab)\nfor i in range(len(tab)):\n newTab[i] = copy.deepcopy(tab[i])\n newTab[i][0] = 2\n\nprint(tab)\nprint(newTab)\n\n",
"tab = [[1]*2]*3\ntab2 = []\nfor t in tab:\n tab2.append(t.copy())\n#check that it worked -... | [
1,
0
] | [] | [] | [
"arrays",
"python"
] | stackoverflow_0074409375_arrays_python.txt |
Q:
How to let Pool.map take a lambda function
I have the following function:
def copy_file(source_file, target_dir):
pass
Now I would like to use multiprocessing to execute this function at once:
p = Pool(12)
p.map(lambda x: copy_file(x,target_dir), file_list)
The problem is, lambda's can't be pickled, so this ... | How to let Pool.map take a lambda function | I have the following function:
def copy_file(source_file, target_dir):
pass
Now I would like to use multiprocessing to execute this function at once:
p = Pool(12)
p.map(lambda x: copy_file(x,target_dir), file_list)
The problem is, lambda's can't be pickled, so this fails. What is the most neat (pythonic) way to f... | [
"Use a function object:\nclass Copier(object):\n def __init__(self, tgtdir):\n self.target_dir = tgtdir\n def __call__(self, src):\n copy_file(src, self.target_dir)\n\nTo run your Pool.map:\np.map(Copier(target_dir), file_list)\n\n",
"For Python2.7+ or Python3, you could use functools.partial:... | [
75,
66,
11,
1,
0
] | [] | [] | [
"multiprocessing",
"pool",
"python"
] | stackoverflow_0004827432_multiprocessing_pool_python.txt |
Q:
'node with name "rabbit" is already running on host' even after killing the processes
Whenever I try to run a rabbit server, it meets me with this error:
ERROR: node with name "rabbit" is already running on host "DESKTOP-BKRTA3R"
I've read that I should kill the processes of rabbit by using
rabbitmqctl stop
But ... | 'node with name "rabbit" is already running on host' even after killing the processes | Whenever I try to run a rabbit server, it meets me with this error:
ERROR: node with name "rabbit" is already running on host "DESKTOP-BKRTA3R"
I've read that I should kill the processes of rabbit by using
rabbitmqctl stop
But I still get the error, What else can I do
I am on windows 10
Here is my full error
2022-11-... | [
"Try removing the process with a PID and using taskkill.\nset /p pid=<%~dp0rabbitmq.pid\ntaskkill /F /PID %pid%\ndel /F /Q %~dp0rabbitmq.pid\n\n"
] | [
0
] | [] | [] | [
"clone",
"django",
"python",
"rabbitmq",
"windows"
] | stackoverflow_0074409565_clone_django_python_rabbitmq_windows.txt |
Q:
BdbQuit raised when debugging Python with pdb
Recently when adding the pdb debugger to my Python 2.7.10 code, I get this message:
Traceback (most recent call last):
File "/Users/isaachess/Programming/vivint/Platform/MessageProcessing/vivint_cloud/queues/connectors/amqplib_connector.py", line 191, in acking_callb... | BdbQuit raised when debugging Python with pdb | Recently when adding the pdb debugger to my Python 2.7.10 code, I get this message:
Traceback (most recent call last):
File "/Users/isaachess/Programming/vivint/Platform/MessageProcessing/vivint_cloud/queues/connectors/amqplib_connector.py", line 191, in acking_callback
callback(message.body)
File "/Users/isaac... | [
"I ran into this when I left import pdb and a pdb.set_trace() in my production code. When the pdb.set_trace() line was executed, python was waiting for my input to tell it to continue or step into, etc... Because the python code was being called by a web server I wasn't there to press c to continue. After so long (... | [
24,
17,
17,
5,
2,
1,
0,
0,
0,
0
] | [] | [] | [
"debugging",
"ipdb",
"pdb",
"python",
"python_2.7"
] | stackoverflow_0034914704_debugging_ipdb_pdb_python_python_2.7.txt |
Q:
Handling stop words that are part of hyphenated words while preprocessing text
While pre-processing text by removal of special characters followed by removal of stop words, words such as add-on and non-committal get converted to add and committal respectively. What is the best approach to handle these cases?
A:
... | Handling stop words that are part of hyphenated words while preprocessing text | While pre-processing text by removal of special characters followed by removal of stop words, words such as add-on and non-committal get converted to add and committal respectively. What is the best approach to handle these cases?
| [
"The \"best\" approach depends on what the intended application is and how you want to handle context and meaning of words. Generally, hyphenated words have a distinct meaning that wouldn't be evident if any part were removed. For example, \"add-on\" is treated as noun, while \"add\" is a verb. Similarly \"committa... | [
1
] | [] | [] | [
"nlp",
"python",
"spacy",
"stop_words"
] | stackoverflow_0074403045_nlp_python_spacy_stop_words.txt |
Q:
ModuleNotFoundError: No module named 'fastapi.responses'
I am trying to use HTMLResponse from FastAPI, as described in the documentation. I'm on version 0.70. I keep getting the following error:
ModuleNotFoundError: No module named 'fastapi.responses'
My code is shown below:
from fastapi import FastAPI
from fasta... | ModuleNotFoundError: No module named 'fastapi.responses' | I am trying to use HTMLResponse from FastAPI, as described in the documentation. I'm on version 0.70. I keep getting the following error:
ModuleNotFoundError: No module named 'fastapi.responses'
My code is shown below:
from fastapi import FastAPI
from fastapi.responses import HTMLResponse
import os
from os import curd... | [
"Since FastAPI is built on top of Starlette, try this:\nfrom starlette.responses import HTMLResponse\n\n",
"I think you're using an older version of FastAPI.\nSo, you have to use:\nfrom starlette.responses import HTMLResponse\n\nIn the latest version of FastAPI 0.75.0, you can use:\nfrom fastapi.responses import ... | [
0,
0
] | [] | [] | [
"api",
"fastapi",
"python"
] | stackoverflow_0069861408_api_fastapi_python.txt |
Q:
Get variables from function input and text after
So id like to make varibles from my function input
So basically, the if statement should check if the varible is True or not. And i want to use the function input + ”-outcome” to check.
Function-outcome = True
Function2-outcome = False
c
def a(B):
Global c
If f’{B... | Get variables from function input and text after | So id like to make varibles from my function input
So basically, the if statement should check if the varible is True or not. And i want to use the function input + ”-outcome” to check.
Function-outcome = True
Function2-outcome = False
c
def a(B):
Global c
If f’{B}-outcome’ == True:
Print(”yes”)
Else:
Print(”no”... | [
"import yfinance as yf\nfrom datetime import date\nimport pandas as pd\n\nd_start = '2022-01-01'\nd_end = date.today().strftime('%Y-%m-%d')\n\n#top50 S&P to create a list, if you will use a variable from an API you will just need to declare it as a string\n#you can create a list of your fav ones and it will work th... | [
0
] | [] | [] | [
"f_string",
"function",
"python",
"variables"
] | stackoverflow_0074409511_f_string_function_python_variables.txt |
Q:
Why is ordering in class Meta not working?
I made a Twitter -like social network where users see latest posts first using Django 3.1.7.
My model :
class Post(models.Model):
date_published = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(User, on_delete=models.CASCADE)
content = models... | Why is ordering in class Meta not working? | I made a Twitter -like social network where users see latest posts first using Django 3.1.7.
My model :
class Post(models.Model):
date_published = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(User, on_delete=models.CASCADE)
content = models.CharField(max_length=240, blank=False, default=... | [
"I had two models: NameMixing and Species, which inherited from the former. NameMixing provided a name field which I wanted to order. NameMixing was abstract. Adding ordering = ['name'] did not work, adding it to Species did.\nI had a Meta class in Species as well as in NameMixing. In order for Species to apply all... | [
0
] | [
"Each string is a field name with an optional “-” prefix, which indicates descending order. Fields without a leading “-” will be ordered ascending. Use the string “?” to order randomly.\nFor example, to order by a pub_date field ascending, use this:\nordering = ['pub_date']\n\nTo order by pub_date descending, use t... | [
-1
] | [
"django",
"python",
"sqlite"
] | stackoverflow_0066460277_django_python_sqlite.txt |
Q:
Python how to parse a list[dict] in python and convert values from nested dictionaries as keys
Need help in writing clean code , I have a yaml parsed output which looks like this :
yaml_output = [{'name' : 'alex', 'subjects' : {'maths' : ['grade_1', 'grade_2']}},
{'name' : 'rio', 'subjects' : {'math... | Python how to parse a list[dict] in python and convert values from nested dictionaries as keys | Need help in writing clean code , I have a yaml parsed output which looks like this :
yaml_output = [{'name' : 'alex', 'subjects' : {'maths' : ['grade_1', 'grade_2']}},
{'name' : 'rio', 'subjects' : {'maths' : ['grade_3', 'grade_2'], 'science : ['grade_4', 'grade_6']}}]
I want it create a list of dictio... | [
"You were close. Your for k,v loop is looking at the wrong data. You don't want to look at ALL the keys, you want to unravel the subjects key and reference the \"name\" specifically.\nyaml_output = [{'name' : 'alex', 'subjects' : {'maths' : ['grade_1', 'grade_2']}},\n {'name' : 'rio', 'subjects' : {... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074409538_python.txt |
Q:
Pandas: filter on grouped and aggregated dataframe
I have a dataframe which is based on a read-in excel list. The data has multiple columns and rows with one unique identifier. I want to plot the data through a PyQT interface based on some user selection (checkboxes), but I cannot select one unique row for plottin... | Pandas: filter on grouped and aggregated dataframe | I have a dataframe which is based on a read-in excel list. The data has multiple columns and rows with one unique identifier. I want to plot the data through a PyQT interface based on some user selection (checkboxes), but I cannot select one unique row for plotting.
The data looks like this:
| Experiment | Data 1 | Dat... | [
"df.groupby('Experiment').agg(list).query('index == \"Exp3\"')\n\noutput:\n Data 1 Data 2\nExperiment \nExp3 [ 1 , 2 ] [ 2 , 2 ]\n\n"
] | [
1
] | [] | [] | [
"dataframe",
"group_by",
"pandas",
"python"
] | stackoverflow_0074409662_dataframe_group_by_pandas_python.txt |
Q:
Am I able to call a submethod of a class's attribute from that class using the class as an attribute?
I am very sorry for the confusing title, I did not know how else to phrase the question.
Let's say I have a class, A. It is described as shown:
class A:
def __init__(self, argument):
self.value = argum... | Am I able to call a submethod of a class's attribute from that class using the class as an attribute? | I am very sorry for the confusing title, I did not know how else to phrase the question.
Let's say I have a class, A. It is described as shown:
class A:
def __init__(self, argument):
self.value = argument
def submethod(self, argumentThatWillBeAClass):
print(dir(argumentThatWillBeAClass))
And t... | [
"\nNow, I have a class, B. Let's add a submethod that calls A's submethod\nwith B as an argument.\n\nBut that isn't what your code does. On the following line:\n self.classAInstance.submethod(self)\n\nYou are calling the method (I don't know what you mean by \"sub\" method, these are all just normal methods) with *... | [
0
] | [
"As one potential solution, you can use inheritance. This allows class B to inherit everything from class A\nclass A:\n def __init__(self, argument):\n self.value = argument\n\n def submethod(self, argumentThatWillBeAClass):\n print(dir(argumentThatWillBeAClass))\n\nclass B(A):\n def __init__... | [
-1
] | [
"oop",
"python",
"python_3.x"
] | stackoverflow_0074409594_oop_python_python_3.x.txt |
Q:
ImportError: No module named 'yaml'
I have one script in which I am trying to execute
python3 env/common_config/add_imagepullsecret.py
But, I am getting the following error:
[root@kevin]# python3 env/common_config/add_imagepullsecret.py
Traceback (most recent call last):
File "env/common_config/add_imagepulls... | ImportError: No module named 'yaml' | I have one script in which I am trying to execute
python3 env/common_config/add_imagepullsecret.py
But, I am getting the following error:
[root@kevin]# python3 env/common_config/add_imagepullsecret.py
Traceback (most recent call last):
File "env/common_config/add_imagepullsecret.py", line 4, in <module>
import ya... | [
"pip install pyyaml\n\nThis should serve the purpose\n",
"Solution 1: install python 3.6(or use pyenv to manage py version) and ln python3 to it\nexport $PYPATH=`which python3`\nwget https://www.python.org/ftp/python/3.6.5/Python-3.6.5.tar.xz\ntar -Jxf Python-3.6.5.tar.xz\ncd Python-3.6.5/\n./configure && make &&... | [
192,
21,
7,
5,
5,
2,
2,
0,
0,
0
] | [] | [] | [
"pip",
"python",
"python_3.x",
"pyyaml"
] | stackoverflow_0050868322_pip_python_python_3.x_pyyaml.txt |
Q:
How to reorganize a dataframe in order to increase dimensionality?
I have an existing data frame with 3 columns: location ,contaminants and Concentration.
It looks something like this:
Location
Contaminants
Concentration
NYC
Chlorine
10
Los Angeles
Lead
5
Los Angeles
Chlorine
2
Miami
Sulfur
5
Miami
Lead
4
I... | How to reorganize a dataframe in order to increase dimensionality? | I have an existing data frame with 3 columns: location ,contaminants and Concentration.
It looks something like this:
Location
Contaminants
Concentration
NYC
Chlorine
10
Los Angeles
Lead
5
Los Angeles
Chlorine
2
Miami
Sulfur
5
Miami
Lead
4
I need to sort it so that there is only one row per location... | [
"You can use pandas.pivot to transform your data from long to wide format\nexample code using sample data:\ndf.pivot(index='Location', columns='Contaminants', values='Concentration').fillna(0)\n\nwhich outputs:\n| Contaminants | Chlorine | Lead | Sulfur |\n| Location | | | |\n|-------------... | [
0
] | [] | [] | [
"data_science",
"dataframe",
"machine_learning",
"pandas",
"python"
] | stackoverflow_0074397280_data_science_dataframe_machine_learning_pandas_python.txt |
Q:
Solve a linear system of equations with bounds using LSQR/LSMR SciPy
Question is quite straight forward. I have an overdetermined system I am attempting to use SciPy LSQR (or LSMR) to solve. However, I cannot find anywhere in the docs on how to set restraints for the minimization.
E.G. Let's say this is the output... | Solve a linear system of equations with bounds using LSQR/LSMR SciPy | Question is quite straight forward. I have an overdetermined system I am attempting to use SciPy LSQR (or LSMR) to solve. However, I cannot find anywhere in the docs on how to set restraints for the minimization.
E.G. Let's say this is the output:
The matrix A has 469 rows and 3 columns
damp = 0.00000000000000e+00
ato... | [
"The functions lsqr and lsmr in scipy.sparse.linalg do not have options for adding constraints. You might be able to use scipy.optimize.lsq_linear instead.\n"
] | [
1
] | [] | [] | [
"python",
"scipy"
] | stackoverflow_0074394670_python_scipy.txt |
Q:
How to find the indices of a letter in a word?
I want to write a program to find the position of letter e in a sentence and print the output (indices) as a list.
This is my code,
def find_position(x):
n=len(x)
for test in range(0,n):
if x[test]=="e":
b=test
return b
text="Helloe"
ans=find_po... | How to find the indices of a letter in a word? | I want to write a program to find the position of letter e in a sentence and print the output (indices) as a list.
This is my code,
def find_position(x):
n=len(x)
for test in range(0,n):
if x[test]=="e":
b=test
return b
text="Helloe"
ans=find_position(text)
print(ans)
I am getting output as 1 w... | [
"Alternative, you could try to use enumerate to get (index, char) tuple at once, and check the char to get your desired index:\nNotes - it's always consider better practice to access an item in an iterable directly, instead of using indirect way (eg. index). It's also helpful to use some meaningful variable names i... | [
2,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074409441_python.txt |
Q:
Stable Baselines3 RuntimeError: mat1 and mat2 must have the same dtype
I am trying to implement SAC with a custom environment in Stable Baselines3 and I keep getting the error in the title. The error occurs with any off policy algorithm not just SAC.
Traceback:
File "<MY PROJECT PATH>\src\main.py", line 70, in <mo... | Stable Baselines3 RuntimeError: mat1 and mat2 must have the same dtype | I am trying to implement SAC with a custom environment in Stable Baselines3 and I keep getting the error in the title. The error occurs with any off policy algorithm not just SAC.
Traceback:
File "<MY PROJECT PATH>\src\main.py", line 70, in <module>
main()
File "<MY PROJECT PATH>\src\main.py", line 66, in main
mode... | [
"Change the inputs to float32 , default the loader set the type as float64.\ninputs = inputs.to(torch.float32)\n\n"
] | [
3
] | [] | [] | [
"openai_gym",
"python",
"pytorch",
"stable_baselines"
] | stackoverflow_0074229178_openai_gym_python_pytorch_stable_baselines.txt |
Q:
Tkinter entry widget doesn't show input during root.after()
I tired creating a countdown timer. During the duration of the timer the user should be able to enter text. However, it only displays the text after the .after() period (I think thats whats happening at least). It updates after each period and then it dis... | Tkinter entry widget doesn't show input during root.after() | I tired creating a countdown timer. During the duration of the timer the user should be able to enter text. However, it only displays the text after the .after() period (I think thats whats happening at least). It updates after each period and then it displays the text. Is there any workaround for this? Is there any ot... | [
"The root.after method is used to perform some kind of callback as the second parameter for the action it should perform once the time has passed. To fix just create a callback function that updates the variable every second. and continues the countdown inside of the callback.\nFor example:\nimport tkinter\nfrom t... | [
0
] | [] | [] | [
"python",
"python_3.x",
"tkinter",
"wait"
] | stackoverflow_0074409507_python_python_3.x_tkinter_wait.txt |
Q:
Running multiple instances of python in windows 11
I am using windows 11 and have installed python 2.7 first, and python 3.10 right after. I have set the environment path for both.
I have also made a copy of the python exe and renamed them to "python2" and "python3" (see below)
https://i.imgur.com/oZlL2iS.jpeg
htt... | Running multiple instances of python in windows 11 | I am using windows 11 and have installed python 2.7 first, and python 3.10 right after. I have set the environment path for both.
I have also made a copy of the python exe and renamed them to "python2" and "python3" (see below)
https://i.imgur.com/oZlL2iS.jpeg
https://i.imgur.com/MBRe9LL.jpeg
In the command prompt when... | [
"As you are below python 3.7 you might have to use those shebang lines:\n#! /usr/bin/python3.6\n#! /usr/bin/python2.7\n\nFor this to work you have to install the python launcher\nBeginngin with 3.7 you could loose the minor version and only use\n#! /usr/bin/python3\n\n",
"Don't add either to the path and use the ... | [
0,
0
] | [] | [] | [
"python",
"python_2.7",
"python_3.x",
"windows"
] | stackoverflow_0074407545_python_python_2.7_python_3.x_windows.txt |
Q:
Django : FieldError at /editstu/121
Error :
Cannot resolve keyword 'id' into field. Choices are: Age, Course_ID, DoB, Grade, Student_ID, Student_Name
My function in views.py
def Editstu(request,id):
editstuobj = Student.objects.get(id=id)
return render(request, 'editstu.html',{'Student':editstuobj})
My u... | Django : FieldError at /editstu/121 | Error :
Cannot resolve keyword 'id' into field. Choices are: Age, Course_ID, DoB, Grade, Student_ID, Student_Name
My function in views.py
def Editstu(request,id):
editstuobj = Student.objects.get(id=id)
return render(request, 'editstu.html',{'Student':editstuobj})
My urls.py
urlpatterns = [
path("admin/"... | [
"I think the model field is Student_ID not id and also use get_object_or_404() so:\ndef Editstu(request,id):\n editstuobj = get_object_or_404(Student,Student_ID=id)\n return render(request, 'editstu.html',{'Student':editstuobj})\n\nAlso use url tags so:\n<td><a href=\"{% url 'Editstu' result.Student_ID %}\">E... | [
2
] | [] | [] | [
"django",
"django_models",
"django_templates",
"django_urls",
"python"
] | stackoverflow_0074409617_django_django_models_django_templates_django_urls_python.txt |
Q:
how to do data augmentation and save it to another folder?
I am working with an image dataset and I want to do data augmentation and I am new to python.
The dataset has 2 classes, and I want to save augmented images in the augmented class folder.
dataset
|
-- original_images
|
|-- cla... | how to do data augmentation and save it to another folder? | I am working with an image dataset and I want to do data augmentation and I am new to python.
The dataset has 2 classes, and I want to save augmented images in the augmented class folder.
dataset
|
-- original_images
|
|-- class1
| |-- benign_image1.png
| |-- benign_image2.png
... | [
"code below provides 2 functions that will do the job. The first function make_dataframe operates on the directory with the stored images, in your case that would be original_images. It produces a dataframe df with columns filepaths, labels where filepaths is the full path to an image and labels is the class label ... | [
3,
1
] | [] | [] | [
"keras",
"python",
"tensorflow"
] | stackoverflow_0073971025_keras_python_tensorflow.txt |
Q:
Plotly - Checkbox instead of dropdown selection
I am trying to use plotly to display a Line chart with sliders and a checkbox dropdown for filters.
My DataFrame (ct2) is like below:
Category
Date
Count
A
2022-06-01
123
B
2022-06-02
56
C
2022-06-03
42
C
2022-06-01
84
A
2022-06-05
32
My sliders are working, a... | Plotly - Checkbox instead of dropdown selection | I am trying to use plotly to display a Line chart with sliders and a checkbox dropdown for filters.
My DataFrame (ct2) is like below:
Category
Date
Count
A
2022-06-01
123
B
2022-06-02
56
C
2022-06-03
42
C
2022-06-01
84
A
2022-06-05
32
My sliders are working, and my dropdown shows items, but when I s... | [
"The reason it was not displayed is that all display settings are false. You need to change the condition to true if the condition is met and false otherwise.\nThe second question is, there are no checkboxes in the custom controls in plotly.\nThe second question is that there are no checkboxes in plotly's custom co... | [
0
] | [] | [] | [
"pandas",
"plotly",
"python",
"visualization"
] | stackoverflow_0074408717_pandas_plotly_python_visualization.txt |
Q:
Handling matrix multiplication in log space in Python
I am implementing a Hidden Markov Model and thus am dealing with very small probabilities. I am handling the underflow by representing variables in log space (so x → log(x)) which has the side effect that multiplication is now replaced by addition and addition ... | Handling matrix multiplication in log space in Python | I am implementing a Hidden Markov Model and thus am dealing with very small probabilities. I am handling the underflow by representing variables in log space (so x → log(x)) which has the side effect that multiplication is now replaced by addition and addition is handled via numpy.logaddexp or similar.
Is there an easy... | [
"This is the best way I could come up with to do it.\nfrom scipy.special import logsumexp\ndef log_space_product(A,B):\n Astack = np.stack([A]*A.shape[0]).transpose(2,1,0)\n Bstack = np.stack([B]*B.shape[1]).transpose(1,0,2)\n return logsumexp(Astack+Bstack, axis=0)\n\nThe inputs A and B are the logs of th... | [
6,
0
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0036467022_numpy_python.txt |
Q:
torchvision mnist RemoteDisconnected: Remote end closed connection without response
I have a pytorch and mnist error....
Why does this error occur?
RemoteDisconnected: Remote end closed connection without response
import torch
import torchvision.datasets as dsets
import torchvision.transforms as transf... | torchvision mnist RemoteDisconnected: Remote end closed connection without response | I have a pytorch and mnist error....
Why does this error occur?
RemoteDisconnected: Remote end closed connection without response
import torch
import torchvision.datasets as dsets
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
import random
training_epochs = 15
... | [
"when I was run code:\nimport torch\nmodel = torch.hub.load('mateuszbuda/brain-segmentation-pytorch', 'unet',\n in_channels=3, out_channels=1, init_features=32, pretrained=True)\n\nI got similar errors:\n\"\nhttp.client.RemoteDisconnected: Remote end closed connection without response\n\"\nThere are multiple way... | [
0
] | [] | [] | [
"deep_learning",
"mnist",
"python",
"torch",
"torchvision"
] | stackoverflow_0061725300_deep_learning_mnist_python_torch_torchvision.txt |
Q:
Python - find max value
Sort of new and learning Python but I think this is a simple one but I'm having trouble with. I need to find the average of 5 numbers for each row in a column, which I've done and confirmed by going into the csv in excel and checking my numbers. Now I need to return just the max value. I've... | Python - find max value | Sort of new and learning Python but I think this is a simple one but I'm having trouble with. I need to find the average of 5 numbers for each row in a column, which I've done and confirmed by going into the csv in excel and checking my numbers. Now I need to return just the max value. I've tried a few things but can't... | [
"If you want the max of the row (I assume cells 6-10, the same ones you were taking the average of), you need to take the max of those original numbers; it's not possible to get the max from the computed average.\nimport csv\n\ndef no_max(in_file):\n with open(in_file, newline='', encoding='utf-16') as file:\n ... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074409980_python.txt |
Q:
Performing voting for classification tasks
I am wondering is it possible to do voting for classification tasks. I have seen plenty of blogs explaining how to use voting for regression purposes.As given below.
# initializing all the model objects with default parameters
model_1 = LinearRegression()
model_2 = xgb.XG... | Performing voting for classification tasks | I am wondering is it possible to do voting for classification tasks. I have seen plenty of blogs explaining how to use voting for regression purposes.As given below.
# initializing all the model objects with default parameters
model_1 = LinearRegression()
model_2 = xgb.XGBRegressor()
model_3 = RandomForestRegressor()
... | [
"That can be done.\n# initializing all the model objects with default parameters\n\nmodel_1= svm.SVC(kernel='rbf')\nmodel_2 = XGBClassifier()\nmodel_3 = RandomForestClassifier()\n \n# Making the final model using voting classifier\nfinal_model = VotingClassifier(estimators=[('svc', model_1), ('xgb', model_2), ('rf'... | [
2,
1
] | [] | [] | [
"machine_learning",
"python",
"scikit_learn"
] | stackoverflow_0074401221_machine_learning_python_scikit_learn.txt |
Q:
datacompy - How to output report string to an external file or within a cell in Jupyter Notebooks?
I am trying to output a datacompy report to either a cell with Jupyter Notebooks as
print(comparison.report())
OR
Output the report to external s3 File as
import boto3
s3 = boto3.resource('s3')
s3.Object('s3://my... | datacompy - How to output report string to an external file or within a cell in Jupyter Notebooks? | I am trying to output a datacompy report to either a cell with Jupyter Notebooks as
print(comparison.report())
OR
Output the report to external s3 File as
import boto3
s3 = boto3.resource('s3')
s3.Object('s3://my-bucket/myfolder/', 'report.txt').put(Body=open(comparison.report(), 'rb'))
with the same error:
I/O o... | [
"You need to open a valid file pointer first. At first I was concerned that the Spark executors would write to parallel files on each host, but this seemed to work normally:\nwith open(\"/tmp/report\", 'w') as fp:\n compare.report(fp)\n\nwith open(\"/tmp/report\", 'r') as fp:\n for line in fp:\n print(... | [
0
] | [] | [] | [
"amazon_s3",
"jupyter",
"python"
] | stackoverflow_0071921347_amazon_s3_jupyter_python.txt |
Q:
Grid of button objects with row and col attributes using Tkinter. AttributeError: 'Buttons' object has no attribute 'tk'
Making a game like tic tac toe where the board size is adjustable. I need the button's text to change when clicked, so I'm trying to make the buttons objects with row and col attributes. First t... | Grid of button objects with row and col attributes using Tkinter. AttributeError: 'Buttons' object has no attribute 'tk' | Making a game like tic tac toe where the board size is adjustable. I need the button's text to change when clicked, so I'm trying to make the buttons objects with row and col attributes. First time using any GUI so I apologize if I'm going about this all wrong.
import tkinter as tk
from tkinter import*
def create_boar... | [
"I got same issue as your. I found problem in line 25.\nChange this:\nbutton = tk.Button(self, text = \" \")\n\nto:\nbutton = tk.Button(root, text = \" \")\n\nOutput:\n\n"
] | [
0
] | [] | [] | [
"attributeerror",
"python",
"tkinter"
] | stackoverflow_0074406061_attributeerror_python_tkinter.txt |
Q:
Steps to Troubleshoot "django.db.utils.ProgrammingError: permission denied for relation django_migrations"
What are some basic steps for troubleshooting and narrowing down the cause for the "django.db.utils.ProgrammingError: permission denied for relation django_migrations" error from Django?
I'm getting this mess... | Steps to Troubleshoot "django.db.utils.ProgrammingError: permission denied for relation django_migrations" | What are some basic steps for troubleshooting and narrowing down the cause for the "django.db.utils.ProgrammingError: permission denied for relation django_migrations" error from Django?
I'm getting this message after what was initially a stable production server but has since had some changes to several aspects of Dja... | [
"I was able to solve my issue based on instructions from this question. Basically, postgres privileges needed to be re-granted to the db user. In my case, that was the user I had setup in the virtual environment settings file. Run the following from the commandline (or within postgres) where mydatabase and dbuser s... | [
145,
16,
5,
4,
0
] | [] | [] | [
"apache",
"django",
"github",
"postgresql",
"python"
] | stackoverflow_0038944551_apache_django_github_postgresql_python.txt |
Q:
Cleaner Way to Change Dictionary Structure
I have the following object type in python, there are several entries in the data-object just like the one below.
> G1 \
jobname
x [3.3935e-06, 6.099100000000001e-06, 8.804... | Cleaner Way to Change Dictionary Structure | I have the following object type in python, there are several entries in the data-object just like the one below.
> G1 \
jobname
x [3.3935e-06, 6.099100000000001e-06, 8.8048e-06...
y [1, 2, 3, 4, 5, 6, 7, 8, 9,... | [
"You wrote\n def process_data(data, zones:list): \n\nbut Author's Intent was apparently\n def process_data(df, zones:list): \n\n\nAre we writing class methods, which accept a self parameter,\nor are we writing top-level functions here?\n\nThe flatten helper looks good, though PEP-8 asks\nyou to name the forma... | [
1
] | [] | [] | [
"data_structures",
"dataframe",
"pandas",
"parsing",
"python"
] | stackoverflow_0074409768_data_structures_dataframe_pandas_parsing_python.txt |
Q:
Using Scikit-Learn OneHotEncoder with a Pandas DataFrame
I'm trying to replace a column within a Pandas DataFrame containing strings into a one-hot encoded equivalent using Scikit-Learn's OneHotEncoder. My code below doesn't work:
from sklearn.preprocessing import OneHotEncoder
# data is a Pandas DataFrame
jobs_e... | Using Scikit-Learn OneHotEncoder with a Pandas DataFrame | I'm trying to replace a column within a Pandas DataFrame containing strings into a one-hot encoded equivalent using Scikit-Learn's OneHotEncoder. My code below doesn't work:
from sklearn.preprocessing import OneHotEncoder
# data is a Pandas DataFrame
jobs_encoder = OneHotEncoder()
jobs_encoder.fit(data['Profession'].u... | [
"OneHotEncoder Encodes categorical integer features as a one-hot numeric array. Its Transform method returns a sparse matrix if sparse=True, otherwise it returns a 2-d array.\nYou can't cast a 2-d array (or sparse matrix) into a Pandas Series. You must create a Pandas Serie (a column in a Pandas dataFrame) for each... | [
39,
21,
7,
0,
0
] | [] | [] | [
"machine_learning",
"one_hot_encoding",
"pandas",
"python",
"scikit_learn"
] | stackoverflow_0058101126_machine_learning_one_hot_encoding_pandas_python_scikit_learn.txt |
Q:
Amusement park ride reservation
The system allows a rider to reserve a place in line without actually having to wait. The rider simply enters a name into a program to reserve a place. Riders that purchase a VIP pass get to skip past the common riders up to the last VIP rider in line. VIPs board the ride first. (Co... | Amusement park ride reservation | The system allows a rider to reserve a place in line without actually having to wait. The rider simply enters a name into a program to reserve a place. Riders that purchase a VIP pass get to skip past the common riders up to the last VIP rider in line. VIPs board the ride first. (Considering the average wait time for a... | [
"Your dispatch length is always equal to 3, but your list may not contain 3 items, so you need to check it. The following code fixes this:\nriders_per_ride = 3 # Num riders per ride to dispatch\n\nline = [] # The line of riders\nnum_vips = 0 # Track number of VIPs at front of line\n\nmenu = (\n \"(1) Reserve ... | [
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0074410025_list_python.txt |
Q:
How to replace all occurrences of "00000" with "0" repeatedly?
I need to repeatedly replace all occurrence of 00000 with 0 in a binary string input.
Although I'm able to achieve it to some extent, I do not know the logic when there are multiple consecutive 00000s like for example:
25 0s should be replaced with on... | How to replace all occurrences of "00000" with "0" repeatedly? | I need to repeatedly replace all occurrence of 00000 with 0 in a binary string input.
Although I'm able to achieve it to some extent, I do not know the logic when there are multiple consecutive 00000s like for example:
25 0s should be replaced with one 0
50 0s should be replaced with two 0s
125 0s should be replaced w... | [
"As I state in my comment, my best guess at what you're trying to do is that you're trying to repeatedly apply the rule that 50's get replaced with 1, so that, for example, 25 0's get reduced to 00000, which in turn gets reduced to 0. Assuming that's correct:\nIt's not the most efficient approach, but here's one wa... | [
1,
1,
0
] | [] | [] | [
"binary",
"list",
"python",
"regex",
"string"
] | stackoverflow_0074404850_binary_list_python_regex_string.txt |
Q:
How python can execute shell command with env
Basically, os.system() can execute shall commands, such as:
os.system("echo $A")
It will work well and output value environment variable A.
But this seems to not work:
os.system("A=b echo $A")
It won't output "b" as expected.
How Python can execute this type of comma... | How python can execute shell command with env | Basically, os.system() can execute shall commands, such as:
os.system("echo $A")
It will work well and output value environment variable A.
But this seems to not work:
os.system("A=b echo $A")
It won't output "b" as expected.
How Python can execute this type of command command?
| [
"\nIt won't output \"b\" as expected.\n\nThe expansion $A to empty string is done by the shell earlier, before running echo.\nTry this:\nos.system(\"A=b; echo $A\")\n\n"
] | [
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074410106_python_python_3.x.txt |
Q:
unzipping file results in "BadZipFile: File is not a zip file"
I have two zip files, both of them open well with Windows Explorer and 7-zip.
However when i open them with Python's zipfile module [ zipfile.ZipFile("filex.zip") ], one of them gets opened but the other one gives error "BadZipfile: File is not a zip ... | unzipping file results in "BadZipFile: File is not a zip file" | I have two zip files, both of them open well with Windows Explorer and 7-zip.
However when i open them with Python's zipfile module [ zipfile.ZipFile("filex.zip") ], one of them gets opened but the other one gives error "BadZipfile: File is not a zip file".
I've made sure that the latter one is a valid Zip File by ope... | [
"files named file can confuse python - try naming it something else. if it STILL wont work, try this code:\ndef fixBadZipfile(zipFile): \n f = open(zipFile, 'r+b') \n data = f.read() \n pos = data.find('\\x50\\x4b\\x05\\x06') # End of central directory signature \n if (pos > 0): \n self._log(\"Trancating f... | [
22,
13,
13,
4,
3,
3,
2,
2,
1,
1,
0
] | [
"In my case, the zip file was corrupted. I was trying to download the zip file with urllib.request.urlretrieve but the file wouldn't completely download for some reason.\nI connected to a VPN, the file downloaded just fine, and I was able to open the file.\n"
] | [
-2
] | [
"python",
"zip"
] | stackoverflow_0003083235_python_zip.txt |
Q:
Git merge: conflict I don't know how to resolve
I have a Django project on Git
I am not very confortable with Git
I have juste finalized, commit and push my feature/22 branch
I have commit (after git add .) and push my master
So my two branchs are up to date
Now, I would like to merge my master with my feature/22 ... | Git merge: conflict I don't know how to resolve | I have a Django project on Git
I am not very confortable with Git
I have juste finalized, commit and push my feature/22 branch
I have commit (after git add .) and push my master
So my two branchs are up to date
Now, I would like to merge my master with my feature/22 locally but I have an conflict
Even after commit, I h... | [
"You can ignore any /__pycache__/ folder from your project. \n\nIf you don't already have a .gitignore, you can make one right inside of your project folder: project/.gitignore.\nPut */__pycache__/* in the .gitignore\n\n",
"remove those cached file with \nrm -rf <path_of_filename>\n\ntry not to push your code wit... | [
6,
1,
0,
0
] | [] | [] | [
"django",
"git",
"python"
] | stackoverflow_0060623453_django_git_python.txt |
Q:
Hypothesis, using "one_of" with Pandas dtypes in the "data_frames" strategy
I would like to construct a Pandas series that is any of several dtypes.
I was hoping to do something like this:
from hypothesis import given
import hypothesis.strategies as hs
import hypothesis.extra.numpy as hs_np
import hypothesis.extra... | Hypothesis, using "one_of" with Pandas dtypes in the "data_frames" strategy | I would like to construct a Pandas series that is any of several dtypes.
I was hoping to do something like this:
from hypothesis import given
import hypothesis.strategies as hs
import hypothesis.extra.numpy as hs_np
import hypothesis.extra.pandas as hs_pd
import numpy as np
import pandas as pd
import pandera as pda
imp... | [
"This code is failing because the dtype= argument to columns must actually be a dtype, not a strategy to generate dtypes (docs). And unfortunately column objects are a special placeholder object, so you can't st.one_of() those either...\nSolution: build up strategies for each series, put those in a list, and pd.co... | [
1
] | [] | [] | [
"property_based_testing",
"python",
"python_hypothesis"
] | stackoverflow_0074355937_property_based_testing_python_python_hypothesis.txt |
Q:
multi-class classification with f1 score equal to 1
I'm dealing with a multi-class classification, and at the end, for some of the labels, the F1 score and precision and recall are 1 .
Is It normal?
I thought it was odd and searched it out, but the answers were quite different and said it was okay.
As u can see in... | multi-class classification with f1 score equal to 1 | I'm dealing with a multi-class classification, and at the end, for some of the labels, the F1 score and precision and recall are 1 .
Is It normal?
I thought it was odd and searched it out, but the answers were quite different and said it was okay.
As u can see in the pic the accuracy is 88 % and I balanced the data, us... | [
"This means that your model fits the training data perfectly. Is it likely that your data can be predicted to this degree of accuracy?\nAre you using a balanced dataset so that there is enough variance and will your model do well in the real world? Your model may be overfitting.\n"
] | [
0
] | [] | [] | [
"machine_learning",
"precision_recall",
"python"
] | stackoverflow_0074407667_machine_learning_precision_recall_python.txt |
Q:
Get the index of the 5 biggest values in a list
Currently working on a list, and I have to try to get the 5 largest numbers and their indexes. But for some reason, when I run what I thought would give me the 5 largest numbers and their indexes it is not saving the information as I expected it. Here is my code:
# G... | Get the index of the 5 biggest values in a list | Currently working on a list, and I have to try to get the 5 largest numbers and their indexes. But for some reason, when I run what I thought would give me the 5 largest numbers and their indexes it is not saving the information as I expected it. Here is my code:
# Given list
list = [13, 11, 12, 11, 8, 8, 10, 8, 9, 12,... | [
"Here's a modified version of your code that will give you something closer to what you expected, with explanations in line of the changes I've made.\n# First off, \"list\" is a special name in Python and represents the \"type\" list. \n# Therefore it's best not to use \"list\" as a variable name. Suggest \"list1\"... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074410220_python.txt |
Q:
TypeError: string indices must be integers in ElasticSearch
I am following the EalsticSearch tutorial (https://soumilshah1995.blogspot.com/2020/01/getting-started-with-elastic-search-and.html) and I am running into the following error when trying to execute
es.indices.create(index='person', ignore=400)
res1 = es.... | TypeError: string indices must be integers in ElasticSearch | I am following the EalsticSearch tutorial (https://soumilshah1995.blogspot.com/2020/01/getting-started-with-elastic-search-and.html) and I am running into the following error when trying to execute
es.indices.create(index='person', ignore=400)
res1 = es.index(index='person',doc_type='people', body=e1)
res2 = es.index(... | [
"I just upgraded the Elasticsearch to the latest version and changed the formatting of the code to:\nes.indices.create(index='person', ignore=400)\n\nres1 = es.index(index=\"person\", id=1, document=e1)\nres2= es.index(index=\"person\", id=1, document=e1)\n\nprint(\"RES1 : {}\".format(res1))\nprint(\"RES2 : {}\".fo... | [
0
] | [] | [] | [
"elasticsearch",
"python",
"typeerror"
] | stackoverflow_0074410209_elasticsearch_python_typeerror.txt |
Q:
Changing Current Working Directory will not work
First time Python learner here, trying to change the current working directory of my project.
I can retrieve the default working directory, however attempting to change it proves harder.
I've tried all combinations but I keep getting 'None' as a response to my Print... | Changing Current Working Directory will not work | First time Python learner here, trying to change the current working directory of my project.
I can retrieve the default working directory, however attempting to change it proves harder.
I've tried all combinations but I keep getting 'None' as a response to my Print command of the new directory.
No idea what is going o... | [
"That's not how you get the changed directory.\nTry this:\nprint ('----New Run----')\nimport os\ncwd = os.getcwd()\nprint ('Current Working Directory is: ', cwd)\nos.chdir(r'C:\\Users\\danie\\Documents\\Programming\\Python\\Projects\\test')\nprint ('New Working Directory is: ', os.getcwd())\nprint ('----End Run----... | [
3
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074410253_python_python_3.x.txt |
Q:
How to find multiple words in multiple websites using Python?
I have a list of 100+ companies and I want to know if they have specific products, certifications. I have used the code below to count the number 1 specific word in multiple websites (found the code from kind-hearted strangers in stackoverflow). (A) But... | How to find multiple words in multiple websites using Python? | I have a list of 100+ companies and I want to know if they have specific products, certifications. I have used the code below to count the number 1 specific word in multiple websites (found the code from kind-hearted strangers in stackoverflow). (A) But, how can I edit the query the_word to include multiple words?
(B) ... | [
"I suggest using list comprehension (for multiple input) and regex (for pattern/partial matching). Also, since you just want the text, you can use .stripped_strings directly instead .find_all(text...) followed by .strip.\n# import re # for regex\n\n## ENSURE the_word IS A LIST OF [lowercase] STRINGS ##\nif type(the... | [
0
] | [] | [] | [
"beautifulsoup",
"python",
"text_mining",
"web_scraping"
] | stackoverflow_0074409192_beautifulsoup_python_text_mining_web_scraping.txt |
Q:
How to calculate Logits the same way it is done in PyTorch?
Regarding Logits, this is my understanting:
What is a Logit? A Logit function, also known as the log-odds
function, is a function that represents probability values from 0 to
1, and negative infinity to infinity.
source: https://deepai.org/machine-learn... | How to calculate Logits the same way it is done in PyTorch? | Regarding Logits, this is my understanting:
What is a Logit? A Logit function, also known as the log-odds
function, is a function that represents probability values from 0 to
1, and negative infinity to infinity.
source: https://deepai.org/machine-learning-glossary-and-terms/logit
I would like to understand how logit... | [
"A call to Categorical.logits internally makes use of a function called\nprobs_to_logits. Going through the linked code, you can see that torch does not use your definition of a logit; it considers logits to simply be log probabilities.\nYou can confirm this in numpy as well:\n>>> np.log([ 0.1, 0.2, 0.5, 0.2])\na... | [
0
] | [] | [] | [
"python",
"pytorch"
] | stackoverflow_0074401109_python_pytorch.txt |
Q:
Convert spreadsheet number to column letter
I'm looking for the opposite to this Q&A: Convert an excel or spreadsheet column letter to its number in Pythonic fashion.
or this one but in python How to convert a column number (eg. 127) into an excel column (eg. AA)
A:
start_index = 1 # it can start either at 0 ... | Convert spreadsheet number to column letter | I'm looking for the opposite to this Q&A: Convert an excel or spreadsheet column letter to its number in Pythonic fashion.
or this one but in python How to convert a column number (eg. 127) into an excel column (eg. AA)
| [
"start_index = 1 # it can start either at 0 or at 1\nletter = ''\nwhile column_int > 25 + start_index: \n letter += chr(65 + int((column_int-start_index)/26) - 1)\n column_int = column_int - (int((column_int-start_index)/26))*26\nletter += chr(65 - start_index + (int(column_int)))\n\n",
"The xlsxwriter... | [
110,
52,
27,
14,
8,
8,
4,
2,
2,
1,
1,
0,
0,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0023861680_python.txt |
Q:
function with a loop shampoo adjust
Question:
Write a function print_shampoo_instructions() with parameter
num_cycles. If num_cycles is less than 1, print "Too few.". If more
than 4, print "Too many.". Else, print "N : Lather and rinse."
num_cycles times, where N is the cycle number, followed by "Done.".
Sample ... | function with a loop shampoo adjust | Question:
Write a function print_shampoo_instructions() with parameter
num_cycles. If num_cycles is less than 1, print "Too few.". If more
than 4, print "Too many.". Else, print "N : Lather and rinse."
num_cycles times, where N is the cycle number, followed by "Done.".
Sample output with input: 2
1 : Lather and rinse... | [
"Your actually reassigning i outside of the while loop. Inside the loop you're simply printing out i + 1. Instead reassign the counter inside the loop:\nwhile i<num_cycles:\n print (i+1,\": Lather and rinse\")\n i = i + 1\n\n",
"def shampoo_instructions(user_cycles):\n if user_cycles < 1:\n print(... | [
3,
0
] | [] | [] | [
"debugging",
"python",
"python_3.x"
] | stackoverflow_0069856404_debugging_python_python_3.x.txt |
Q:
Pyinstaller .exe file does not open with Face_recognition module in it. (works in .py)
I have wrote a code for face recognition in python.
My code works perfectly in .py file (without any errors or warning), but after making a .exe file out of it, through pyinstaller it won't work at all.
I have searched through, ... | Pyinstaller .exe file does not open with Face_recognition module in it. (works in .py) | I have wrote a code for face recognition in python.
My code works perfectly in .py file (without any errors or warning), but after making a .exe file out of it, through pyinstaller it won't work at all.
I have searched through, for the same and tried the following methods, but it still won't work.
first method i made t... | [
"Solved the above by doing this,\nChanging the data=[] in the main.spec worked for me now I just pasted all this files [('shape_predictor_68_face_landmarks.dat','./face_recognition_models/models'),('shape_predictor_5_face_landmarks.dat','./face_recognition_models/models'),('mmod_human_face_detector.dat','./face_rec... | [
0,
0
] | [] | [] | [
"exe",
"face_recognition",
"hook",
"pyinstaller",
"python"
] | stackoverflow_0067281038_exe_face_recognition_hook_pyinstaller_python.txt |
Q:
How to dynamiclly call SOLID princles following classes
I have a module where I try to follow the SOLID principles to create and generate data and I think the following is based around the Liskov Substitution Principle:
class BaseLoader(ABC):
def __init__(self, dataset_name='mnist'):
self.dataset_name... | How to dynamiclly call SOLID princles following classes | I have a module where I try to follow the SOLID principles to create and generate data and I think the following is based around the Liskov Substitution Principle:
class BaseLoader(ABC):
def __init__(self, dataset_name='mnist'):
self.dataset_name=dataset_name
class MNISTLoader(BaseLoader):
def load(... | [
"I wouldn't say this has much to do with LSP since both classes inherit only from an abstract base class that never gets instantiated. You are simply sharing a dataset_name member of the base class to reduce code duplication. And forget about the default value in argument dataset_name='mnist' it has no point the wa... | [
1
] | [] | [] | [
"python",
"solid_principles"
] | stackoverflow_0074306403_python_solid_principles.txt |
Q:
How can I change element of numpy array manually?
Following is my numpy array.
import numpy as np
arr = np.array([1,2,3,4,5])
arrc=arr
arrc[arr<3]=3
When I run
>>> arrc
output : array([3,3,3,4,5])
>>> arr
output : array([3,3,3,4,5])
I expected changing arrc does not affect arr. However, both array is changing.... | How can I change element of numpy array manually? | Following is my numpy array.
import numpy as np
arr = np.array([1,2,3,4,5])
arrc=arr
arrc[arr<3]=3
When I run
>>> arrc
output : array([3,3,3,4,5])
>>> arr
output : array([3,3,3,4,5])
I expected changing arrc does not affect arr. However, both array is changing. In my actual code I am changing arrc multiple times so... | [
"Simply, just index the element and set the value.\na[1,2] = \"some value\"\n\n",
"You have to .copy() when you copy array values. Otherwise, it is the same reference you update with both variables.\nUse:\narrc = arr.copy()\n\n"
] | [
1,
0
] | [] | [] | [
"arrays",
"numpy",
"python"
] | stackoverflow_0074410270_arrays_numpy_python.txt |
Q:
split on delimeter and ignore a pattern
I would like to split a string based on a delimiter and ignore a particular pattern. I have lines in a text file that look like so
"ABC | 0 | 567 | my name is | however
TQD | 0 | 567 | my name is | but
GED | 0 | 567 | my name is | haha"""
I would like to split on "|" ... | split on delimeter and ignore a pattern | I would like to split a string based on a delimiter and ignore a particular pattern. I have lines in a text file that look like so
"ABC | 0 | 567 | my name is | however
TQD | 0 | 567 | my name is | but
GED | 0 | 567 | my name is | haha"""
I would like to split on "|" but ignore 0 and 567 and grab the rest. i.e
... | [
"To include the | specific numbers | in the split sequence:\npattern = re.compile(r' *\\|(?: *(?:0|567) *\\|)* *')\n\nSee this demo at regex101 or a Python demo at tio.run\n\nThe (?: non capturing groups ) is repeated * any amount of times.\n"
] | [
3
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0074410206_python_regex.txt |
Q:
jinja2.exceptions.TemplateSyntaxError: Encountered unknown tag 'else'
Iam trying to test the recommender with some random values which are not present in the list. My else part is not working and keeps throwing me an error
Can you please help how do fix the else part?
A:
{% if %}
{% for %} ... {% endfor %}
{... | jinja2.exceptions.TemplateSyntaxError: Encountered unknown tag 'else' |
Iam trying to test the recommender with some random values which are not present in the list. My else part is not working and keeps throwing me an error
Can you please help how do fix the else part?
| [
"{% if %}\n {% for %} ... {% endfor %}\n{% endif %}\n{% else %}\n\nhas the else out of order. But for what you're trying to do, https://jinja.palletsprojects.com/en/3.0.x/templates/#for shows an option that will do what you want.\n"
] | [
0
] | [] | [] | [
"jinja2",
"python"
] | stackoverflow_0074410248_jinja2_python.txt |
Q:
if statement homework error, how do i fix it?
I have some intro to python homework I can't seem to get right.
The question is : "Write a program to determine how much to tip the server in a restaurant. The tip should be 15% of the check, with a minimum of $2." And the hint suggested to use "if" statement.
This is... | if statement homework error, how do i fix it? | I have some intro to python homework I can't seem to get right.
The question is : "Write a program to determine how much to tip the server in a restaurant. The tip should be 15% of the check, with a minimum of $2." And the hint suggested to use "if" statement.
This is what I've got so far but I get an error '>' not su... | [
"input() returns a string. Therefore Bill is a string, and you cannot compare strings to numbers.\nYou can convert the input value to a floating-point value using float(), like this:\nBill = float(input(\"Enter bill amount\"))\n\n"
] | [
0
] | [] | [] | [
"if_statement",
"printing",
"python",
"python_2.7",
"string"
] | stackoverflow_0074410329_if_statement_printing_python_python_2.7_string.txt |
Q:
Rounding cmath complex numbers?
I have instances in my code where two complex numbers (using the cmath module) that should be exactly the same, do not cancel out due to the floating point precision of the base 2 system causing the numbers to deviate from each other by a small difference in value at some nth decima... | Rounding cmath complex numbers? | I have instances in my code where two complex numbers (using the cmath module) that should be exactly the same, do not cancel out due to the floating point precision of the base 2 system causing the numbers to deviate from each other by a small difference in value at some nth decimal place.
If they were floating number... | [
"\"round\" does not work directly on complex numbers, but it does work separately on the real resp. imaginary part of the number, e.g. rounding on 4 digits:\nx = 0.6538461538461539-0.2692307692307693j\nx_real = round(x.real, 4)\nx_imag = round(x.imag, 4)\nx = x_real + x_imag * 1j\n\n",
"Numpy is defacto for numer... | [
1,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0033211796_python_python_3.x.txt |
Q:
How to generate a random 0's and 1's Matrix in which the sum of each row equals 10 in python
How can I generate a Random (N*M) 0's and 1's Matrix in which the sum of each row equals to 10?
(in python using numpy)
for example for 10*10(N*M) matrix we can use:
import numpy as np
np.random.randint(2, size=(10, 10))
... | How to generate a random 0's and 1's Matrix in which the sum of each row equals 10 in python | How can I generate a Random (N*M) 0's and 1's Matrix in which the sum of each row equals to 10?
(in python using numpy)
for example for 10*10(N*M) matrix we can use:
import numpy as np
np.random.randint(2, size=(10, 10))
but I want sum of each rows equals to 10
| [
"This isn't necessarily the most efficient method, but it is concise:\nIn [29]: rng = np.random.default_rng(121263137472525314065)\n\nIn [30]: n_rows = 5\n\nIn [31]: n_cols = 20\n\nIn [32]: n_ones = 10\n\nIn [33]: rng.multivariate_hypergeometric([1]*n_cols, n_ones, size=n_rows)\nOut[33]: \narray([[0, 0, 0, 1, 0, 0,... | [
3,
1,
0,
0
] | [] | [] | [
"matrix",
"numpy",
"python",
"random"
] | stackoverflow_0074410011_matrix_numpy_python_random.txt |
Q:
why I can't print one by one in the python list?
allData = []
tanggaldata= []
while True:
name = input("input your name (if done input DONE) : ")
tanggal = input("input your date (if done input DONE) : ")
if name == "DONE" or tanggal == "DONE":
break
elif name != "DONE":
allData.app... | why I can't print one by one in the python list? |
allData = []
tanggaldata= []
while True:
name = input("input your name (if done input DONE) : ")
tanggal = input("input your date (if done input DONE) : ")
if name == "DONE" or tanggal == "DONE":
break
elif name != "DONE":
allData.append(name)
tanggaldata.append(tanggal)
... | [
"You are printing doubles because you have a loop inside of a loop. You don't need the second loop\nfor tanggaldatas in tanggaldata :\n\nFor every person you are already getting a name and date so there will always be the same amount of both. Instead use a for loop with a counter till the length one of the arrays s... | [
0
] | [] | [] | [
"arrays",
"jupyter_notebook",
"list",
"python",
"python_3.x"
] | stackoverflow_0074410359_arrays_jupyter_notebook_list_python_python_3.x.txt |
Q:
convert list of tuple into dictionary python
[(
The word ‘Women Empowerment’ itself implies that women are not powerful enough - they need to be empowered., 0.125), (This painful truth has been in existence for a long long time., 0.16666666666666666), (It is in recent years that noticeable work started beginning t... | convert list of tuple into dictionary python | [(
The word ‘Women Empowerment’ itself implies that women are not powerful enough - they need to be empowered., 0.125), (This painful truth has been in existence for a long long time., 0.16666666666666666), (It is in recent years that noticeable work started beginning to lift women out of the abyss of insignificance an... | [
"If you have a list of two-element tuples, then you can pass that list as an argument to dict() and it will construct the dictionary for you:\nmydict = dict(list_of_tuples)\n\n"
] | [
2
] | [] | [] | [
"python"
] | stackoverflow_0074410405_python.txt |
Q:
Why can't Python 3 virtualenv find some installed packages?
I am working with a Python virtualenv named env to execute Odoo. In the virtualenv bin directory, I got this:
pip
pip3
pip3.8
python -> /usr/bin/python3
python3 -> python
python3.8 -> python
And the Odoo service is running this command to execute Odoo (... | Why can't Python 3 virtualenv find some installed packages? | I am working with a Python virtualenv named env to execute Odoo. In the virtualenv bin directory, I got this:
pip
pip3
pip3.8
python -> /usr/bin/python3
python3 -> python
python3.8 -> python
And the Odoo service is running this command to execute Odoo (as you can see, using the python3.8 of the virtualenv):
ExecStart... | [
"Odoo 13 is not compatible with the Python 3.8 version. You can try with Python 3.7 or 3.6 versions. Anyway, many issues have been fixed, so I am not sure about the Python 3.8 incompatibility. But, in principle, the branch Odoo v13 was created for Python 3.6, as you can check in the setup.py file\nIf the problem st... | [
0,
0,
0
] | [] | [] | [
"odoo",
"odoo_13",
"python",
"python_3.x",
"virtualenv"
] | stackoverflow_0070154013_odoo_odoo_13_python_python_3.x_virtualenv.txt |
Q:
AWS sam build not building lambda functions
I'm new to building with AWS SAM. When I execute sam build it shows build succeeded but I don't see my function in the build directory.
This is my directory structure
Folder PATH listing for volume Code
Volume serial number is B243-6647
D:.
ª .gitignore
ª template.ya... | AWS sam build not building lambda functions | I'm new to building with AWS SAM. When I execute sam build it shows build succeeded but I don't see my function in the build directory.
This is my directory structure
Folder PATH listing for volume Code
Volume serial number is B243-6647
D:.
ª .gitignore
ª template.yaml
ª tree.txt
ª
+---.aws-sam
ª ª build.t... | [
"I was almost doing everything right. Just needed to add Type outside Properties :/\nUpdated template.yaml\nAWSTemplateFormatVersion: '2010-09-09'\nTransform: AWS::Serverless-2016-10-31\nDescription: Url Shortener\n\nGlobals:\n Function:\n Handler: index.handler\n Runtime: python3.9\n\nResources:\n HelloWor... | [
0
] | [] | [] | [
"amazon_cloudformation",
"amazon_web_services",
"aws_lambda",
"aws_sam",
"python"
] | stackoverflow_0074410062_amazon_cloudformation_amazon_web_services_aws_lambda_aws_sam_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.