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:
Multiple variables in an 'async with' statement?
Is is possible to create multiple variables in an async with statement ?
I know that the equivalent synchronous version exists from here: Multiple variables in a 'with' statement?
so the synchronous version looks like this:
# some files
f1 = 'tests/test_csv.csv'
f2 ... | Multiple variables in an 'async with' statement? | Is is possible to create multiple variables in an async with statement ?
I know that the equivalent synchronous version exists from here: Multiple variables in a 'with' statement?
so the synchronous version looks like this:
# some files
f1 = 'tests/test_csv.csv'
f2 = 'tests/some_file.txt'
f3 = ''
with open(f1) as a, ... | [
"Yes, it's allowed. The documentation says that the syntax of async with is the same as with, but with the keyword async before it.\nThe specification of with says that listing multiple items is equivalent to nesting them. So your code would be equivalent to:\nasync with A() as a\n async with B() as b:\n ... | [
0
] | [] | [] | [
"async_with",
"asynchronous",
"python"
] | stackoverflow_0074307415_async_with_asynchronous_python.txt |
Q:
Django: Match two models by same field they have
I have 2 models. User model
class User(TimeStampedModel):
phone_number = models.CharField(
_('Phone number'),
null=True,
blank=True,
max_length=30,
)
reservations = models.ManyToManyField(
'Reservation',
re... | Django: Match two models by same field they have | I have 2 models. User model
class User(TimeStampedModel):
phone_number = models.CharField(
_('Phone number'),
null=True,
blank=True,
max_length=30,
)
reservations = models.ManyToManyField(
'Reservation',
related_name='Users',
verbose_name=_('Reservatio... | [
"# retrieving the first reservation\n# You can use .get(id=xxx) instead of first\n# if you want to use an specific reservation\nreservation = Reservation.objects.first()\n# Get the first user related with the reservation\nreservation.Users.first()\n\nI recommend that you add unique=True to phone_number in the User ... | [
0
] | [] | [] | [
"django",
"django_models",
"django_rest_framework",
"python"
] | stackoverflow_0074306980_django_django_models_django_rest_framework_python.txt |
Q:
How pull a docker image and give it a diferente name?
I need pull a docker image of tensorflow.
I know that for pull a image i have to use this commmand:
docker pull tensorflow/tensorflow:2.4.3
But i dont want my image with this name:
tensorflow/tensorflow:2.4.3
How can i change this name in the moment that i pu... | How pull a docker image and give it a diferente name? | I need pull a docker image of tensorflow.
I know that for pull a image i have to use this commmand:
docker pull tensorflow/tensorflow:2.4.3
But i dont want my image with this name:
tensorflow/tensorflow:2.4.3
How can i change this name in the moment that i pull it ?
| [
"The location you pulled it from and the name are tightly coupled. So you can retag after pulling:\ndocker pull tensorflow/tensorflow:2.4.3\ndocker tag tensorflow/tensorflow:2.4.3 yourid/tensorflow:2.4.3\n\nOtherwise, you'd need to pull the image from outside of docker and side load the image, but that's really mor... | [
2,
1
] | [] | [] | [
"docker",
"python"
] | stackoverflow_0070531871_docker_python.txt |
Q:
Can I have same functionality as re.findall() without using any module directly in python?
My task is to use automata theory for autocorrect text. All my references show the use of re.findall() for the purpose of finding matches. Can I recreate the functionality without using any library directly. I am allowed to ... | Can I have same functionality as re.findall() without using any module directly in python? | My task is to use automata theory for autocorrect text. All my references show the use of re.findall() for the purpose of finding matches. Can I recreate the functionality without using any library directly. I am allowed to use different function form different libraries.
I am expecting something like source code for f... | [
"CPython is open source. The sourcecode for the re package is on github.\n"
] | [
0
] | [] | [] | [
"autocorrect",
"nlp",
"python",
"python_re"
] | stackoverflow_0074307559_autocorrect_nlp_python_python_re.txt |
Q:
How to scrap href information for a product, but only if the product is in stock?
I'm trying to scrape a list of products of products on the following page: https://www.beermerchants.com/browse/brewery/cantillon , however I only want to print products that are in stock. I've been able to scrape the full list of pr... | How to scrap href information for a product, but only if the product is in stock? | I'm trying to scrape a list of products of products on the following page: https://www.beermerchants.com/browse/brewery/cantillon , however I only want to print products that are in stock. I've been able to scrape the full list of products with the following code, however how can I modify this so that this is only true... | [
"I have adapted your code to use xpath, in order to add more complex logic.\nI've checked the products that can be added to cart (meaning they are in stock)\nimport ssl\nimport requests\nimport sys\n\nimport time\nimport smtplib\nfrom email.message import EmailMessage\nimport hashlib\nfrom urllib.request import url... | [
0,
0
] | [] | [] | [
"beautifulsoup",
"python",
"web_scraping"
] | stackoverflow_0074307336_beautifulsoup_python_web_scraping.txt |
Q:
Renaming files in a folder with pathlib and for loops
I've written the following renaming tool in Python. It was unintentionally moving all my files to a single directory until I added the os.chdir in my for loop, which then made it work better and keep each renamed file inside its correct folder. But I don't rea... | Renaming files in a folder with pathlib and for loops | I've written the following renaming tool in Python. It was unintentionally moving all my files to a single directory until I added the os.chdir in my for loop, which then made it work better and keep each renamed file inside its correct folder. But I don't really understand the logic behind why this script, without th... | [
"I would assume this is because it was renaming the files to your current working directory (ie wherever you saved the script) rather than the actual directory where the files were stored.\nfile = your/file/name.txt\nos.path.dirname(file) # This gives 'your/file'\nos.path.basename(your/file) # This gives 'file'\n\n... | [
1,
0
] | [] | [] | [
"chdir",
"path",
"pathlib",
"python",
"rename"
] | stackoverflow_0063580938_chdir_path_pathlib_python_rename.txt |
Q:
Fill Word Merge Fields from dataset using Python
I am trying to fill a Word template that contains 10 Merge Fields on one single page ("guest_1", ..., "guest_10") with a column from a dataset. The template can be found here: https://file.io/GVO4hyOwBCiv
I was able to fill the Word template with constant data using... | Fill Word Merge Fields from dataset using Python | I am trying to fill a Word template that contains 10 Merge Fields on one single page ("guest_1", ..., "guest_10") with a column from a dataset. The template can be found here: https://file.io/GVO4hyOwBCiv
I was able to fill the Word template with constant data using the docx-mailmerge package (see below in the code # T... | [
"I found the solution:\n# Import packages\nfrom natsort import natsorted\nimport os\n\nfrom mailmerge import MailMerge\nimport pandas as pd\n\n# Split dataframe into chunks of up to 10 rows - adapted from: https://stackoverflow.com/a/28882020/9195104\ndef split_dataframe(df, chunk_size=10000):\n\n chunks = list(... | [
0
] | [] | [] | [
"mailmerge",
"python"
] | stackoverflow_0074296988_mailmerge_python.txt |
Q:
ModuleNotFoundError: No module named 'requests' using venv in vscode
I have 1 file, i get as far as line 1 import requests, nothing more yet and I receive the following error ModuleNotFoundError: No module named 'requests'.
Using Visual Studio Code, installed today with standalone Python x64 3.7.4
Python Extensi... | ModuleNotFoundError: No module named 'requests' using venv in vscode | I have 1 file, i get as far as line 1 import requests, nothing more yet and I receive the following error ModuleNotFoundError: No module named 'requests'.
Using Visual Studio Code, installed today with standalone Python x64 3.7.4
Python Extension installed in VSCODE
venv created within VSCODE as a subfolder of worksp... | [
"try get python version in vscode terminal \npython --version\n\nand check python version vscode IDE used by clicking left buttom corner.\n\nmake sure these 2 versions are consistent. if not, select the version of IDE with the same version of your terminal.\n",
"Have you checked your user and workspace settings?... | [
5,
4,
1,
1,
0,
0
] | [] | [] | [
"python",
"python_requests",
"virtual_environment",
"visual_studio_code"
] | stackoverflow_0058160360_python_python_requests_virtual_environment_visual_studio_code.txt |
Q:
selecting a df row by month formatted with (lambda x: datetime.datetime.strptime(x, '%Y-%m-%dT%H:%M:%S%z'))
I'm having some issues with geopandas and pandas datetime objects; I kept getting the error
pandas Invalid field type <class 'pandas._libs.tslibs.timedeltas.Timedelta'>
when I try to save it using gpd.to_fi... | selecting a df row by month formatted with (lambda x: datetime.datetime.strptime(x, '%Y-%m-%dT%H:%M:%S%z')) | I'm having some issues with geopandas and pandas datetime objects; I kept getting the error
pandas Invalid field type <class 'pandas._libs.tslibs.timedeltas.Timedelta'>
when I try to save it using gpd.to_file() apparently this is a known issue between pandas and geopandas date types so I used
df.DATE = df.DATE.apply(l... | [
"The statement df.DATE returns a Series object. That doesn't have a .month attribute. The dates inside the Series do, which is why row.DATE.month works. Try something like:\nfilter = [x.month == month for x in df.DATE]\ndf_filtered = df[filter]\n\nBefore that, I'm not sure what you're trying to accomplish with pd.D... | [
2
] | [] | [] | [
"geopandas",
"pandas",
"python"
] | stackoverflow_0074307597_geopandas_pandas_python.txt |
Q:
Need To Remove First And Last \n From DataFrame Text
Let's say I have the following data frame:
"\n mark has \n no name",
"\n john walks his \n dog",
"mary is fun \n",
"tim is \n old"
data = [
"\n mark has \n no name",
"\n john walks his \n dog",
"mary is fun \n",
"tim is \n old"
]
df = pd.DataFr... | Need To Remove First And Last \n From DataFrame Text | Let's say I have the following data frame:
"\n mark has \n no name",
"\n john walks his \n dog",
"mary is fun \n",
"tim is \n old"
data = [
"\n mark has \n no name",
"\n john walks his \n dog",
"mary is fun \n",
"tim is \n old"
]
df = pd.DataFrame(data, columns=['Sentences'])
How can I write a functi... | [
"It's not a lambda, but the below code seems to fit the bill. The basic approach is to iterate through the dataframe, row by row, and test each string for whether it starts or ends with \\n, then use string indices to return a string that doesn't have that character.\nimport pandas as pd\n\ndata = [\"\\n mark has \... | [
-2
] | [
"df['fixed'] = df.Sentences.str.strip(\"\\n\")\n\nor, in case you want more granular control over what to strip on the left / right:\ndf['fixed'] = df.Sentences.str.lstrip(\"\\n\").str.rstrip(\"\\n\")\n\npandas has Vectorized string functions for Series, so you can do colum.str, then apply common string methods suc... | [
-1
] | [
"lambda",
"python"
] | stackoverflow_0074307131_lambda_python.txt |
Q:
Simple argparse example wanted: 1 argument, 3 results
The documentation for the argparse python module, while excellent I'm sure, is too much for my tiny beginner brain to grasp right now. I don't need to do math on the command line or meddle with formatting lines on the screen or change option characters. All I w... | Simple argparse example wanted: 1 argument, 3 results | The documentation for the argparse python module, while excellent I'm sure, is too much for my tiny beginner brain to grasp right now. I don't need to do math on the command line or meddle with formatting lines on the screen or change option characters. All I want to do is "If arg is A, do this, if B do that, if none o... | [
"Here's the way I do it with argparse (with multiple args):\nparser = argparse.ArgumentParser(description='Description of your program')\nparser.add_argument('-f','--foo', help='Description for foo argument', required=True)\nparser.add_argument('-b','--bar', help='Description for bar argument', required=True)\nargs... | [
446,
307,
238,
65,
28,
13,
13,
11,
5,
4,
3,
3,
1,
0,
0,
0
] | [
"The simplest answer! \nP.S. the one who wrote the document of argparse is foolish\npython code:\nimport argparse\nparser = argparse.ArgumentParser(description='')\nparser.add_argument('--o_dct_fname',type=str)\nparser.add_argument('--tp',type=str)\nparser.add_argument('--new_res_set',type=int)\nargs = parser.parse... | [
-1
] | [
"argparse",
"python"
] | stackoverflow_0007427101_argparse_python.txt |
Q:
Python Window Activation
How would I programmatically activate a window in Windows using Python? I'm sending keystrokes to it and at the moment I'm just making sure it's the last application used then sending the keystroke Alt+Tab to switch over to it from the DOS console. Is there a better way (since I've learned... | Python Window Activation | How would I programmatically activate a window in Windows using Python? I'm sending keystrokes to it and at the moment I'm just making sure it's the last application used then sending the keystroke Alt+Tab to switch over to it from the DOS console. Is there a better way (since I've learned by experience that this way i... | [
"You can use the win32gui module to do that. First you need to get a valid handle on your window. You can use the win32gui.FindWindow if you know the window class name or the exact title. If not, you can enumerate the windows with the win32gui.EnumWindows and try to find the right one.\nOnce you have the handle, yo... | [
57,
8,
2,
1,
0,
0,
0
] | [] | [] | [
"python",
"windows"
] | stackoverflow_0002090464_python_windows.txt |
Q:
Python pandas merge map with multiple values xlookup
I have a dataframe of actor names:
df1
actor_id actor_name
1 Brad Pitt
2 Nicole Kidman
3 Matthew Goode
4 Uma Thurman
5 Ethan Hawke
And another dataframe of movies that the actors were in:
df2
actor_id actor_movie movie_revenue_m
1 Once Upon a ... | Python pandas merge map with multiple values xlookup | I have a dataframe of actor names:
df1
actor_id actor_name
1 Brad Pitt
2 Nicole Kidman
3 Matthew Goode
4 Uma Thurman
5 Ethan Hawke
And another dataframe of movies that the actors were in:
df2
actor_id actor_movie movie_revenue_m
1 Once Upon a Time in Hollywood 150
2 The Others 50
2 Moulin Roug... | [
"One way is to continue with the merge and then filter the result set\nmovie title that is alphabetically first\n# sort by name, movie and then pick the first while grouping by actor\ndf.sort_values(['actor_name','actor_movie'] ).groupby('actor_id', as_index=False).first()\n\n actor_id actor_name actor_movie... | [
1
] | [] | [] | [
"merge",
"pandas",
"python",
"xlookup"
] | stackoverflow_0074307506_merge_pandas_python_xlookup.txt |
Q:
Plot a vertical line using datetime.time and axvline
I am trying to use the axvline function to plot datetime.time values and seeing this error. please help.
Here is the code:
import datetime as dt
from datetime import datetime
import matplotlib.pyplot as plt
i='wpt'
x = [datetime.time(12,10), datetime.time(1... | Plot a vertical line using datetime.time and axvline | I am trying to use the axvline function to plot datetime.time values and seeing this error. please help.
Here is the code:
import datetime as dt
from datetime import datetime
import matplotlib.pyplot as plt
i='wpt'
x = [datetime.time(12,10), datetime.time(12, 15)]
fig, axs = plt.subplots(3, sharex = True, figsize... | [
"matplotlib expects a numeric x coordinate, not a datetime object.\nYou need to convert the time to a number, e.g. by using the matplotlib.dates.date2num function:\nimport matplotlib.dates as mdates\n\naxs[i].axvline(mdates.date2num(datetime.combine(date.today(), x[0])), ...)\n\nThis will convert the time to a floa... | [
0
] | [] | [] | [
"datetime",
"matplotlib",
"python"
] | stackoverflow_0074306978_datetime_matplotlib_python.txt |
Q:
Read/Write Local JSON file using Python File executed by GitHub Actions Workflow
I have a python script that reads in a json file and outputs an updated json file under the same name.
This script executes when running on my local machine, but when the script is executed by GitHub Actions Workflow file it
(1) can ... | Read/Write Local JSON file using Python File executed by GitHub Actions Workflow | I have a python script that reads in a json file and outputs an updated json file under the same name.
This script executes when running on my local machine, but when the script is executed by GitHub Actions Workflow file it
(1) can not load the file
(2) Does not error when writing the file but there is no outputted ... | [
"Is your json version-controlled? if its not, and because github workers are ephemeral, initially the json won't exist, meaning you should be getting a filenotfounderror. If this is the case, just protect against it:\nimport json\n\n# get file\ntry:\n existing_file = json.load(open('example.json'))\nexcept FileN... | [
0
] | [] | [] | [
"github",
"json",
"python"
] | stackoverflow_0074307128_github_json_python.txt |
Q:
python call-back for python module segments
I am writing a python module for using a c++ lib, which uses call-backs. (asyn calls)
1: passing python function as below
Py_XINCREF(cb_p);
if(!PyArg_ParseTuple(args, "ky#O",
316 &hdl,
317 &(buf_p), &(buflen),
318 ... | python call-back for python module segments | I am writing a python module for using a c++ lib, which uses call-backs. (asyn calls)
1: passing python function as below
Py_XINCREF(cb_p);
if(!PyArg_ParseTuple(args, "ky#O",
316 &hdl,
317 &(buf_p), &(buflen),
318 &(cb_p->ctrl_cb))) {
;
;
;
P... | [
"figured out, the issue is the call-backs on different thread. doing the following addresses it.\nPyGILState_STATE state = PyGILState_Ensure();\nPyObject_CallObject(cb_p->ctrl_cb, arglist);\nPyGILState_Release(state);\n"
] | [
0
] | [] | [] | [
"callback",
"cpython",
"python"
] | stackoverflow_0074280166_callback_cpython_python.txt |
Q:
How to find branch point from binary skeletonize image
I use Python OpenCV to skeletonize an image like this:
and I want to find the branch point of the skeleton
I have no idea how to do it. Any thoughts?
A:
This question is already quite old but if anyone else stumbles across this and would like to have an an... | How to find branch point from binary skeletonize image | I use Python OpenCV to skeletonize an image like this:
and I want to find the branch point of the skeleton
I have no idea how to do it. Any thoughts?
| [
"This question is already quite old but if anyone else stumbles across this and would like to have an answer that does not rely on additional packages and uses simple morphological operations you might find the following helpful.\nThe idea is simply to apply a hit-or-miss transform to search for pixels that satisfy... | [
4,
1,
1,
0
] | [
"Output (overlaid on input image): \n\nCode: \n#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nFind branch point in example image.\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mahotas.morph import hitmiss as hit_or_miss\nfrom skimage.morphology import medial_axis as skeletonize\n# ... | [
-1
] | [
"computer_vision",
"image_processing",
"opencv",
"python",
"python_2.7"
] | stackoverflow_0043037692_computer_vision_image_processing_opencv_python_python_2.7.txt |
Q:
python nested dict reorganization to list
Do you know if there is a quick method to do the following dictionary transformation? (without looping through dict's keys and construct it from scratch)
From this nested python dictionary:
{
"demographicAll": {
"allAges": {
"rating": "8.8",
... | python nested dict reorganization to list | Do you know if there is a quick method to do the following dictionary transformation? (without looping through dict's keys and construct it from scratch)
From this nested python dictionary:
{
"demographicAll": {
"allAges": {
"rating": "8.8",
"votes": "2327099"
},
"age... | [
"The best I was able to do (it still loops through the dictionary inside the list comprehension) is:\nmydict = {\n \"demographicAll\": {\n \"allAges\": {\n \"rating\": \"8.8\",\n \"votes\": \"2327099\"\n },\n \"agesUnder18\": {\n \"rating\": \"9.0\",\n ... | [
0
] | [] | [] | [
"dictionary",
"nested",
"python",
"python_3.x",
"transformation"
] | stackoverflow_0074307624_dictionary_nested_python_python_3.x_transformation.txt |
Q:
AttributeError with openpyxl
I'm trying to read an Excel workbook into a three-dimensional array ([worksheet][column][cell]) but I'm getting an error with openpyxl (v2.5.0a2) that looks like it contradicts the online documentation.
The documentation for the worksheet module clearly states that there's a 'columns' ... | AttributeError with openpyxl | I'm trying to read an Excel workbook into a three-dimensional array ([worksheet][column][cell]) but I'm getting an error with openpyxl (v2.5.0a2) that looks like it contradicts the online documentation.
The documentation for the worksheet module clearly states that there's a 'columns' attribute (and I've seen examples ... | [
"Solved it, for future reference it doesn't look like the 'ReadOnlyWorksheet' object does contain a 'column' attribute (which is strange). Removing the read only argument to load_workbook solved the issue.\n",
"Little elaboration. Changing to False fix my issue\nOld\nopenpyxl.load_workbook(filename=self.students_... | [
8,
0
] | [] | [] | [
"openpyxl",
"python"
] | stackoverflow_0045220078_openpyxl_python.txt |
Q:
Uvicorn --reload using WatchFiles is not working for FastAPI in Docker container
I am developing a FastAPI app. It is running on Uvicorn in a Docker container using docker-compose.
I want to include some files other than *.py to trigger the auto reload while in development.
According to the docs Uvicorn needs the ... | Uvicorn --reload using WatchFiles is not working for FastAPI in Docker container | I am developing a FastAPI app. It is running on Uvicorn in a Docker container using docker-compose.
I want to include some files other than *.py to trigger the auto reload while in development.
According to the docs Uvicorn needs the optional dependency WatchFiles installed to be able to use the --reload-include flag, ... | [
"I just had the same problem and the problem is with WatchFiles.\nIn the watchfiles documentation it is understood that the detection relies on file system notifications, and I think that via docker its events are not launched when using a volume.\n\nNotify will fall back to file polling if it can't use file system... | [
2
] | [] | [] | [
"docker",
"docker_compose",
"fastapi",
"python",
"uvicorn"
] | stackoverflow_0073966627_docker_docker_compose_fastapi_python_uvicorn.txt |
Q:
the background color of my program is only visable when I close the app icon
I have an app icon open but I can' see a white background in my application window untill I close the app. What do I do?
import pygame
# Internationalizing Pygame
pygame.init()
# Title and Icon
pygame.display.set_caption("Space Invaders... | the background color of my program is only visable when I close the app icon | I have an app icon open but I can' see a white background in my application window untill I close the app. What do I do?
import pygame
# Internationalizing Pygame
pygame.init()
# Title and Icon
pygame.display.set_caption("Space Invaders")
icon = pygame.image.load()
pygame.display.set_icon(icon)
# player
playerIMG = ... | [
"It is a matter of Indentation you have to draw the scene and update the display in the application loop:\nrunning = True\nwhile running: # RGB\n screen.fill((222, 222, 222))\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n\n# INDENTATION\n#-->|\n ... | [
0
] | [] | [] | [
"game_development",
"pygame",
"python"
] | stackoverflow_0074307891_game_development_pygame_python.txt |
Q:
How do I get Celery to execute in production on Heroku?
I'm using Celery on my Django app.
I can't get the celery task to execute unless I run celery -A appname worker -l info --pool=solo in the terminal.
How do I get it execute when the site is in production?
A:
You need to add a worker process to your Procfile... | How do I get Celery to execute in production on Heroku? | I'm using Celery on my Django app.
I can't get the celery task to execute unless I run celery -A appname worker -l info --pool=solo in the terminal.
How do I get it execute when the site is in production?
| [
"You need to add a worker process to your Procfile, e.g.\nweb: gunicorn some_app.wsgi\nworker: celery -A appname worker -l info --pool solo\n\nAfter redeploying, scale up one or more workers, e.g. by running\nheroku ps:scale worker=1\n\n"
] | [
2
] | [] | [] | [
"celery",
"django",
"heroku",
"postgresql",
"python"
] | stackoverflow_0074304793_celery_django_heroku_postgresql_python.txt |
Q:
How to remove points from a dataframe based on a selected area on a plot
I have some experimental data that is often flawed with artifacts exemplified with something like this:
I need a quick way to manually select these random spikes and remove them from datasets.
I figured that any plotting library with a focus... | How to remove points from a dataframe based on a selected area on a plot | I have some experimental data that is often flawed with artifacts exemplified with something like this:
I need a quick way to manually select these random spikes and remove them from datasets.
I figured that any plotting library with a focus on interactive plots should have an easy way to do this but so far I keep str... | [
"I suggest to use Holoviews and Panel.\nThey are high level visualization tools that facilitate the creation and control of low level bokeh, matplotlib or plotly figures.\nHere are an example:\nimport panel as pn\nimport holoviews as hv \nimport pandas as pd\nfrom bokeh.models import ColumnDataSource\n\n# This exam... | [
1
] | [] | [] | [
"ipywidgets",
"plotly",
"python"
] | stackoverflow_0074282494_ipywidgets_plotly_python.txt |
Q:
How to find IoU from segmentation masks?
I am doing an image segmentation task and I am using a dataset that only has ground truths but no bounding boxes or polygons.
I have 2 classes( ignoring 0 for background) and the outputs and ground truth labels are in an array like
Predicted--/---Labels
0|0|0|1|2 0|0|0|... | How to find IoU from segmentation masks? | I am doing an image segmentation task and I am using a dataset that only has ground truths but no bounding boxes or polygons.
I have 2 classes( ignoring 0 for background) and the outputs and ground truth labels are in an array like
Predicted--/---Labels
0|0|0|1|2 0|0|0|1|2
0|2|1|0|0 0|2|1|0|0
0|0|1|1|1 0|0|1... | [
"So I just found out that jaccard_similarity_score is regarded as IoU.\nSo the solution is very simple,\nfrom sklearn.metrics import jaccard_similarity_score\n jac = jaccard_similarity_score(predictions, label, Normalize = True/False)\nSource link: https://scikit-learn.org/stable/modules/generated/sklearn.metrics.j... | [
7,
0
] | [] | [] | [
"image_segmentation",
"python",
"pytorch"
] | stackoverflow_0051115630_image_segmentation_python_pytorch.txt |
Q:
Rolling count of changes between row elements
I have a data frame that looks like this:
Identification
Date (day/month/year)
X
Y
123
01/01/2022
100
abc
123
02/01/2022
200
acb
123
03/01/2022
300
ary
124
01/01/2022
200
abc
124
02/01/2022
900
abc
124
03/01/2022
900
abc
I am trying to create two separate 'chan... | Rolling count of changes between row elements | I have a data frame that looks like this:
Identification
Date (day/month/year)
X
Y
123
01/01/2022
100
abc
123
02/01/2022
200
acb
123
03/01/2022
300
ary
124
01/01/2022
200
abc
124
02/01/2022
900
abc
124
03/01/2022
900
abc
I am trying to create two separate 'change' columns, one for x and y separate... | [
"This is not the most performant but gets the job done:\ndef consec_count(arr):\n total = 0\n out = np.zeros(len(arr), dtype=np.int32)\n acc = arr[0]\n for idx, el in enumerate(arr):\n if el == acc or el == np.nan or el == pd.NA:\n total = 0\n else:\n total += 1\n ... | [
1,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074306573_pandas_python.txt |
Q:
How to call cef.CreateBrowserSync()
I'm attempting to use cefpython3 with tkinter and want to make it OOP. Right now I have 3 classes GUI which act as the controller (runs tk.Tk()) and controls what page is showing. Next is a MainPage class which holds all the pages parts; buttons, labels, and a Browser object. Th... | How to call cef.CreateBrowserSync() | I'm attempting to use cefpython3 with tkinter and want to make it OOP. Right now I have 3 classes GUI which act as the controller (runs tk.Tk()) and controls what page is showing. Next is a MainPage class which holds all the pages parts; buttons, labels, and a Browser object. The third class is a BrowserFrame class whi... | [
"It sounds like you have called cef.Initialize() in a different section of your code from where you are attempting to call cef.CreateBrowserSync()\ncef.Initialize() is what begins the UI thread. See here\n"
] | [
0
] | [] | [] | [
"cefpython",
"python",
"tkinter"
] | stackoverflow_0070137221_cefpython_python_tkinter.txt |
Q:
Exercise Sorting Dictionaries
Hello, i'm gonna be really thankful if someone can tell me diffrent aproach to the task from the code below(Im sorry for my grammar, still learning english). Im looking also for advice for better writing a code, the idea for the sorting_dwarfs function didnt come on my own. Im still t... | Exercise Sorting Dictionaries |
Hello, i'm gonna be really thankful if someone can tell me diffrent aproach to the task from the code below(Im sorry for my grammar, still learning english). Im looking also for advice for better writing a code, the idea for the sorting_dwarfs function didnt come on my own. Im still trying to understand fully how the ... | [
"A few suggestions that should be helpful in executing the code:\n\nInstead of using the dwarf_color as the dictionary key, use both the dwarf_name and dwarf_color as the key.\nat the same time, create a separate color tracker for number of dwarf_color instances.\nThis will allow you to update the dwarf_physics by... | [
0
] | [] | [] | [
"dictionary",
"python",
"sorting"
] | stackoverflow_0074307522_dictionary_python_sorting.txt |
Q:
MacOS:python: command not found
Requirement: I have a script that has a python command to run and the script is used by everyone
Error: python: command not found
Example:
cat test.sh
python -c "... | MacOS:python: command not found | Requirement: I have a script that has a python command to run and the script is used by everyone
Error: python: command not found
Example:
cat test.sh
python -c "import json,sys;"
If I change the sc... | [
"As suggested by the homebrew installer itself, be sure to add this to your .bashrc or .zshrc:\nexport PATH=\"/usr/local/opt/python/libexec/bin:$PATH\"\n\n:( Above worked only one time but next time i ran it threw same error python command not found\n",
"Finally below solved my problem\nsudo ln -s /usr/bin/python... | [
0,
0
] | [] | [] | [
"macos",
"python",
"python_3.x"
] | stackoverflow_0074294549_macos_python_python_3.x.txt |
Q:
Remove a pair of key:value depending if the parameter of the function is in the dictionary
personnages_restants = {'Bernard': {'genre': 'homme', 'accessoires': ['chapeau']},
'Claire': {'genre': 'femme', 'accessoires': ['chapeau']},
'Eric': {'genre': 'homme', 'accessoires': ['chapeau']... | Remove a pair of key:value depending if the parameter of the function is in the dictionary | personnages_restants = {'Bernard': {'genre': 'homme', 'accessoires': ['chapeau']},
'Claire': {'genre': 'femme', 'accessoires': ['chapeau']},
'Eric': {'genre': 'homme', 'accessoires': ['chapeau']},
'George': {'genre': 'homme', 'accessoires': ['chapeau']},
'Mari... | [
"You used the same name valeur_caracteristique for 2 different objects! Thus your \"Qui Est-Ce\" algorithm is confused :)\npersonnages_restants = {'Bernard': {'genre': 'homme', 'accessoires': ['chapeau']},\n 'Claire': {'genre': 'femme', 'accessoires': ['chapeau']},\n 'Eric': {'genre': 'h... | [
1
] | [] | [] | [
"dictionary",
"function",
"python"
] | stackoverflow_0074307898_dictionary_function_python.txt |
Q:
Python unit tests run function after all test
I need to test smth on python via ssh. I don't want to make ssh connection for every test, because it is to long, I have written this:
class TestCase(unittest.TestCase):
client = None
def setUp(self):
if not hasattr(self.__class__, 'client') or self.__... | Python unit tests run function after all test | I need to test smth on python via ssh. I don't want to make ssh connection for every test, because it is to long, I have written this:
class TestCase(unittest.TestCase):
client = None
def setUp(self):
if not hasattr(self.__class__, 'client') or self.__class__.client is None:
self.__class__.... | [
"You should use setUpClass and tearDownClass instead, if you want to keep the same connection for all tests. You'll also need to make the disconnect method static, so it belongs to the class and not an instance of the class.\nclass TestCase(unittest.TestCase):\n\n def setUpClass(cls):\n cls.connection =... | [
21,
5,
1
] | [] | [] | [
"python",
"python_unittest",
"ssh",
"unit_testing"
] | stackoverflow_0026884198_python_python_unittest_ssh_unit_testing.txt |
Q:
Trying to make a dark- lightmode switcher
I'm trying to make a Button which switches between light and dark mode. Switching to dark mode is pretty easy, but switching to light mode again is a bit complicated.
I am trying to switch to the default Palette but I don't know how it really works.
This is the funct... | Trying to make a dark- lightmode switcher | I'm trying to make a Button which switches between light and dark mode. Switching to dark mode is pretty easy, but switching to light mode again is a bit complicated.
I am trying to switch to the default Palette but I don't know how it really works.
This is the function I'm using:
def modeSwitch(self):
... | [
"To reset the palette back to the system default, you can call:\nQApplication.setPalette(QApplication.style().standardPalette())\n\nThis fetches the palette from the current style, which will be the system default.\n"
] | [
1
] | [] | [] | [
"pyqt",
"pyqt5",
"python",
"qt",
"qt5"
] | stackoverflow_0074308016_pyqt_pyqt5_python_qt_qt5.txt |
Q:
How to ignore (or convert) "\N" in a CSV with Pandas?
I have a very large CSV file with many cells that have "\N" as the value. For example:
OBJ_1
OBJ_2
TCA
16908
37152
2019-07-29 01:13:37
37152
16908
2019-07-29 01:13:37
16908
37152
2019-07-29 01:13:37
\N
16908
2019-07-29 01:13:37
19483
23132
\N
22829
\N
20... | How to ignore (or convert) "\N" in a CSV with Pandas? | I have a very large CSV file with many cells that have "\N" as the value. For example:
OBJ_1
OBJ_2
TCA
16908
37152
2019-07-29 01:13:37
37152
16908
2019-07-29 01:13:37
16908
37152
2019-07-29 01:13:37
\N
16908
2019-07-29 01:13:37
19483
23132
\N
22829
\N
2019-07-29 01:13:37
When I run the function to... | [
"According to the docs, you can use the na_values argument to automatically convert these to NaNs, like this:\ndf = pd.read_csv(\"path\", na_values=\"\\\\N\")\n\n"
] | [
3
] | [] | [] | [
"csv",
"pandas",
"python"
] | stackoverflow_0074307963_csv_pandas_python.txt |
Q:
Maximizing Pearson Correlation, what should be loss function
I'm using Keras for a deep learning prediction task and my aim is to maximize Pearson correlation between predicted values and true labels.
What would be the ideal loss function to use in this scenario?
A:
Ideally you want a loss that minimizes the dis... | Maximizing Pearson Correlation, what should be loss function | I'm using Keras for a deep learning prediction task and my aim is to maximize Pearson correlation between predicted values and true labels.
What would be the ideal loss function to use in this scenario?
| [
"Ideally you want a loss that minimizes the distance between the prediction distribution and the target distribution. So, the answer to this question depends on the distribution of your labels. \nAssuming your labels are gaussian, MSE should be a good loss to go with. You can read more about MSE vs Pearson Correlat... | [
0,
0
] | [] | [] | [
"correlation",
"deep_learning",
"keras",
"python",
"statistics"
] | stackoverflow_0049883099_correlation_deep_learning_keras_python_statistics.txt |
Q:
Multiple members of class are updated instead of one
I have created class File:
@dataclass
class Match:
length: int
pos_A: int
pos_B: int
f_index: int
class File:
__name = ""
__pos_in_list = 0
__statements = []
__matches = []
def __init__(self, name: str, pos: int, statements:... | Multiple members of class are updated instead of one | I have created class File:
@dataclass
class Match:
length: int
pos_A: int
pos_B: int
f_index: int
class File:
__name = ""
__pos_in_list = 0
__statements = []
__matches = []
def __init__(self, name: str, pos: int, statements: [Statement]):
self.__name = name
self.__p... | [
"You need to move variable definition inside the init method. Defining variable outside of init means that those variables will be shared amongst all objects. Same goes for __name, __pos_in_list and __statements variables too\n@dataclass\nclass Match:\n length: int\n pos_A: int\n pos_B: int\n f_index: i... | [
1,
0
] | [] | [] | [
"class",
"list",
"python",
"python_3.x"
] | stackoverflow_0074307862_class_list_python_python_3.x.txt |
Q:
Find out all possible cartesian products using Recursion
The function takes in a string (str) s and an integer (int) n .
The function returns a list (list) of all Cartesian product of s with length n
The expression product(s,n) can be computed by adding each character in s to the
result of product(s,n-1) .
>... | Find out all possible cartesian products using Recursion | The function takes in a string (str) s and an integer (int) n .
The function returns a list (list) of all Cartesian product of s with length n
The expression product(s,n) can be computed by adding each character in s to the
result of product(s,n-1) .
>>> product('ab',3)
'aaa', 'aab', 'aba', 'abb', 'baa', 'bab... | [
"Your code is building a single string. That doesn't match what the function is supposed to do, which is return a list of strings. You need to add the list-building logic, and deal with the fact that your recursive calls are going to produce lists as well.\nI'd do something like this:\ndef product(s, n):\n if n ==... | [
1
] | [] | [] | [
"cartesian_product",
"permutation",
"python",
"recursion"
] | stackoverflow_0074307708_cartesian_product_permutation_python_recursion.txt |
Q:
Django testing UpdateView - object has no attribute 'object'
I am trying to write a test for an UpdateView I created.
My view looks like this:
class MutantUpdateView(UpdateView):
context_object_name = "mutant"
fields = ["mutation_level"]
model = Mutant
pk_url_kwarg = "mutant_id"
template_name_s... | Django testing UpdateView - object has no attribute 'object' | I am trying to write a test for an UpdateView I created.
My view looks like this:
class MutantUpdateView(UpdateView):
context_object_name = "mutant"
fields = ["mutation_level"]
model = Mutant
pk_url_kwarg = "mutant_id"
template_name_suffix = "_update_form"
def get_context_data(self, **kwargs):
... | [
"The problem is not the view, but testing the view. Your test aims to \"mimic\" the code flow of the view, but the object is set in the .get(…) method [classy-Django]. You likely can implement that too, but if you later change the view, or you add a mixin, etc. That will result in fixing all tests.\nOne usually use... | [
1
] | [] | [] | [
"django",
"django_forms",
"python",
"updateview"
] | stackoverflow_0074306839_django_django_forms_python_updateview.txt |
Q:
How to create a file in a different directory? (python)
I am currently stuck with the following error:
IOError: [Errno 2] No such file or directory: '/home/pi/V1.9/Storage/Logs/Date_2018-08-02_12:51.txt'
My code to open the file is the following:
nameDir = os.path.join('/home/pi/V1.9/Storage/Logs', "Date_" + now... | How to create a file in a different directory? (python) | I am currently stuck with the following error:
IOError: [Errno 2] No such file or directory: '/home/pi/V1.9/Storage/Logs/Date_2018-08-02_12:51.txt'
My code to open the file is the following:
nameDir = os.path.join('/home/pi/V1.9/Storage/Logs', "Date_" + now.strftime("%Y-%m-%d_%H:%M") + ".txt")
f = open(nameDir, 'a')
... | [
"If you are creating the file use the write mode w or use a+\nf = open(nameDir, 'w')\nf = open(nameDir, 'a+')\n\nUse only a append if the file already exist. \n",
"The problem seems to be here:\nf = open(nameDir, 'a')\n\n'a' stands for append, which means: the file should already exist, you get an error message b... | [
0,
0,
0
] | [] | [] | [
"file",
"python"
] | stackoverflow_0051653124_file_python.txt |
Q:
Unit testing that a method was called in another object's method in Python
Most of my unit testing experience is with Java and now I'm turning to Python. I need to test whether a method (from object B) gets called inside another method (in object A).
In Java the test method would have to pass a mock or spy version... | Unit testing that a method was called in another object's method in Python | Most of my unit testing experience is with Java and now I'm turning to Python. I need to test whether a method (from object B) gets called inside another method (in object A).
In Java the test method would have to pass a mock or spy version of B to A's constructor to be used when the B method is invoked. Do I need to d... | [
"Apart from the possible problems with the design, mentioned in the comment by @Alex, there is a couple of errors in using the mock.\nFirst, you are mocking the wrong object. As in object_a you do from obj_b import * (which is bad style by the way - only import the objects you need), you need to patch the object re... | [
1
] | [] | [] | [
"mocking",
"python",
"python_unittest",
"spying",
"unit_testing"
] | stackoverflow_0074306497_mocking_python_python_unittest_spying_unit_testing.txt |
Q:
Conditional expression with variable change
a1, a2, a3, a4,= 0, -100,12,5
val=0
list1=[]
for i in range(5):
if a()<50:
val +=1
In this conditional statement, I want the variable a to change every time the loop rotates.
For example, from a1>>a2>>a3>>a4 and until the end.I need to define many condition... | Conditional expression with variable change | a1, a2, a3, a4,= 0, -100,12,5
val=0
list1=[]
for i in range(5):
if a()<50:
val +=1
In this conditional statement, I want the variable a to change every time the loop rotates.
For example, from a1>>a2>>a3>>a4 and until the end.I need to define many conditions to make the calculation algorithm more efficien... | [
"a = [0, -100, 12, 5] # use a list.\n\nval = 0\nfor i in a: # loop through items in a\n if i < 50: # check if the item is less than 50\n val += 1\n\n"
] | [
0
] | [] | [] | [
"algorithm",
"dynamics_al",
"if_statement",
"loops",
"python"
] | stackoverflow_0074308100_algorithm_dynamics_al_if_statement_loops_python.txt |
Q:
How to run same logic in parallel across multiple subsets of the same data in Python
I have a dataset, let's call it data1.
data1 can be segmented into subsets using a variable store_number.
Now for each subset by store_number I want to run the same logic, say finding the total sales amount.
Is it possible to run ... | How to run same logic in parallel across multiple subsets of the same data in Python | I have a dataset, let's call it data1.
data1 can be segmented into subsets using a variable store_number.
Now for each subset by store_number I want to run the same logic, say finding the total sales amount.
Is it possible to run this logic across all the stores in parallel in python? In my current set up I have put th... | [
"If your calculation is a CPU-bound task, you should look at using multiprocessing.Pool to apply your function to each subset using separate CPU cores.\nIf your task is IO-bound (e.g. it involves DB queries), you should check out the ThreadPoolExecutor which will run over each subset in its own thread.\n"
] | [
0
] | [] | [] | [
"parallel_processing",
"python"
] | stackoverflow_0074308129_parallel_processing_python.txt |
Q:
Python Faker fake.word(): Filter out profanity
I noticed that when I use the fake.word() function with locale set to 'pl_PL' it sometimes generates a swear word which is not ideal for me. Is there an easy way to force Faker to stop outputting swear words, preferably without having to list all of the swear words my... | Python Faker fake.word(): Filter out profanity | I noticed that when I use the fake.word() function with locale set to 'pl_PL' it sometimes generates a swear word which is not ideal for me. Is there an easy way to force Faker to stop outputting swear words, preferably without having to list all of the swear words myself?
| [
"Unfortunately I do not know of a way to remove swear words without typing them out.\nOne option is to remove the swear words from the word list of the pl_PL lorem Provider class.\nfrom faker.providers.lorem.pl_PL import Provider as PLProvider\n\nbad_words = [\"kurwa\"]\nPLProvider.word_list = tuple(word for word i... | [
2,
2
] | [] | [] | [
"faker",
"python"
] | stackoverflow_0074307524_faker_python.txt |
Q:
How do I sort multiple columns in a dataframe based on 2 columns, while keeping one of them static in python?
My dataframe-
dfmodtestes
Account Key Name MonthSinceInception False
1 a0 Gu 20 0.5
1 a6 Gu 15 0.4
1 a9 Gu 35 0.9
2 ... | How do I sort multiple columns in a dataframe based on 2 columns, while keeping one of them static in python? | My dataframe-
dfmodtestes
Account Key Name MonthSinceInception False
1 a0 Gu 20 0.5
1 a6 Gu 15 0.4
1 a9 Gu 35 0.9
2 89 Pa 70 0.8
2 01 Ra 08 0.1
My objective is to keep the account o... | [
"Try using sort_values, note per docs ascending can accept a liset of bool:\ndf.sort_values(['Account', 'MonthSinceInception'], ascending=[True, False])\n\nOutput:\n Account Key Name MonthSinceInception False\n2 1 a9 Gu 35 0.9\n0 1 a0 Gu 20 0.5\n1 ... | [
1,
0
] | [] | [] | [
"numpy",
"pandas",
"python",
"sorting"
] | stackoverflow_0074306720_numpy_pandas_python_sorting.txt |
Q:
Extract value by using function with parameter
I have a nested dictionary containing both the title and the number of pages of a book. I want to write a function that gets as first argument the dictionary to search in and as second one a page number (as string). The function will then search through the dictionary... | Extract value by using function with parameter | I have a nested dictionary containing both the title and the number of pages of a book. I want to write a function that gets as first argument the dictionary to search in and as second one a page number (as string). The function will then search through the dictionary and print all the titles of book which have the sam... | [
"You may want to use dict.values() instead of dict.items() at times when the key doesn't matter. This will likely reduce some confusion later down the line.\nGiven:\ntext = {\n 1: {1: {'ch.name': 'The Boy Who Lived', 'pages': '146'},\n 2: {'ch.name': 'The Vanishing Glass', 'pages': '126'}},\n 2: {1: {'ch.name':... | [
0,
0,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0074307747_dictionary_python.txt |
Q:
Binary search tree with undefined nodes and no reference to the parent node, a corresponding x value is given to any node
A binary tree is given where each node has a limited and undefined number of children. In the node structure, there are no references to the parent node. A corresponding X value is given to any... | Binary search tree with undefined nodes and no reference to the parent node, a corresponding x value is given to any node | A binary tree is given where each node has a limited and undefined number of children. In the node structure, there are no references to the parent node. A corresponding X value is given to any node in the tree. If values are unique in the tree, find the value of the parent node of the node with the value X. Specificat... | [
"Hope you are not cheating in a test.\nEdit: This is for n-ary tree rather than binary tree.\nThis can be done with basic tree traversal with back-tracking.\nHere's a Depth-First-Search based Implementation:\nclass Tree(object):\n \"Generic tree node. Adapted from https://stackoverflow.com/a/28015122/7562633 \"\... | [
1
] | [] | [] | [
"binary_tree",
"python",
"tree"
] | stackoverflow_0074308101_binary_tree_python_tree.txt |
Q:
how to add a where filter when using pandas groupby aggregation function
I have a question about how to using pandas groupby() function but I need to add a filter on it, please follow follow example df:
id c1 c2 c3
1 1 2 3
1 2 3 4
1 3 4 5
if I use code:
grouped_df = df.groupby(['id']).agg(
Min... | how to add a where filter when using pandas groupby aggregation function | I have a question about how to using pandas groupby() function but I need to add a filter on it, please follow follow example df:
id c1 c2 c3
1 1 2 3
1 2 3 4
1 3 4 5
if I use code:
grouped_df = df.groupby(['id']).agg(
Min_1=('c1', np.min),
Min_2=('c2', np.min),
Min_3=('c2', np.min))
grouped... | [
"This does not use any additional pandas function, but one way to do this is to simply index the input to np.min directly. This would be similar to your where clause.\ngrouped_df = df.groupby(['id']).agg(\n Min_1=('c1', lambda x : np.min(x[(x>=2) & (x<=3)])),\n Min_2=('c2', lambda x : np.min(x[(x>=2) & (x<=3... | [
0
] | [] | [] | [
"filter",
"group_by",
"pandas",
"python"
] | stackoverflow_0074307961_filter_group_by_pandas_python.txt |
Q:
Perform date transformation before multple groupbys in Pandas
I wish to groupby date country and type and convert any date that has same month value to the first of that month.
Data
country type date energy
US aa 8/5/2022 10
US aa 8/25/2022 1
US aa ... | Perform date transformation before multple groupbys in Pandas | I wish to groupby date country and type and convert any date that has same month value to the first of that month.
Data
country type date energy
US aa 8/5/2022 10
US aa 8/25/2022 1
US aa 8/2/2022 11
US bb 8/5/2022 55
US ... | [
"Try this using pd.Grouper:\ndf.groupby(['country', \n 'type', \n pd.Grouper(key='date', freq='MS')], sort=False)['energy'].sum().reset_index()\n\nOutput:\n country type date energy\n0 US aa 2022-08-01 22\n1 US bb 2022-08-01 80\n2 AUSTRALIA bb 2022-0... | [
3
] | [] | [] | [
"group_by",
"numpy",
"pandas",
"python"
] | stackoverflow_0074307973_group_by_numpy_pandas_python.txt |
Q:
HTML Elements not updated
I am trying to retreive an HTML Table from a website to save it in a csv file via a Python script.
The number of records (rows) displayed on the HTML Page is 10.
On the same HTML page there is a button to display the next 10 records (rows).
I have no issue to retreive the fisrt 10 records... | HTML Elements not updated | I am trying to retreive an HTML Table from a website to save it in a csv file via a Python script.
The number of records (rows) displayed on the HTML Page is 10.
On the same HTML page there is a button to display the next 10 records (rows).
I have no issue to retreive the fisrt 10 records but when my python scirpt call... | [
"I guess I find the error in my code.\nI used :\nresponse = requests.get(driver.current_url, verify=False)\nsoup = bs(response.text, 'html.parser')\n\ninstead of:\nresponse = requests.get(driver.current_url, verify=False)\nsoup = bs(driver.page_source, 'html.parser')\n\n"
] | [
0
] | [] | [] | [
"element",
"python"
] | stackoverflow_0074275361_element_python.txt |
Q:
Error importing tensorflow "AlreadyExistsError: Another metric with the same name already exists."
I am running this simple code on Spyder 3.3 with Python 3.7 and Tensorlow 2.0:
import tensorflow as tf
print(tf.__version__)
When I try to run it again in the same IPython console, I get the following error:
File "... | Error importing tensorflow "AlreadyExistsError: Another metric with the same name already exists." | I am running this simple code on Spyder 3.3 with Python 3.7 and Tensorlow 2.0:
import tensorflow as tf
print(tf.__version__)
When I try to run it again in the same IPython console, I get the following error:
File "/home/rodrigo/.local/lib/python3.7/site-packages/tensorflow_core/python/eager/monitoring.py", line 121, ... | [
"TL;DR: Ensure the Keras version matches the Tensorflow version\nI am experiencing the same thing with:\n\nWindows\nPython3.8\nTensorflow-2.6.1\n\nThe core issue appears to be that there are two Keras packages installed:\n<site-packages>/keras\n<site-packages/tensorflow/python/keras\n\nIf you look at the release no... | [
61,
10,
6,
3,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [] | [] | [
"python",
"tensorflow"
] | stackoverflow_0058012741_python_tensorflow.txt |
Q:
Why is my code not working anymore once I turn it into an app?
I have just followed a tutorial to turn a simple article summarizing file written with Python into an app.
The code works just fine, displays a window for the user to enter an url and a button to process it all.
I turned the code into an app and now th... | Why is my code not working anymore once I turn it into an app? | I have just followed a tutorial to turn a simple article summarizing file written with Python into an app.
The code works just fine, displays a window for the user to enter an url and a button to process it all.
I turned the code into an app and now the processing does not happen. The interface does pop up, it is possi... | [
"Your code gets stuck as soon as it tries to execute article.parse(). This is because newspaper is a broken library in Python 3.\nIt can't convert the website from HTML to plain text properly and can't continue with the code and give you any results. Hence you don't see it when you press the button. If you still wa... | [
1
] | [] | [] | [
"cmd",
"python",
"tkinter"
] | stackoverflow_0074307461_cmd_python_tkinter.txt |
Q:
Dataframe printed to terminal without print() command
I have written some code to download stockprices using Python.
All Tickers (140+, e.g. BMW.DE) have no problems.
I'm having issues with 'CON.DE'. It won't save to a .csv file and more peculiar it prints the dataframe to the terminal without there being a print(... | Dataframe printed to terminal without print() command | I have written some code to download stockprices using Python.
All Tickers (140+, e.g. BMW.DE) have no problems.
I'm having issues with 'CON.DE'. It won't save to a .csv file and more peculiar it prints the dataframe to the terminal without there being a print() command.
I'm running it using the following versions:
yf... | [
"You're actually running into an odd issue with Window's special CON(note it's case insensitive) filename which basically is redirecting to the console. This same code works fine in the WSL(linux) or non-windows.\nThe issue is in the filename. df.to_csv(\"con\") produces this behavior so as you start stripping away... | [
1
] | [] | [] | [
"pandas",
"python",
"windows",
"yfinance"
] | stackoverflow_0074308023_pandas_python_windows_yfinance.txt |
Q:
Django to AWS deterministic=True requires SQLite 3.8.3 or higher
I deployed my AWS application but am receiving an error when I navigate to its EC instance URL:
deterministic=True requires SQLite 3.8.3 or higher
I tried this solution, but when I run eb deploy and eb ssh and vi /var/app/venv/staging-LQM1lest/lib/... | Django to AWS deterministic=True requires SQLite 3.8.3 or higher | I deployed my AWS application but am receiving an error when I navigate to its EC instance URL:
deterministic=True requires SQLite 3.8.3 or higher
I tried this solution, but when I run eb deploy and eb ssh and vi /var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py, the file ... | [
"Basically, I wasn't able to get mysql working. Instead, I opted to migrate to an aws Postgres instance. It's working fine now.\n"
] | [
0
] | [] | [] | [
"amazon_elastic_beanstalk",
"django",
"python",
"sqlite"
] | stackoverflow_0074269951_amazon_elastic_beanstalk_django_python_sqlite.txt |
Q:
How to increase FPS in ursina python
I want to create survival games with infinite block terrain(like Minecraft). So i using ursina python game engine, you can see it here
So i using perlin noise to create the terrain with build-in ursina block model. I test for first 25 block and it work pretty good with above 10... | How to increase FPS in ursina python | I want to create survival games with infinite block terrain(like Minecraft). So i using ursina python game engine, you can see it here
So i using perlin noise to create the terrain with build-in ursina block model. I test for first 25 block and it work pretty good with above 100 FPS, so i start increase to 250 block an... | [
"I'm not able to test this code at the moment but this should serve as a starting point:\nlevel_parent = Entity(model=Mesh(vertices=[], uvs=[]))\n\nfor z in range(mapHeight):\n for x in range(mapWidth):\n height = round(GeneratedNoiseMap(z, x, 20) * maxHeight)\n block = Voxel(position=(x, height - ... | [
1,
0
] | [] | [] | [
"python",
"ursina"
] | stackoverflow_0069413473_python_ursina.txt |
Q:
Using Pytest and the Gitlab CI with relative paths
I have an issue that is driving me mental and I can't get my head around it.
I am writing a little python App and wrote a few tests using pytest. For some of the tests, I need to load some files that are in subdirectories. It looks like this:
App/
src/
ma... | Using Pytest and the Gitlab CI with relative paths | I have an issue that is driving me mental and I can't get my head around it.
I am writing a little python App and wrote a few tests using pytest. For some of the tests, I need to load some files that are in subdirectories. It looks like this:
App/
src/
main.py
logic/
logic.py
test_logi... | [
"You can infer the path of the TestFile.json at runtime from its relative location w.r.t. the test_logic.py file, something like this:\nimport os\n\n# __file__ is the path of the current file, in this case the path of test_logic.py\nTESTFILE_FOLDER = os.path.join(os.path.dirname(__file__), 'TestFiles')\n\ndef test_... | [
1
] | [] | [] | [
"gitlab",
"pytest",
"python"
] | stackoverflow_0074304974_gitlab_pytest_python.txt |
Q:
Not able to install Point Cloud Library onto python using conda
Hi all I am having a hard time installing the PCL or point cloud library onto python using the function conda install -c conda-forge pcl. I am getting all types of errors and it is not installing pcl properly and there is something about a brew? Pleas... | Not able to install Point Cloud Library onto python using conda | Hi all I am having a hard time installing the PCL or point cloud library onto python using the function conda install -c conda-forge pcl. I am getting all types of errors and it is not installing pcl properly and there is something about a brew? Please help
I have tried many things and even looked at the Point Cloud Li... | [
"You can try other channels instead too, sometimes it works, check here for other channels:\npcl anaconda three channels\nIf that still doesnot work then try in anaconda powershell pip install pcl.\nI hope this will help.\n",
"As per documentation of the python package:\nconda install -c conda-forge -c davidcaron... | [
0,
0
] | [] | [] | [
"anaconda",
"conda",
"point_cloud_library",
"python"
] | stackoverflow_0074258820_anaconda_conda_point_cloud_library_python.txt |
Q:
pd.info() in AttributeError: 'int' object has no attribute 'info'
I just use pandas to write a load_data function, then I have bug in my code, I don't know how to deal with that? and my code df.info() alway has errors AttributeError: 'int' object has no attribute 'info', or the output is 0or none`
import numpy as ... | pd.info() in AttributeError: 'int' object has no attribute 'info' | I just use pandas to write a load_data function, then I have bug in my code, I don't know how to deal with that? and my code df.info() alway has errors AttributeError: 'int' object has no attribute 'info', or the output is 0or none`
import numpy as np
import pandas as pd
import csv
from io import StringIO
def load_dat... | [
"It's because the load_data function is returning 0 and not the dataframe that has been loaded. You need to modify your return statement in order for this to work as expected:\ndef load_data():\n buffer = StringIO()\n #df.info(buf = buffer)\n #buffer.getvalue()\n #with open('work.csv', ';') as f:\n d... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074308436_dataframe_pandas_python.txt |
Q:
Create an array based on column values in a dataframe
I currently have a dataframe with title names as the column headers. I have a row which has counts the number of ratings for each title, and an another row with the median rating of each title. I want to create an array which holds the median ratings for titles... | Create an array based on column values in a dataframe | I currently have a dataframe with title names as the column headers. I have a row which has counts the number of ratings for each title, and an another row with the median rating of each title. I want to create an array which holds the median ratings for titles with more than a certain number of ratings, is this possib... | [
"You can use df.iloc[0] > 60 to create an array of Boolean values indicating whether each value in row 0 is greater than 60 (where df is your dataframe variable).\nAnd you can use this to filter the values in your second row (df.iloc[1]) to get:\ndf.iloc[1][df.iloc[0] > 60]\nIt should return the pandas series:\nMul... | [
2
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074308461_dataframe_pandas_python.txt |
Q:
If all the values are in one file, how do you split them into different lists?
How would I write a python code for this using split function?
Example of input file (.txt) :
3
Day 1
Option A, 30
Option B, 60
Option C, 90
Day 2
Option A, 16
Option B, 24
Option C, 30
Day 3
Option A, 64
Option B, 49
Option C, 39
Th... | If all the values are in one file, how do you split them into different lists? | How would I write a python code for this using split function?
Example of input file (.txt) :
3
Day 1
Option A, 30
Option B, 60
Option C, 90
Day 2
Option A, 16
Option B, 24
Option C, 30
Day 3
Option A, 64
Option B, 49
Option C, 39
This should be the output:
List A = [3] #total options available
List B = [110, 133, 1... | [
"\nopen and iterate over the file\nif a line starts with 'Day' skip it\nsplit each line on a comma\n\nuse the first item of the split as a dictionary key\nuse the second item to add to that key's value\n\n\n\n",
"You just do it line by line. You'll probably read the data from a file, and in that case you'll want... | [
0,
0,
0
] | [] | [] | [
"python",
"split_function"
] | stackoverflow_0074307903_python_split_function.txt |
Q:
Google Assistant "Error: no such option: --project-id"
I wanted to install Google Assistant on Raspberry Pi 3B+. I watched YouTube videos and read the official guide:
https://developers.google.com/assistant/sdk/guides/service/python/embed/run-sample
And the sequence finally came to the test code,
googlesamples-ass... | Google Assistant "Error: no such option: --project-id" | I wanted to install Google Assistant on Raspberry Pi 3B+. I watched YouTube videos and read the official guide:
https://developers.google.com/assistant/sdk/guides/service/python/embed/run-sample
And the sequence finally came to the test code,
googlesamples-assistant-pushtotalk --project-id my-dev-project --device-model... | [
"I use only googlesamples-assistant-pushtotalk and solve problem\n"
] | [
0
] | [] | [] | [
"google_assist_api",
"google_assistant",
"google_assistant_sdk",
"python"
] | stackoverflow_0073992779_google_assist_api_google_assistant_google_assistant_sdk_python.txt |
Q:
Converting unixtime to the number of days
Is it possible to translate the result of unix-time (namely, the number of seconds since 1970, January 1) into the number of days?
I'm not talking about the usual date YY.MM.DD.
For example, I got the average user lifetime on the site based on movie ratings and want to tra... | Converting unixtime to the number of days | Is it possible to translate the result of unix-time (namely, the number of seconds since 1970, January 1) into the number of days?
I'm not talking about the usual date YY.MM.DD.
For example, I got the average user lifetime on the site based on movie ratings and want to translate this into the number of days.
I tried to... | [
"divide by 60 to get minutes then by 60 to get hours then by 24 to get days --> 60 * 60 * 24 = 86400\nimport time\nprint(time.time() / 86400)\n\n\n"
] | [
1
] | [] | [] | [
"python",
"unix"
] | stackoverflow_0074308485_python_unix.txt |
Q:
Removal of rows with a duplicate value in a column based on a condition from another column - Python/Pandas
I have data from a CSV file read into Pandas dataframe (all cells have string type, NaN:s are replaced with "" already) with some duplicate values that I need to get rid of.
A sample input CSV:
Col1,Col2,Col... | Removal of rows with a duplicate value in a column based on a condition from another column - Python/Pandas | I have data from a CSV file read into Pandas dataframe (all cells have string type, NaN:s are replaced with "" already) with some duplicate values that I need to get rid of.
A sample input CSV:
Col1,Col2,Col3
A,rrrrr,fff
A,,ffff
B,rrr,fffff
C,,ffffff
D,rrrrrrr,ffff
C,rrrr,fffff
E,rrrrr,fff
C,,kkkkk
I need to remove th... | [
"You can compute the count of each value in Col1 and then use that computed_count and pandas.Series.isna() for getting waht you want.\ndf['cnt_col1'] = df.groupby('Col1')['Col1'].transform('count')\nm = (df[\"Col2\"].isna()) & (df[\"cnt_col1\"]>1)\ndf_new = df[~m].drop('cnt_col1', axis=1)\nprint(df_new)\n\nOr witho... | [
1
] | [] | [] | [
"duplicates",
"pandas",
"python"
] | stackoverflow_0074308446_duplicates_pandas_python.txt |
Q:
How to make a discord bot go online using discord.py?
I'm trying to make a discord bot. After several tries I still can't get it to go online.
So I'm using a mac and when I ran:
python3 -m pip install -U discord.py
I get a message that says "Requirement already satisfied".
My code:
import discord
from discord.ext... | How to make a discord bot go online using discord.py? | I'm trying to make a discord bot. After several tries I still can't get it to go online.
So I'm using a mac and when I ran:
python3 -m pip install -U discord.py
I get a message that says "Requirement already satisfied".
My code:
import discord
from discord.ext import commands
client = commands.Bot(command_prefix = '.'... | [
"As nuclio said, I personally think that naming your file \"discord.py\" is really hard to use, which means it would require more than you think to make your bot run using that name.\nIf you have regenerated your bot token, make sure to update your code with the latest token, if not, your bot will never be online. ... | [
2,
0
] | [
"import discord\nfrom discord.ext import commands\nclient = commands.Bot(command_prefix = '>')\n\n@client.event\nasync def on_ready():\n print (\"Log : \"+str(client.user))\n\nclient.run('token')```\n\n"
] | [
-1
] | [
"discord",
"discord.py",
"python"
] | stackoverflow_0065637532_discord_discord.py_python.txt |
Q:
How do I convert a list of entries into a dictionary and merge it with an already existing dictionary?
Given I have the following function:
add_to_list({ 'GOOG': [100.21] }, ('GOOG', 130.00))
This function is supposed to convert values ('GOOG', 130.00) into a dictionary in the format 'GOOG':130.00. On top, it is ... | How do I convert a list of entries into a dictionary and merge it with an already existing dictionary? | Given I have the following function:
add_to_list({ 'GOOG': [100.21] }, ('GOOG', 130.00))
This function is supposed to convert values ('GOOG', 130.00) into a dictionary in the format 'GOOG':130.00. On top, it is meant to append the already existing dictionaries with values that are not already included.
Upon trying the... | [
"This may be a flawed interpretation of the challenge.\ndef add_to_list(x, y):\n assert isinstance(x, dict)\n assert isinstance(y, tuple)\n k, v = y\n x.setdefault(k, []).append(v)\n return x\nprint(add_to_list({ 'GOOG': [100.21] }, ('GOOG', 130.00)))\n\nOutput:\n{'GOOG': [100.21, 130.0]}\n\n",
"de... | [
2,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0074308267_dictionary_python.txt |
Q:
Programming a Discord bot with Python- How do I make it join a voice channel?
I want to make the bot join the voice channel that I'm in when prompted. Here's what I have:
@client.event
async def on_message(message):
if message.content.startswith('.join'):
channel = 775902254951301125
await channel.connec... | Programming a Discord bot with Python- How do I make it join a voice channel? | I want to make the bot join the voice channel that I'm in when prompted. Here's what I have:
@client.event
async def on_message(message):
if message.content.startswith('.join'):
channel = 775902254951301125
await channel.connect()
It doesn't seem to work, any tips?
| [
"I think this is what you're looking for!\n@client.command(pass_context=True)\nasync def join(ctx):\n channel = ctx.message.author.voice.voice_channel\n await client.join_voice_channel(channel)\n\nThat was pulled straight from this video which was just a google search away.\n",
"try run in command prompt/po... | [
1,
0,
0
] | [] | [] | [
"discord.py",
"python"
] | stackoverflow_0065729028_discord.py_python.txt |
Q:
How to send a message with discord.py without a command
import discord
import asyncio
client = discord.Client()
@client.event
async def on_ready():
print("I'm ready.")
async def send(message):
await client.send_message(client.get_channel("123456789"), message)
client.run("token")
loop = asyncio.get_eve... | How to send a message with discord.py without a command | import discord
import asyncio
client = discord.Client()
@client.event
async def on_ready():
print("I'm ready.")
async def send(message):
await client.send_message(client.get_channel("123456789"), message)
client.run("token")
loop = asyncio.get_event_loop()
loop.run_until_complete(send("hello"))
Hi, i want ... | [
"The reason your code is not working is because client.run is blocking, meaning that nothing after it will execute. This means your loop will never be reached.\nTo get around this, use client.loop.create_task.\nThe github of discord.py has an example of a background task, found here. You should be able to use this ... | [
20,
1,
0
] | [] | [] | [
"bots",
"discord",
"discord.py",
"python"
] | stackoverflow_0049835742_bots_discord_discord.py_python.txt |
Q:
Error trying to replace spaces with underscores
I am trying to ask the player to write a sentence. If the sentence has no spaces, it will return as so. Otherwise, i want all the spaces to be replaced with underscores.
sentence = input("Enter de sentence: ")
def replace():
if sentence.count(" ")>0:
sent... | Error trying to replace spaces with underscores | I am trying to ask the player to write a sentence. If the sentence has no spaces, it will return as so. Otherwise, i want all the spaces to be replaced with underscores.
sentence = input("Enter de sentence: ")
def replace():
if sentence.count(" ")>0:
sentence[1 : sentence.index(" ")] +"_"+ sentence[sentence... | [
"You're misunderstanding many thing it seems, the method name, the variables, ...\nLet's go back to a simple one\ndef replace(content):\n if content.count(\" \") > 0:\n content = content.replace(\" \", \"_\")\n return content\n\nsentence = input(\"Enter de sentence: \")\nprint(replace(sentence))\n\nBut... | [
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074307724_python.txt |
Q:
ValueError: not enough values to unpack (expected 2, got 1) error when running outlook email creator
ValueError: not enough values to unpack (expected 2, got 1) is the error im getting when i try to run python app.py in terminal. I am using visual studio code. Here is the code from when i ran the app.
> python app... | ValueError: not enough values to unpack (expected 2, got 1) error when running outlook email creator | ValueError: not enough values to unpack (expected 2, got 1) is the error im getting when i try to run python app.py in terminal. I am using visual studio code. Here is the code from when i ran the app.
> python app.py
Traceback (most recent call last):
File "C:\Users\7932\Downloads\OutlookEmailCreator-master\OutlookE... | [
"It's difficult to tell without access to the code, but the error message is suggesting that there is no '@' character present in the random_proxy string. Maybe try print out the value of random_proxy immediately before the split happens to investigate?\n"
] | [
1
] | [] | [] | [
"python",
"valueerror"
] | stackoverflow_0074308624_python_valueerror.txt |
Q:
Convert date string to datetime format python
I have dates like ‘feb-97’, ‘jan-02’, ‘dec-22’ in a dataframe and want to convert the column to datetime format with day as start or last day of month.
A:
df = pd.DataFrame({'date':['feb-97', 'jan-02', 'dec-22']})
df['date'] = pd.to_datetime(df['date'], format='%b-%y... | Convert date string to datetime format python | I have dates like ‘feb-97’, ‘jan-02’, ‘dec-22’ in a dataframe and want to convert the column to datetime format with day as start or last day of month.
| [
"df = pd.DataFrame({'date':['feb-97', 'jan-02', 'dec-22']})\ndf['date'] = pd.to_datetime(df['date'], format='%b-%y')\n\ndate\n0 1997-02-01\n1 2002-01-01\n2 2022-12-01\n\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074308705_python.txt |
Q:
Uvicorn run on specified python version
When I run
/home/xxx/.local/bin/uvicorn --version
I got:
Running uvicorn 0.17.0 with CPython 3.6.9 on Linux
But I have installed python3.7, I want to run uvicorn with 3.7 instead 3.6.9.
I have also:
/usr/bin/python --version
Python 3.7.5
How to point Python to 3.7 instead 3... | Uvicorn run on specified python version | When I run
/home/xxx/.local/bin/uvicorn --version
I got:
Running uvicorn 0.17.0 with CPython 3.6.9 on Linux
But I have installed python3.7, I want to run uvicorn with 3.7 instead 3.6.9.
I have also:
/usr/bin/python --version
Python 3.7.5
How to point Python to 3.7 instead 3.6 for the uvicorn?
| [] | [] | [
"Find the pip instance associated with your python 3.7 installation and use it instead. You can use whereis pip to locate all of the occurrences on your path.\n"
] | [
-1
] | [
"python",
"uvicorn"
] | stackoverflow_0074307126_python_uvicorn.txt |
Q:
Discord.py Restart Command
So, i was making a bot and i was wondering if there is a way to restart it using a command like:
p!restart
i did like a command:
p!shutdown
but cant figure out how to restart, for those who came here looking for a shutdown cmd:
async def shutdown(ctx):
id = str(ctx.author.id)
if ... | Discord.py Restart Command | So, i was making a bot and i was wondering if there is a way to restart it using a command like:
p!restart
i did like a command:
p!shutdown
but cant figure out how to restart, for those who came here looking for a shutdown cmd:
async def shutdown(ctx):
id = str(ctx.author.id)
if id == 'your_id_here':
aw... | [
"ctx.bot.logout() only logs your bot out.\nIf you want to fully restart your program, this is how I accomplished it:\nimport sys\nimport os\nfrom discord.ext import commands\n\nbot = commands.Bot\n\ndef restart_bot(): \n os.execv(sys.executable, ['python'] + sys.argv)\n\n@bot.command(name= 'restart')\nasync def re... | [
4,
1,
0
] | [] | [] | [
"discord.py",
"python",
"restart",
"shutdown"
] | stackoverflow_0063180082_discord.py_python_restart_shutdown.txt |
Q:
Is there a more elegant way of finding minimum in array in this case?
What needs to be done in this task:
Determine the amount of couples of neighbouring elements in which both of the numbers are multiple of 7 and also determine a minimal sum of the elements of such couples.
In the actual task I need to read a fil... | Is there a more elegant way of finding minimum in array in this case? | What needs to be done in this task:
Determine the amount of couples of neighbouring elements in which both of the numbers are multiple of 7 and also determine a minimal sum of the elements of such couples.
In the actual task I need to read a file, but here I put elements in the list by myself.
a = [7, 14, 2, 6, 5, 7, 7... | [
"Use float('inf'), which will always compare larger to any other number (except float('inf') and float('nan'), of course).\nSo:\nminSum = float('inf')\n\n",
"It is far more elegant to use the built-in function min to search for a minimum.\nmin_sum = min(\n x + y\n for (x, y) in zip(a, a[1:])\n if x % 7 =... | [
3,
0,
0,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074307591_python_python_3.x.txt |
Q:
Remove adjacent duplicate words in a string with Python?
How would I remove adjacent duplicate words in a string. For example
'Hey there There' -> 'Hey there'
A:
Using re.sub with a backreference we can try:
inp = 'Hey there There'
output = re.sub(r'(\w+) \1', r'\1', inp, flags=re.IGNORECASE)
print(output) # He... | Remove adjacent duplicate words in a string with Python? | How would I remove adjacent duplicate words in a string. For example
'Hey there There' -> 'Hey there'
| [
"Using re.sub with a backreference we can try:\ninp = 'Hey there There'\noutput = re.sub(r'(\\w+) \\1', r'\\1', inp, flags=re.IGNORECASE)\nprint(output) # Hey there\n\nThe regex pattern used here says to:\n(\\w+) match and capture a word\n[ ] followed by a space\n\\1 then followed by the same word (ignorin... | [
9,
3,
0
] | [] | [] | [
"duplicates",
"python",
"string"
] | stackoverflow_0068481155_duplicates_python_string.txt |
Q:
Discord.py ban all members
I am trying to make code that bans all members in a server. This is for educational reasons, do not plan on doing it in a real server. My current code is:
@client.command()
async def d(ctx):
for member in list(ctx.guild.members):
try:
await member.ban(reason="pooooop", ... | Discord.py ban all members | I am trying to make code that bans all members in a server. This is for educational reasons, do not plan on doing it in a real server. My current code is:
@client.command()
async def d(ctx):
for member in list(ctx.guild.members):
try:
await member.ban(reason="pooooop", delete_message_days=7)
p... | [
"\n@client.command()\nasync def massban(ctx):\n for user in ctx.guild.members:\n try:\n await user.ban()\n except:\n pass\n\nyou can loop through all the members and ban them\nyou're code should work anyways\nDocs Ban\n",
"I have done this but instead of banning, I just prin... | [
0,
0,
0,
0,
0
] | [] | [] | [
"discord.py",
"python"
] | stackoverflow_0064342384_discord.py_python.txt |
Q:
when I tried to import resnet50 it says "No module named 'keras.applications.resnet50"
line 6, in <module> from keras.applications.resnet50 import ResNet50, preprocess_input ModuleNotFoundError: No module named 'keras.applications.resnet50'
`
`import numpy as np
import pickle
from keras.applications.resnet50 impo... | when I tried to import resnet50 it says "No module named 'keras.applications.resnet50" | line 6, in <module> from keras.applications.resnet50 import ResNet50, preprocess_input ModuleNotFoundError: No module named 'keras.applications.resnet50'
`
`import numpy as np
import pickle
from keras.applications.resnet50 import ResNet50, preprocess_input
from keras.preprocessing import image
from keras.models import... | [
"from tensorflow.keras.applications.resnet50 import ResNet50\n\n"
] | [
1
] | [] | [] | [
"deep_learning",
"keras",
"python",
"resnet"
] | stackoverflow_0074308776_deep_learning_keras_python_resnet.txt |
Q:
Find the mean based on similar other columns in Pandas
I was looking for a way to find the mean of numerical values based on a certain column. I looked to this link for advice but it requires all values of one column to be the same and I'm sure there's a Pythonic way that would do that for all values that are dupl... | Find the mean based on similar other columns in Pandas | I was looking for a way to find the mean of numerical values based on a certain column. I looked to this link for advice but it requires all values of one column to be the same and I'm sure there's a Pythonic way that would do that for all values that are duplicates.
Here's an example.
data = {
"Name": ["John", "John... | [
"# groupby and mean\ndf.groupby('Name', as_index=False)['Score'].mean()\n\nName Score\n0 Cindy 94.0\n1 John 64.5\n2 Robert 77.0\n3 Sarah 83.5\n\n",
"new_df = df.groupby(['Name'], as_index=False).agg({'Score': pd.Series.mean})\n\n Name Score\n0 Cindy 94.0\n1 John 64.5\n2 Robert ... | [
1,
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074308768_pandas_python.txt |
Q:
Discord Python, creating a Channel and moving directly people to it?
I already created this code:
#Creating the Channel
guild = bot.get_guild(771495836701425725)
await guild.create_voice_channel(f"Rainbow Ranked for {members2move}", category=940356081891287110, user_limit=members2move)
prin... | Discord Python, creating a Channel and moving directly people to it? | I already created this code:
#Creating the Channel
guild = bot.get_guild(771495836701425725)
await guild.create_voice_channel(f"Rainbow Ranked for {members2move}", category=940356081891287110, user_limit=members2move)
print("Created a new Voice Channel!")
print(f"Moving {members2move} Pe... | [
"create_voice_channel returns the channel and you can access a channel's id,\napparently you have to pass a channel object to the move_member function not just the id\n#Creating the Channel\n guild = bot.get_guild(771495836701425725)\n v_channel = await guild.create_voice_channel(f\"Rainbow Ranked for... | [
1,
0,
0
] | [] | [] | [
"discord",
"discord.py",
"python"
] | stackoverflow_0071400037_discord_discord.py_python.txt |
Q:
What's the best way to escape a bash command in python?
I have a function that takes in a command as a string, and runs it on an AWS container using the aws binary.
The command adds a few extra symbols before and after the command the user requested to run - I won't get into why.
def run_command_on_aws_container(c... | What's the best way to escape a bash command in python? | I have a function that takes in a command as a string, and runs it on an AWS container using the aws binary.
The command adds a few extra symbols before and after the command the user requested to run - I won't get into why.
def run_command_on_aws_container(command: str, aws_info):
full_command = f"bash -c 'echo -n... | [
"shlex.quote() is designed specifically for this:\nfull_command = \"bash -c \" + shlex.quote(f'echo -n \"|\"; {command}; echo -n \"|\"')\n\n"
] | [
3
] | [] | [] | [
"bash",
"python"
] | stackoverflow_0074308630_bash_python.txt |
Q:
ImportError: cannot import name 'db' from 'database_functions'
I'm trying to connect to a Postgres database using Flask and SQLAlchemy.
I followed an youtube tutorial however it doesn't seem to work for me, as it throws an error normally associated with circular dependencies.
When i type on the Python console: fro... | ImportError: cannot import name 'db' from 'database_functions' | I'm trying to connect to a Postgres database using Flask and SQLAlchemy.
I followed an youtube tutorial however it doesn't seem to work for me, as it throws an error normally associated with circular dependencies.
When i type on the Python console: from database_functions import db it says:
Traceback (most recent call ... | [
"This is likely a scoping issue. In your file pasted above, the db variable is not available at the module level since it's defined inside of an if block.\nif __name__ == '__main__': is typically used when you want a file to be directly executable but not have the executable code at the module level.\nFor example:\... | [
0
] | [] | [] | [
"flask",
"flask_sqlalchemy",
"python"
] | stackoverflow_0074308785_flask_flask_sqlalchemy_python.txt |
Q:
Jupyter installation requiring C++ 14.0 on Windows 11
I'm trying to install Jupyter in a Python 3.11 installation (from python.org). It errors out with error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/. I hav... | Jupyter installation requiring C++ 14.0 on Windows 11 | I'm trying to install Jupyter in a Python 3.11 installation (from python.org). It errors out with error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/. I have found other similar questions (such as this one), but fol... | [
"No it won't install in 3.11 for now! Although it may be mentioned as a stable release on the python.org site in the downloads section.\nA stable version basically means that most of the packages/libraries should get installed easily. Jupyter being no exception.\nI remember 3.7 being a popular choice of being the s... | [
0
] | [] | [] | [
"jupyter",
"python",
"python_3.x"
] | stackoverflow_0074240881_jupyter_python_python_3.x.txt |
Q:
How to get a user's avatar with their id in discord.py?
I tried using the following code but it didn't work.
@bot.command()
async def avatar(ctx,*, avamember):
user = bot.get_user(avamember)
await ctx.send(f"{user.avatar_url}")
Edit: For anyone that had a similar problem, while not mentioned in the docs, ... | How to get a user's avatar with their id in discord.py? | I tried using the following code but it didn't work.
@bot.command()
async def avatar(ctx,*, avamember):
user = bot.get_user(avamember)
await ctx.send(f"{user.avatar_url}")
Edit: For anyone that had a similar problem, while not mentioned in the docs, discord.Member can take user ids aside from @username so ther... | [
"I'm presuming you're Tagging the user with @UserNameHere in discord. It's much easier to take that input as a member Object :)\nYou also don't need to wrap the url in quotes.\nThis code is if it is in a cog:\n@commands.command()\nasync def avatar(self, ctx, *, avamember : discord.Member=None):\n userAvatarUrl ... | [
4,
0,
0,
0
] | [
"A more optimized version of the code:\n@bot.command()\nasync def get_user_icon(ctx, member:discord.Member):\n await ctx.send(member.avatar_url)\n\n"
] | [
-4
] | [
"discord",
"discord.py",
"python"
] | stackoverflow_0059799987_discord_discord.py_python.txt |
Q:
Discord.py --> channel.mention
I'm trying to make a bot for a discord server that simply listens for specific messages, deletes them and then refers the user to a different text channel (in a clickable link by mentioning it)
Here's what I have now:
import Discord
import asyncio
client = discord.Client()
@client.... | Discord.py --> channel.mention | I'm trying to make a bot for a discord server that simply listens for specific messages, deletes them and then refers the user to a different text channel (in a clickable link by mentioning it)
Here's what I have now:
import Discord
import asyncio
client = discord.Client()
@client.event
async def on_message(message... | [
"Don't know if your problem is solved or not, but for all future developers looking on this thread. A super simple way to get a bot to mention a channel is like this...\n<#channelID>\n\nwere the channel ID is the discord ID of the specific channel you wish to mention.\nand in an example\nawait message.channel.send(... | [
12,
1,
0
] | [] | [] | [
"discord",
"discord.py",
"python"
] | stackoverflow_0052132913_discord_discord.py_python.txt |
Q:
How can I cumulatively sum defaultdict with same parameter? (Python)
I recently started using defaultdict in python.
When ım using defaultdict ı struggled to cumulative sum with same parameter.
In my case ı have defaultdict like that:
defaultdict(<class 'list'>,
{'11106000022': [(216.0, datetime.datetime(2... | How can I cumulatively sum defaultdict with same parameter? (Python) | I recently started using defaultdict in python.
When ım using defaultdict ı struggled to cumulative sum with same parameter.
In my case ı have defaultdict like that:
defaultdict(<class 'list'>,
{'11106000022': [(216.0, datetime.datetime(2022, 10, 5, 0, 0)),
(216.0, datetime.datetime(202... | [
"data = defaultdict(...)\nfor key, val in data.items():\n sums_by_date = defaultdict(float)\n for item in val:\n sums_by_date[item[1]] += item[0]\n data[key] = [(v, k) for k, v in sums_by_date.items()]\n\nwhich results in\n{'11106000022': [(432.0, datetime.datetime(2022, 10, 5, 0, 0)), (480.0, datet... | [
1
] | [] | [] | [
"defaultdict",
"python"
] | stackoverflow_0074305668_defaultdict_python.txt |
Q:
Sending embeds through discord.py
I've been doing a lot of work creating discord bots with the discord api through javascript with discord.js.
I am trying to create my first discord bot with python using the discord api through discord.py and with requests through requests.py.
My goal is to check status code on a ... | Sending embeds through discord.py | I've been doing a lot of work creating discord bots with the discord api through javascript with discord.js.
I am trying to create my first discord bot with python using the discord api through discord.py and with requests through requests.py.
My goal is to check status code on a site, and when a message is sent that c... | [
"Okay working down your list of questions:\n\nYou're not formatting {r.status_code} but just sending it as a string which is why it shows up as just that. To fix it, all you have to do is add 1 \"f\".\n\nembed.description = f'**Status Code:** {r.status_code}'\n\nor, if you want to use a consistent way of formatting... | [
0,
0,
0,
0
] | [] | [] | [
"discord",
"discord.py",
"python"
] | stackoverflow_0060245575_discord_discord.py_python.txt |
Q:
durable-rules python how to negate a statement
How do I negate a statement? https://pypi.org/project/durable-rules/
I would like something like this but the ! doesn't work.
with ruleset('awv'):
@when_all(m.visits.anyItem(item.cpt_codes.anyItem( item.matches('G0438') | item.matches('G0439') )))
def had_awv_... | durable-rules python how to negate a statement | How do I negate a statement? https://pypi.org/project/durable-rules/
I would like something like this but the ! doesn't work.
with ruleset('awv'):
@when_all(m.visits.anyItem(item.cpt_codes.anyItem( item.matches('G0438') | item.matches('G0439') )))
def had_awv_exam_or_awv_visit_more_than_12_month(c):
pri... | [
"Maybe - is what you are searching for... At least it looks like that to some extend in the documentation, but I don't know enough about the framework to tell whether it really does what you want.\nIf it doesn't, I'd suggest to manually negate your statement:\n@when_all(m.visits.anyItem( item.cpt_codes.allItems( (i... | [
1
] | [] | [] | [
"durable_rules",
"python"
] | stackoverflow_0074308296_durable_rules_python.txt |
Q:
Flask Python Google OAuth - Client Id not found
I'm trying to implement Google OAuth2 into my webapp, using the demo source code provided by Google: https://github.com/authlib/demo-oauth-client/tree/master/flask-google-login , but I'm getting "Authorisation Error Error 401: invalid_client The OAuth client was not ... | Flask Python Google OAuth - Client Id not found | I'm trying to implement Google OAuth2 into my webapp, using the demo source code provided by Google: https://github.com/authlib/demo-oauth-client/tree/master/flask-google-login , but I'm getting "Authorisation Error Error 401: invalid_client The OAuth client was not found".
In the URL queryString I can also see &client... | [
"I solved the issue by doing the following:\n\nRemoving the trailing '/' from the Authorised redirect URIs in Google Console, Credentials section.\nAdded client_id = app.config['GOOGLE_CLIENT_ID'] to oauth.register\n\n"
] | [
0
] | [] | [] | [
"flask",
"oauth",
"python"
] | stackoverflow_0074306768_flask_oauth_python.txt |
Q:
What risks are associated with formatting a string before passing it to pandas.eval?
I do a lot of queries on dataframes in pandas. pandas.DataFrame.query takes human-readable strings that represent dataframe operations and then evaluates them with pandas.eval (documented here). As discussed in this question, I'd ... | What risks are associated with formatting a string before passing it to pandas.eval? | I do a lot of queries on dataframes in pandas. pandas.DataFrame.query takes human-readable strings that represent dataframe operations and then evaluates them with pandas.eval (documented here). As discussed in this question, I'd like to write functions like the ones below that compile the query strings in a way that d... | [
"\nI've been told that formatting strings that are about to be eval'd is \"an extremely slippery slope\" but I'm not sure why.\n\nI think that's generally good advice. I think there are some problems which can only be solved with eval(), but 99% of the code which uses eval() can be more easily and more safely solve... | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074308558_pandas_python.txt |
Q:
How to delete json files if they contain a specific key/value
I have a directory of json files. I want to delete the files that have this in them.
{
"error": "not_found",
"message": "Can't find",
"value": "item"
}
This is 2 versions of what I have now. The error says "string indices must be integers" ... | How to delete json files if they contain a specific key/value | I have a directory of json files. I want to delete the files that have this in them.
{
"error": "not_found",
"message": "Can't find",
"value": "item"
}
This is 2 versions of what I have now. The error says "string indices must be integers" so I think how I'm writing the syntax wrong. But I can't find the s... | [
"It's because when you are doing:\nfile for file in data\n\nfile is a str, because it's each key in the dictionary data.\n# over a sample dictionary\ndata = {'here': None, 'is': None, 'content': None}\n\nfor k in data:\n print(k, type(k))\n\n# prints each key and the type 'str'\nhere <class 'str'>\nis <class 'st... | [
0
] | [] | [] | [
"json",
"python"
] | stackoverflow_0074309021_json_python.txt |
Q:
Discord.py how to delete all roles in server
I'm trying to delete all roles in my discord server, but it takes a huge amount of time. So I decided to do this task with discord.py bot, but I'm getting this error:
discord.errors.HTTPException: 400 Bad Request (error code: 50028): Invalid Role
Here's my code:
@clie... | Discord.py how to delete all roles in server | I'm trying to delete all roles in my discord server, but it takes a huge amount of time. So I decided to do this task with discord.py bot, but I'm getting this error:
discord.errors.HTTPException: 400 Bad Request (error code: 50028): Invalid Role
Here's my code:
@client.command()
async def delroles(ctx):
for role in... | [
"The problem is that all users have an \"invisible role\" called @everyone, which is impossible to remove.\nDo:\nasync def delroles(ctx):\n for role in ctx.guild.roles: \n try: \n await role.delete()\n except:\n await ctx.send(f\"Cannot delete {role.name}\")\n\n",
"import discord\nfrom dis... | [
3,
0
] | [] | [] | [
"discord",
"discord.py",
"python"
] | stackoverflow_0068820168_discord_discord.py_python.txt |
Q:
Hierarchical string delimiting not splitting
I am trying to create a function to parse a string based on multiple delimiters, but in a hierarchical format: i.e., try the first delimiter, then the second, then the third, etc.
This question seemingly provides a solution, specifically linking this comment.
# Split th... | Hierarchical string delimiting not splitting | I am trying to create a function to parse a string based on multiple delimiters, but in a hierarchical format: i.e., try the first delimiter, then the second, then the third, etc.
This question seemingly provides a solution, specifically linking this comment.
# Split the team names, with a hierarchical delimiter
def sp... | [
"Execute the \"nothing worked\" fallback AFTER trying all delimiters:\nfor d in delims:\n result = inp.split(d, maxsplit=1)\n if len(result) == 2: \n return result\nreturn [inp] # If nothing worked, return the input \n\n",
"As an alternative, instead of looping the delimiters, you might use a single... | [
2,
0,
0
] | [] | [] | [
"delimiter",
"python",
"split",
"string"
] | stackoverflow_0074308951_delimiter_python_split_string.txt |
Q:
pyautogui moveto not working(has correct coords)
import pyautogui
while True:
test = pyautogui.locateCenterOnScreen('test.png',region=[600,570,680,570],grayscale=False,confidence=.6)
if test:
pyautogui.moveTo(1000,1000)
print(str(test),'found',test.x,test.y)
break
The print stateme... | pyautogui moveto not working(has correct coords) | import pyautogui
while True:
test = pyautogui.locateCenterOnScreen('test.png',region=[600,570,680,570],grayscale=False,confidence=.6)
if test:
pyautogui.moveTo(1000,1000)
print(str(test),'found',test.x,test.y)
break
The print statement is getting run(so its not that the if statement is ... | [
"With further inspection/test, visual studio code has to be run as admin in order for (moveto) to work while it's not a focused application. This said, if you are using (moveto) and visual studio code has focus, (moveto) will work.\nIn conclusion, run VS CODE as admin for (moveto) to work correctly.\n"
] | [
0
] | [] | [] | [
"pyautogui",
"python"
] | stackoverflow_0074308512_pyautogui_python.txt |
Q:
How to integrate two models in sequential order in one endpoint?
I want to create an API using one endpoint but in my app, the first model output is the second model output. Is it possible to implement using SageMaker?
From my understanding model_fn, prediction_fn, output_fn can only use one model at a time.
A:
... | How to integrate two models in sequential order in one endpoint? | I want to create an API using one endpoint but in my app, the first model output is the second model output. Is it possible to implement using SageMaker?
From my understanding model_fn, prediction_fn, output_fn can only use one model at a time.
| [
"Pipeline Model (sequential models)\nThere is a specific mode in SageMaker:\nLook at PipelineModel.\n\nYou can pass a list of sagemaker.Model objects in the order you want\nthe inference to happen.\n\nThis is an official AWS example to follow:\nTrain register and deploy a pipeline model\nfrom sagemaker import Pipel... | [
1
] | [] | [] | [
"amazon_sagemaker",
"machine_learning",
"python"
] | stackoverflow_0074308758_amazon_sagemaker_machine_learning_python.txt |
Q:
Why is my sqlite3 program saying "column not found"?
I want to make a levelling system for my Discord bot. I imported datetime and sqlite3:
@client.event
async def on_member_join(member): ###add a row in the db for the new member when they join
user = member.id
conn = sqlite3.connect('level.db')
cur = con... | Why is my sqlite3 program saying "column not found"? | I want to make a levelling system for my Discord bot. I imported datetime and sqlite3:
@client.event
async def on_member_join(member): ###add a row in the db for the new member when they join
user = member.id
conn = sqlite3.connect('level.db')
cur = conn.cursor()
cur.execute('CREATE TABLE IF NOT EXISTS leve... | [
"The first problem is with the table creation:\nIn [1]: import sqlite3\n\nIn [2]: conn = sqlite3.connect(':memory:')\nOut[2]: <sqlite3.Connection at 0x8738a53f0>\n\nIn [3]: cur = conn.cursor()\nOut[3]: <sqlite3.Cursor at 0x873faa340>\n\nIn [4]: cur.execute('CREATE TABLE IF NOT EXISTS levels INSERT INTO levels(\"use... | [
0
] | [] | [] | [
"discord",
"discord.py",
"python",
"python_3.x",
"sqlite"
] | stackoverflow_0074307765_discord_discord.py_python_python_3.x_sqlite.txt |
Q:
solved : launch uvicorn with external defined port
I need to launch a microservice based on fastapi/uvicorn and running on a port defined in a config.ini file.
Here is my code
config.ini
[application]
version = 0.1.0
appName = kakarot
port = 8001
description = MicroService M1
main.py
`
from fastapi import Fast... | solved : launch uvicorn with external defined port | I need to launch a microservice based on fastapi/uvicorn and running on a port defined in a config.ini file.
Here is my code
config.ini
[application]
version = 0.1.0
appName = kakarot
port = 8001
description = MicroService M1
main.py
`
from fastapi import FastAPI
import configparser
# -------------- settings -----... | [
"How are you parsing the ini file, the vital content to judge what's going on is missing from your question. Have you checked the value of APP_PORT with a break point or print statement?\nCompare your setup to the following working example;\nimport configparser\n\nconfig = configparser.ConfigParser()\nconfig.read('... | [
0
] | [] | [] | [
"fastapi",
"python",
"uvicorn"
] | stackoverflow_0074308096_fastapi_python_uvicorn.txt |
Q:
Subtracting elements from sorted dictionary in Python
I have a sorted dictionary (here the bids of an order book) with the following form, where the items in the parentheses are {price: amount} and sorted.
bids = SortedDict({0.0005: 11.0, 0.006: 10.0, 0.01: 28.6, 0.0105: 21.8, 0.012: 25.1})
I also know my own quo... | Subtracting elements from sorted dictionary in Python | I have a sorted dictionary (here the bids of an order book) with the following form, where the items in the parentheses are {price: amount} and sorted.
bids = SortedDict({0.0005: 11.0, 0.006: 10.0, 0.01: 28.6, 0.0105: 21.8, 0.012: 25.1})
I also know my own quotes, which are:
own_bids = [{0.006: 10.0}, {0.012: 5.1}]
M... | [
"If I understand you correctly, you want to substract own_bids from bids and filter the zero values out:\nbids = {0.0005: 11.0, 0.006: 10.0, 0.01: 28.6, 0.0105: 21.8, 0.012: 25.1}\nown_bids = [{0.006: 10.0}, {0.012: 5.1}]\n\ntmp = {k: v for d in own_bids for k, v in d.items()}\n\nnew_bids = {\n k: new_val for k,... | [
2,
1,
0
] | [] | [] | [
"dictionary",
"python",
"sorteddictionary",
"subtraction"
] | stackoverflow_0074156060_dictionary_python_sorteddictionary_subtraction.txt |
Q:
I want to tag a person who clicks a button discord.py
components = [
[
Button(label="Open a ticket", style=2, custom_id="Open", emoji="")
]
]
await ctx.send(embed=embed, components=components )
while True:
interaction = await client.wait_for("button_click", check = lambda i: i.component.label.s... | I want to tag a person who clicks a button discord.py |
components = [
[
Button(label="Open a ticket", style=2, custom_id="Open", emoji="")
]
]
await ctx.send(embed=embed, components=components )
while True:
interaction = await client.wait_for("button_click", check = lambda i: i.component.label.startswith("Open"))
overwrites = {
member_role... | [
"Instead of ctx.author.name (ctx.author is a discord.member class)\nUse ctx.author.mention\nDocs:\nhttps://discordpy.readthedocs.io/en/stable/api.html?highlight=mention#discord.Member.mention\n",
"i've resolved using the library of discord.py (interaction) instead of this i used the object (user.name)\n",
"impo... | [
1,
0,
0
] | [] | [] | [
"discord",
"discord.py",
"python",
"python_3.x"
] | stackoverflow_0072595288_discord_discord.py_python_python_3.x.txt |
Q:
How to remove space from variable and put a character instead of space in python?
My Python code looks like
name = 'my full name'
And i wanna print this texts be like
https://example.com/?s=my+full+name
So How can i remove space and put that '+'?
I want the example code and with explanation if possible.
A:
Als... | How to remove space from variable and put a character instead of space in python? | My Python code looks like
name = 'my full name'
And i wanna print this texts be like
https://example.com/?s=my+full+name
So How can i remove space and put that '+'?
I want the example code and with explanation if possible.
| [
"Also you can write like this\nname=\"my full name\"\nname1=[] #To store the string(modified)\nfor _ in range(len(name)):\n if name[_]==' ': #condition \n name1.remove(name[_-1])#removes the last appended element\n\n\nname1.append(name[_-1]+\"+\")#appends concatenate last element with '+'\nelse:\n name1.app... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074308655_python.txt |
Q:
Python dataframe from a nested list and dictionaries
I have a nested list of dictionaries and lists as below:
my_list = [{'a1':'1','b1':[{'c11':'2','d11':'3','e11':'4','f11':'5'},{'c12':'6','d12':'7','e12':'8','f12':'9'}],
'g1':'10','h1':'11'},
{'a2':'12','b2':[{'c21':'13','d21':'14','e21':'15','f21':'16'},{'c22'... | Python dataframe from a nested list and dictionaries | I have a nested list of dictionaries and lists as below:
my_list = [{'a1':'1','b1':[{'c11':'2','d11':'3','e11':'4','f11':'5'},{'c12':'6','d12':'7','e12':'8','f12':'9'}],
'g1':'10','h1':'11'},
{'a2':'12','b2':[{'c21':'13','d21':'14','e21':'15','f21':'16'},{'c22':'17','d22':'18','e22':'19','f22':'20'}],
'g2':'21','h2':'... | [
"You could iterate over the list of dictionaries first to flatten each row.\nimport re\n\ndef remove_first_digit(s):\n return re.sub(r'[0-9]', '', s, 1)\n\ndef flatten_row(d, flattened):\n \"\"\"Recursively iterate through the dict d, saving any (str: str)\n key-value pairs we find in the flattened dict... | [
2
] | [] | [] | [
"dataframe",
"multidimensional_array",
"nested_loops",
"pandas",
"python"
] | stackoverflow_0074308977_dataframe_multidimensional_array_nested_loops_pandas_python.txt |
Q:
How to extract values from a loop that stop at a specified n
I am trying to create tuples from 2 input. For example, my program will ask how many people is there. Let's say I write 3. The program will ask profession of each one and his salary. After that, I want the program to display a tuple containing (professio... | How to extract values from a loop that stop at a specified n | I am trying to create tuples from 2 input. For example, my program will ask how many people is there. Let's say I write 3. The program will ask profession of each one and his salary. After that, I want the program to display a tuple containing (profession, salary) is ascending order of salary.
What im trying to achieve... | [
"You need to save the pair in a main list, then print the list\nvalues = []\nnumber_person = int(input(\"Write the number of person: \"))\nfor i in range(number_person):\n profession = input(\"Write profession: \")\n salary = int(input(\"Write salary: \"))\n values.append((profession, salary))\n\nfor item ... | [
0,
0
] | [] | [] | [
"dictionary",
"for_loop",
"loops",
"python",
"tuples"
] | stackoverflow_0074308911_dictionary_for_loop_loops_python_tuples.txt |
Q:
Solving palindromic 'Triangle Quest' puzzle in Python
I'm trying to solve this programming puzzle:
You are given a positive integer N (0 < N < 10). Your task is to print a
palindromic triangle of size N.
For example, a palindromic triangle of size 5 is:
1
121
12321
1234321
123454321
You can't take more than tw... | Solving palindromic 'Triangle Quest' puzzle in Python | I'm trying to solve this programming puzzle:
You are given a positive integer N (0 < N < 10). Your task is to print a
palindromic triangle of size N.
For example, a palindromic triangle of size 5 is:
1
121
12321
1234321
123454321
You can't take more than two lines. You have to complete the code
using exactly one ... | [
"for i in range(1,int(input())+1):\n print(int((10**i-1)/9)**2)\n\n1 -> ( 10 - 1) / 9 = 1, 1 * 1 = 1\n2 -> ( 100 - 1) / 9 = 11, 11 * 11 = 121\n3 -> ( 1000 - 1) / 9 = 111, 111 * 111 = 12321\n4 -> (10000 - 1) / 9 = 1111, 1111 * 1111 = 1234321\n\n",
"I ended up doing the following (thanks @rai... | [
11,
10,
6,
5,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [] | [] | [
"palindrome",
"python",
"python_3.x"
] | stackoverflow_0034494247_palindrome_python_python_3.x.txt |
Q:
Match a number of letters based on how many numbers are matched using Regex
I'm trying to create a regex pattern to match account ids following certain rules. This matching will occur within a python script using the re library, but I believe the question is mostly just a regex in general issue.
The account ids ad... | Match a number of letters based on how many numbers are matched using Regex | I'm trying to create a regex pattern to match account ids following certain rules. This matching will occur within a python script using the re library, but I believe the question is mostly just a regex in general issue.
The account ids adhere to the following rules:
Must be exactly 6 characters long
The letters and n... | [
"I am unsure how to modify your regex to ensure that the overall username length is 6 characters. However, it would be extremely easy to check that in python.\nimport re\n\ndef check_username(name):\n if len(name) == 6:\n if re.search(\"((?=^[0-9])[0-9]{1,6}[A-Z]{0,5}$)|((?=^[A-Z])[A-Z]{3}[0-9]{3}$)\", n... | [
1,
1
] | [] | [] | [
"python",
"python_re",
"regex"
] | stackoverflow_0074307054_python_python_re_regex.txt |
Q:
Calculating a week beginning date in Python, starting on Monday
I have a dataframe with columns 'Transaction_Date' and 'Day_of_Week'. The former is a datetime64 format, the latter the day of the week spelled out. I'm trying to create a separate column called 'Week_of', which begins on Mondays. Specifically, if a... | Calculating a week beginning date in Python, starting on Monday | I have a dataframe with columns 'Transaction_Date' and 'Day_of_Week'. The former is a datetime64 format, the latter the day of the week spelled out. I'm trying to create a separate column called 'Week_of', which begins on Mondays. Specifically, if a row's 'Transaction_Date' has a 'Day_of_Week' of Monday, then I want ... | [
"Here's why this is a problem.\n# Create a value for Week_of date\nif df[df['Day_of_Week']=='Monday']:\n df['Week_of'] = df[df['Transaction_Date']]\n\nThere are (probably) many rows where \"Day_of_Week\" is \"Monday\". So, what is the if statement supposed to check? How does it come up with one true/false deci... | [
0
] | [] | [] | [
"datetime",
"pandas",
"python"
] | stackoverflow_0074309151_datetime_pandas_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.