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: Scrape the feature image from this website but it returns this `data:image/gif Using Scrapy and Scrapy shell in python to scrape the feature image from this website https://www.thrillist.com/travel/nation/all-the-ways-to-cool-off-in-austin but it returns this data:image/gif;base64,R0 instead of src of the image, I...
Scrape the feature image from this website but it returns this `data:image/gif
Using Scrapy and Scrapy shell in python to scrape the feature image from this website https://www.thrillist.com/travel/nation/all-the-ways-to-cool-off-in-austin but it returns this data:image/gif;base64,R0 instead of src of the image, I need the help of someone if any one tell me the way to fix this to get src of the ...
[ "The biggest image on that page would be the one marked (somehow) for Desktop - common sense logic. So why not try to locate its source like below?\npic = response.xpath('//picture[@data-testid=\"picture-tag\"]//source[@data-size=\"desktop\"]/@srcset').get()\n\nResult is the source for the biggest size for that pag...
[ 2, 1 ]
[]
[]
[ "python", "scrapy", "scrapy_shell", "web_scraping", "xpath" ]
stackoverflow_0074120927_python_scrapy_scrapy_shell_web_scraping_xpath.txt
Q: python move file to another folder, rename if file same name already exist how to move .dat file to another folder, rename to file(1).dat if same file name exist. *(1) increase the more file same name exist. current code: src_fldr = r"C:\OUTBOX" dst_fldr = "C:\\OUTBOX\\OUTBOX(Backup)" path = Path(".") # current...
python move file to another folder, rename if file same name already exist
how to move .dat file to another folder, rename to file(1).dat if same file name exist. *(1) increase the more file same name exist. current code: src_fldr = r"C:\OUTBOX" dst_fldr = "C:\\OUTBOX\\OUTBOX(Backup)" path = Path(".") # current directory extension = ".dat" for dat_file in glob.glob(src_fldr+"\\*.dat"): ...
[ "To move the file without risking of overwriting it, you should check if it exists first, and, if so, add a counter to the filename. Pathlib's path can help you with that:\nfrom pathlib import Path\nimport shutil\n\nsrc_fldr = Path(r\"C:\\OUTBOX\")\ndst_fldr = Path(r\"C:\\OUTBOX\\OUTBOX(Backup)\")\nextension = \".d...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074119832_python.txt
Q: Selenium problem with ElementClickInterceptedException I am trying to scraping in this URL, dealing with a Download button and I am having a problem, as the last line gives a ElementClickInterceptedException. My actual goal is to download the CSV file. The code: from selenium import webdriver from selenium.webdriv...
Selenium problem with ElementClickInterceptedException
I am trying to scraping in this URL, dealing with a Download button and I am having a problem, as the last line gives a ElementClickInterceptedException. My actual goal is to download the CSV file. The code: from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.s...
[ "\nElement you trying to click in initially out of the visible viewpoint. So, you need first to scroll the page and only then to click on that element.\nBy clicking the first element new tab is opened and the second element you want to click is there, on the second tab. So, you need to switch to the new tab to acce...
[ 0 ]
[]
[]
[ "python", "selenium", "selenium_chromedriver", "selenium_webdriver", "webdriverwait" ]
stackoverflow_0074124006_python_selenium_selenium_chromedriver_selenium_webdriver_webdriverwait.txt
Q: Custom QuerySet for a Django admin action # Customers model Customers(models.Model): name = models.CharField(max_length=255) emails = ArrayField(models.EmailField(), default=list, blank=True) ... ... ... I have a QuerySet which has all the information according to the model of all the selecte...
Custom QuerySet for a Django admin action
# Customers model Customers(models.Model): name = models.CharField(max_length=255) emails = ArrayField(models.EmailField(), default=list, blank=True) ... ... ... I have a QuerySet which has all the information according to the model of all the selected customers. # Django admin action def ge...
[ "I used the following way to get the desired data.\nCustomers.objects.filter(is_active=True)\n .annotate(\n emails =Func(F(\"emails\"), function=\"unnest\")\n )\n .values(\n \"name\",\n \"emails\",\n )\n .distinct()\n\n" ]
[ 0 ]
[]
[]
[ "django", "django_admin", "django_queryset", "python" ]
stackoverflow_0074014403_django_django_admin_django_queryset_python.txt
Q: Select only non zero values from a matrix using another matrix python numpy I have two arrays mp of shape (240, 480) and pop_fts_norm which is an array of length N of arrays of shape (240, 480). I want to create an array of length N with values from mp but only where elements of x are != 0, for each array x in pop...
Select only non zero values from a matrix using another matrix python numpy
I have two arrays mp of shape (240, 480) and pop_fts_norm which is an array of length N of arrays of shape (240, 480). I want to create an array of length N with values from mp but only where elements of x are != 0, for each array x in pop_fts_norm. Inefficient code: full_mp = np.array([np.array([mp[i][j] if (x != 0)[i...
[ "full_mp = np.array([np.where(x != 0, mp, 0) for x in pop_fts_norm])\nfull_mp.shape\n\nFound a solution.\n", "You can transform your matrices in the array to a set of 0 and 1, and after that you can just multiply elementwise the two matrix to get the result:\nfor x in pop_fts_norm:\n x[x!=0] = 1\n\nfull_mp = n...
[ 1, 0 ]
[]
[]
[ "numpy", "performance", "python" ]
stackoverflow_0074124033_numpy_performance_python.txt
Q: Split python array into equally-sized chunks and omit elements at indexes I need to iterate indexes from e.g. 0-6, 30-36, 60-66 etc and omit the values at indexes in between. I found sth like this for splitting into equal chunks but did not find a way to exclude specific indexes... def chunks(xs, n): n = max(1, n)...
Split python array into equally-sized chunks and omit elements at indexes
I need to iterate indexes from e.g. 0-6, 30-36, 60-66 etc and omit the values at indexes in between. I found sth like this for splitting into equal chunks but did not find a way to exclude specific indexes... def chunks(xs, n): n = max(1, n) return (xs[i:i+n] for i in range(0, len(xs), n)) Does anyone has a hint? Than...
[ "Change your function to\ndef chunks(xs, n):\n steps = 30 # you should also give the steps in your case it is 30\n n = max(1, n)\n return (xs[i:i+n] for i in range(0, len(xs), steps)) # Also this will be returning generator if you want list then use [xs[i:i+n] for i in range(0, len(xs), steps)]\n\n" ]
[ 0 ]
[]
[]
[ "arrays", "chunks", "python", "slice", "split" ]
stackoverflow_0074124291_arrays_chunks_python_slice_split.txt
Q: Exception Type: KeyError when registering a new user using a custom made register model Whenever I try to register a new user when i receive an Exception Type: KeyError error. There seem to be something wrong with the submitted password but I don't understand the issue in depth. Can someone please explain this err...
Exception Type: KeyError when registering a new user using a custom made register model
Whenever I try to register a new user when i receive an Exception Type: KeyError error. There seem to be something wrong with the submitted password but I don't understand the issue in depth. Can someone please explain this error to me? And perhaps how to solve it as well. The user is created, I can see that in the adm...
[ "Try this and check if it works\nin\ndef createaccount(request):\n ...............\n if request.method == \"POST\":\n form = CustomUserRegisterForm(request.POST,instance = request.user) \n\n", "It is not 100% obvious what you are trying to do. Is UserRegister meant to be a model for your base use...
[ 0, 0 ]
[]
[]
[ "custom_model_binder", "django", "error_handling", "python" ]
stackoverflow_0074079335_custom_model_binder_django_error_handling_python.txt
Q: telegram bot reply message for buttons recently i created a telegram bot using python and i added keyboard button features to the bot. However, i am having difficulties in getting replies from bot to the buttons users choose. button7 = KeyboardButton('About Us',request_contact= False) keyboard2 = ReplyKeyboardMark...
telegram bot reply message for buttons
recently i created a telegram bot using python and i added keyboard button features to the bot. However, i am having difficulties in getting replies from bot to the buttons users choose. button7 = KeyboardButton('About Us',request_contact= False) keyboard2 = ReplyKeyboardMarkup(resize_keyboard = True, one_time_keyboard...
[ "Try it:\nmarkup = types.InlineKeyboardMarkup()\nbutton1 = types.InlineKeyboardButton(text='Ukraine', url=\"https://en.wikipedia.org/wiki/Ukraine\", callback_data='1')\nmarkup.add(button1)\nbot.send_message(message.from_user.id, 'Do you know?, parse_mode='Markdown', reply_markup=markup)\n\n", "Text (inline button...
[ 0, 0 ]
[]
[]
[ "keyboard", "python", "telegram", "telegram_bot" ]
stackoverflow_0074049643_keyboard_python_telegram_telegram_bot.txt
Q: Scraping a website with selenium in python: Problem in clicking "download images" Buttons Good morning. I am new in using python and webscraping. I have to download a series of images from this link (just the last part of the urll change for the following pages): https://historisch.cbs.nl/detail.php?nav_id=0-1&ind...
Scraping a website with selenium in python: Problem in clicking "download images" Buttons
Good morning. I am new in using python and webscraping. I have to download a series of images from this link (just the last part of the urll change for the following pages): https://historisch.cbs.nl/detail.php?nav_id=0-1&index=2&id=30568043 What I want to do is click on the two download buttons in order that at the en...
[ "You're trying to click on a button located in an iframe. You need to switch to that iframe first, then locate the button, then click on it:\nWebDriverWait(browser, 5).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH, '//iframe[@class=\"detail-media-viewer\"]')))\nt.sleep(5) ## let elements within iframe l...
[ 0 ]
[]
[]
[ "button", "download", "python", "selenium", "web_scraping" ]
stackoverflow_0074121865_button_download_python_selenium_web_scraping.txt
Q: Translate loop in numpy methods I need to get the cumulative maximum of array longband until its [i-1] value is >= of RsiMa[i], then turn to its "real" [i] value and restart cumulating. Actually the only way I found to achieve this is by a for loop. Is it translatable to numpy? How can I convert it? THE CODE: impo...
Translate loop in numpy methods
I need to get the cumulative maximum of array longband until its [i-1] value is >= of RsiMa[i], then turn to its "real" [i] value and restart cumulating. Actually the only way I found to achieve this is by a for loop. Is it translatable to numpy? How can I convert it? THE CODE: import numpy as np RsiMa = np.array([ 2...
[ "This method do not prodice any improvement, but at least works:\n### vector function ###\ndef vect(array1, array2, counter):\n if (array1[counter-1] > array1[counter] and array1[counter-1] < array2):\n array1[counter] = array1[counter-1]\n return array1[counter]\n\nvvect = np.vectorize(vect, exclude...
[ 0 ]
[]
[]
[ "arrays", "loops", "numpy", "python", "vectorization" ]
stackoverflow_0074086852_arrays_loops_numpy_python_vectorization.txt
Q: Changing Chart Legend Colors, build own chart color scheme - Openpyxl 2.4.9 I know you are able to change chart colors with the .style = number, however none of the existing color schemes work for what I need. I would like to build my own chart color scheme. What I would like to know is where would I do that. Wher...
Changing Chart Legend Colors, build own chart color scheme - Openpyxl 2.4.9
I know you are able to change chart colors with the .style = number, however none of the existing color schemes work for what I need. I would like to build my own chart color scheme. What I would like to know is where would I do that. Where are the .style numbers located in the library. If I found this, I would be able...
[ "I had the same question, and I coudn't figure out where the .style numbers were. But I created a solution that worked for me from this answer.\nI built a PieChart and a HorizontalBarChart.\n--- SOLUTION FOR PIE CHARTS ---\nfrom openpyxl.chart import PieChart, Reference\nfrom openpyxl.chart.marker import DataPoint\...
[ 0 ]
[]
[]
[ "openpyxl", "python", "python_3.x" ]
stackoverflow_0048232452_openpyxl_python_python_3.x.txt
Q: How to merge a few DataFrames in one loop in Python Pandas? I have DataFrame and function in Python Pandas like below: data frame: VALUES_RNG |COL_D | PRICE -----------|--------|---------- 500-600 | XXX | 580 200-300 | ABC | 240 200-300 | ABC | 230 500-600 | GG | 555 ... | ... ...
How to merge a few DataFrames in one loop in Python Pandas?
I have DataFrame and function in Python Pandas like below: data frame: VALUES_RNG |COL_D | PRICE -----------|--------|---------- 500-600 | XXX | 580 200-300 | ABC | 240 200-300 | ABC | 230 500-600 | GG | 555 ... | ... | ... VALUES_RNG has the following values: 200-300, 500-600 func...
[ "try to use pivot. here is just an example:\ndf = pd.DataFrame({\n 'VALUES_RNG': ['500-600', '200-300', '200-300', '500-600', ],\n 'COL_D': ['XXX', 'ABC', 'ABC', 'GG', ],\n 'PRICE': [580, 240, 230, 555, ],\n})\n\ndf = df.pivot(values=['PRICE'], columns=['VALUES_RNG'])\nprint(df.describe()) # result:\n\n ...
[ 0 ]
[]
[]
[ "for_loop", "loops", "merge", "pandas", "python" ]
stackoverflow_0074124139_for_loop_loops_merge_pandas_python.txt
Q: SettingWithCopyWarning even when using .copy I'm using pandas 1.5.0, and I'm getting the SettingWithCopyWarning, for the following code: df["data"] = df["data"].apply(clip_from_start, args=(16,)) df = df.dropna() df[aug1_col] = df[column].map(augmentor).copy() df[aug2_col] = df[column].map(augmento...
SettingWithCopyWarning even when using .copy
I'm using pandas 1.5.0, and I'm getting the SettingWithCopyWarning, for the following code: df["data"] = df["data"].apply(clip_from_start, args=(16,)) df = df.dropna() df[aug1_col] = df[column].map(augmentor).copy() df[aug2_col] = df[column].map(augmentor).copy() The other reference on this topic: How ...
[ "Solution was to do:\n df[\"data\"] = df[\"data\"].apply(clip_from_start, args=(16,))\n df = df.dropna()\n df = df.copy()\n df[aug1_col] = df[column].map(augmentor).copy()\n df[aug2_col] = df[column].map(augmentor).copy()\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "python" ]
stackoverflow_0074123979_dataframe_python.txt
Q: Reading a portion of a large xlsx file with python? I have a large .xlsx file with 1 million rows. I don't want to open the whole file in one go. I was wondering if I can read a chunk of the file, process it and then read the next chunk? (I prefer to use pandas for it.) import pandas as pd # File size 50m data = ...
Reading a portion of a large xlsx file with python?
I have a large .xlsx file with 1 million rows. I don't want to open the whole file in one go. I was wondering if I can read a chunk of the file, process it and then read the next chunk? (I prefer to use pandas for it.) import pandas as pd # File size 50m data = pd.read_excel("m.xlsx") # It takes a long time to open a...
[ "Maybe you are looking for:\nimport pandas as pd\n\ndata = pd.read_excel(\"m.xlsx\", nrows=50) # nrows are the number of rows to parse\n\nReference: https://pandas.pydata.org/docs/reference/api/pandas.read_excel.html#:~:text=0%2C%202%5D.-,nrows,-int%2C%20default%20None\n", "Here is an option to read a number of r...
[ 1, 1 ]
[]
[]
[ "pandas", "python", "xlsx" ]
stackoverflow_0074123774_pandas_python_xlsx.txt
Q: How to initiate a session from celery signal? Trying to init a requests.Session() from a function decorated with @worker_init.connect. That means the function is called by a celery signal. Function simply looks like this: class MasterCelery(Celery): def __init__( self, *args, ...
How to initiate a session from celery signal?
Trying to init a requests.Session() from a function decorated with @worker_init.connect. That means the function is called by a celery signal. Function simply looks like this: class MasterCelery(Celery): def __init__( self, *args, **kwargs ) -> None: super().__init_...
[ "\nIf your goal is to initialize a Session once for every celery\nworker process and using this Session inside your task\nfunctions then using Custom Task Classes would be the best\nchoice.\nExample : Using Custom task classes directly\nfrom celery import Task\nclass SomeTaskThatUseSession(Task):\n def __init__(...
[ 0 ]
[]
[]
[ "celery", "python", "python_requests" ]
stackoverflow_0070899540_celery_python_python_requests.txt
Q: Python Telegram Bot Suddenly Giving "Chat Not Found" Error I've been using a simple bot (code below) for many months but it has recently stopped working. The bot is an admin of the group and I have sent a message to it. Does anyone know what the issue is? import telegram bot = telegram.Bot(token='xxxxxxxxxxx') b...
Python Telegram Bot Suddenly Giving "Chat Not Found" Error
I've been using a simple bot (code below) for many months but it has recently stopped working. The bot is an admin of the group and I have sent a message to it. Does anyone know what the issue is? import telegram bot = telegram.Bot(token='xxxxxxxxxxx') bot.send_message("-1111111111", text="hello")
[ "In general, I have a question about this bot and I doubt at all that it will work in this form... However, your error is most likely related to the fact that:\n\nthe chat where the bot was the administrator was deleted\nthe bot has been stripped of admin rights/removed from the chat\n\nI recommend checking what th...
[ 0 ]
[]
[]
[ "python", "python_telegram_bot", "telegram", "telegram_bot" ]
stackoverflow_0074122683_python_python_telegram_bot_telegram_telegram_bot.txt
Q: how can I iterate specific rows of excel worksheet if I have row numbers using openpyxl? I am new to programming, currently learning python and openpyxl for excel file manipulations. I am writing a script to help in updating repairs database which picks specific records in an excel sheet. I have written a script w...
how can I iterate specific rows of excel worksheet if I have row numbers using openpyxl?
I am new to programming, currently learning python and openpyxl for excel file manipulations. I am writing a script to help in updating repairs database which picks specific records in an excel sheet. I have written a script where I can get the row numbers of the excel data I need to update but the challenge now is abo...
[ "Technically the same as accepted answer\nsheet : Sheet = book.active\n\nindices : set[int] = {10, 20, }\nrows : Iterable[int] = (row for i, row in enumerate(sheet.rows, 1) if i in indices)\n\nfor row in rows:\n ... do whatever\n\n", "import openpyxl\n\n\nbook = openpyxl.load_workbook('numbers.xlsx')\n\nsheet ...
[ 1, 0, 0 ]
[]
[]
[ "excel", "openpyxl", "python" ]
stackoverflow_0063421181_excel_openpyxl_python.txt
Q: How to find all repeating parts of one text python I have a text, for example: a = ''' - Hello, this is a noname podcast and joining us today is Joe. - Who's Joe? you would ask... ... - Anyway, thank you for listening to the noname podcast. Special thanks to Joe, who was joining us today. ''' Now I would like to ...
How to find all repeating parts of one text python
I have a text, for example: a = ''' - Hello, this is a noname podcast and joining us today is Joe. - Who's Joe? you would ask... ... - Anyway, thank you for listening to the noname podcast. Special thanks to Joe, who was joining us today. ''' Now I would like to find the repeating parts of this text of a sufficient le...
[ "Here is some proposal. This operates at the word level using a simple split but you can tune this to sentences or any other split depending on your interests. Also importantly, you'd need some preprocessing (I just cleaned for dots but in a large text more should be done).\na = '''\n- Hello, this is a noname podca...
[ 0, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074122522_python_python_3.x.txt
Q: error while defining SparkContext in jupyter notebooke(Python 3 (ipykernel)) sc = SparkContext(conf=conf) error using anaconda`s Jupyter notebook, this is my first time using pyspark. what I am trying to do is defining the spark environment to read a csv file on the local disk. Edit: added the text as user2314737 ...
error while defining SparkContext in jupyter notebooke(Python 3 (ipykernel))
sc = SparkContext(conf=conf) error using anaconda`s Jupyter notebook, this is my first time using pyspark. what I am trying to do is defining the spark environment to read a csv file on the local disk. Edit: added the text as user2314737 asked for text instead of an image and now StackOverflow wants me to add more deta...
[ "One common problem is a wrong Java version.\nCheck that Java 8 (or higher) is installed and that the JAVA_HOME environment variable is set (to the installation directory).\nIf this doesn't help, you might also need to set the variables SPARK_HOME and PYTHONPATH (see https://spark.apache.org/docs/latest/api/python/...
[ 0, 0 ]
[]
[]
[ "anaconda", "jupyter_notebook", "pyspark", "python" ]
stackoverflow_0071807669_anaconda_jupyter_notebook_pyspark_python.txt
Q: Fix keys must be str, int, float, bool or None, not Snowflake error I am trying to write a list of users from a discord server into a json using python, but I keep receiving this error. Ideally I want to turn my dict {Snowflake(USERID#): Member(user=User(id=Snowflake(USERID#), username='USERNAME', discriminator='...
Fix keys must be str, int, float, bool or None, not Snowflake error
I am trying to write a list of users from a discord server into a json using python, but I keep receiving this error. Ideally I want to turn my dict {Snowflake(USERID#): Member(user=User(id=Snowflake(USERID#), username='USERNAME', discriminator='#', bot=None), nick=None), Into a JSON file only containing the bot=none ...
[ "I wrote this sample bot which produced the json dumps you are looking for:\nfrom discord import Intents, Member, Guild\nfrom discord.ext import commands\nfrom os import environ\nimport json\n\n\nclass StackOverFlowAnswer(commands.Bot):\n def convert_member_to_dict(self, member: Member) -> dict:\n return ...
[ 1, 0 ]
[]
[]
[ "discord", "json", "python", "snowflake_cloud_data_platform" ]
stackoverflow_0074032932_discord_json_python_snowflake_cloud_data_platform.txt
Q: Calculate average asset price when using netting instead of hedging I'm trying to come up with a formula to calculate the average entry/position price to further update my stop loss and take profit. For example opened BTC buy position with amount of 1 when price was 20000. Later when price dropped down to 19000 we...
Calculate average asset price when using netting instead of hedging
I'm trying to come up with a formula to calculate the average entry/position price to further update my stop loss and take profit. For example opened BTC buy position with amount of 1 when price was 20000. Later when price dropped down to 19000 we made another buy using the same amount of 1, "avereging" the position to...
[ "Thanks to Yuri's suggestion to look into VWAP, I came up with the following code, which is more advanced and allows you to use different contract/volume sizes and increase/decrease \"distance\" between orders.\nAs an example here I used avarage price of BTC 20000 and increased steps distance using 1.1 multiplier a...
[ 0 ]
[]
[]
[ "math", "pandas", "python", "trading" ]
stackoverflow_0074060642_math_pandas_python_trading.txt
Q: How I can access myblob path in azure function with python? I created "Trigger Azure Functions on blob containers using an event subscription" with visual studio code and I am running it in local, For now I want to read netCDF files. normally I am doing this by : from netCDF4 import Dataset nc_file ='path of ...
How I can access myblob path in azure function with python?
I created "Trigger Azure Functions on blob containers using an event subscription" with visual studio code and I am running it in local, For now I want to read netCDF files. normally I am doing this by : from netCDF4 import Dataset nc_file ='path of .nc file' nc = Dataset(nc_file, mode='r') but now I dont kn...
[ "\nbut now I dont know how to find the path of my file in the container\n\nSince you are using blob trigger, you just need to upload a file to the container which you have mentioned in your Azure function's function.json path. Below is my function.json where the function could able to read the file when uploaded to...
[ 0, 0 ]
[]
[]
[ "azure", "azure_functions", "eventtrigger", "netcdf", "python" ]
stackoverflow_0074107863_azure_azure_functions_eventtrigger_netcdf_python.txt
Q: Aligning rotated xticklabels and ylabels with their respective xticks and yticks Here is the output of the code : array = [[64,7,5], [9,195,1], [6,17,2]] df_cm = pd.DataFrame(array, range(3), range(3)) sn.set(font_scale=1.4) # for l)abel size sn.heatmap(df_cm, annot=True, annot_kws={"size": 16}...
Aligning rotated xticklabels and ylabels with their respective xticks and yticks
Here is the output of the code : array = [[64,7,5], [9,195,1], [6,17,2]] df_cm = pd.DataFrame(array, range(3), range(3)) sn.set(font_scale=1.4) # for l)abel size sn.heatmap(df_cm, annot=True, annot_kws={"size": 16}, cmap='Blues', fmt='g') # font size class_names = ['dog','cat','bear'] plt.gca().xax...
[ "With tick_marks = np.arange(len(class_names)) you're setting new tick marks. Just get the existing ones with ax.get_xticks()/ax.get_yticks():\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sn\n\narray = [[64,7,5],\n [9,195,1],\n [6,17,2]]\ndf_cm = pd.Da...
[ 1 ]
[]
[]
[ "axis_labels", "matplotlib", "python" ]
stackoverflow_0074124527_axis_labels_matplotlib_python.txt
Q: Multi-assignment in Python When initializing multiple variables in Python is seems that every variable is different (i.e. not a reference) : >>>x = y = z = 6 >>>x=5 >>>y=0 >>>print(x,y,z) >>>5 0 6 but when I am using a numpy array every variable is actually a reference: import numpy as np x = y = z = 6*np.ones(1)...
Multi-assignment in Python
When initializing multiple variables in Python is seems that every variable is different (i.e. not a reference) : >>>x = y = z = 6 >>>x=5 >>>y=0 >>>print(x,y,z) >>>5 0 6 but when I am using a numpy array every variable is actually a reference: import numpy as np x = y = z = 6*np.ones(1) x[0] = 5 y[0] = 0 print(x,y,z) ...
[ "This is down to a difference in types. Integers are not passed by reference, so each variable gets its own copy of the number. If you look at a different object like a list though:\nx = y = z = [0,1,2]\nx[0] = 2\nprint(x, y, x)\n[2, 1, 2], [2, 1, 2], [2, 1, 2]\n\nthis is also passed by reference, so they all chang...
[ 1, 1 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074124745_numpy_python.txt
Q: Dagster-image cli recreate the image deployment describe here: https://github.com/dagster-io/dagster/tree/master/python_modules/automation/automation/docker/images How do I install the dagster-image cli? dagster-image build-all --name <YOUR IMAGE> I tried running pip install -e . from setup.py folder https://gith...
Dagster-image cli
recreate the image deployment describe here: https://github.com/dagster-io/dagster/tree/master/python_modules/automation/automation/docker/images How do I install the dagster-image cli? dagster-image build-all --name <YOUR IMAGE> I tried running pip install -e . from setup.py folder https://github.com/dagster-io/dagst...
[ "I am guessing you want to build your own custom Docker image of user code deployment in Dagster. Here is a simple workaround:\nBuild your image on top of the official Dagster user-code-example.\nFROM dagster/user-code-example:latest\n\nRUN pip install \\\n ...your dependencies\n\nCOPY your_repo/ / \n\n" ]
[ 0 ]
[]
[]
[ "dagster", "python", "setup.py", "setuptools" ]
stackoverflow_0072948123_dagster_python_setup.py_setuptools.txt
Q: python winapi check if sheet exists i am using this: from win32com.client import Dispatch excel_file = Dispatch("Excel.Application") excel_file.Workbooks.Open(excel_result_path) excel_file.Visible = 1 mySheet = excel_file.Worksheets.Add() mySheet.Name = "name" which works fine. the only problem is, if the sheet a...
python winapi check if sheet exists
i am using this: from win32com.client import Dispatch excel_file = Dispatch("Excel.Application") excel_file.Workbooks.Open(excel_result_path) excel_file.Visible = 1 mySheet = excel_file.Worksheets.Add() mySheet.Name = "name" which works fine. the only problem is, if the sheet allready exists, i get an error telling me...
[ "'name' in [excel_file.Sheets(i).Name for i in range(1,excel_file.Sheets.Count+1)]\n\n", "Slightly more readable solution:\n'name' in [sheet.Name for sheet in excel_file.Sheets]\n\n" ]
[ 3, 0 ]
[]
[]
[ "excel", "python", "winapi" ]
stackoverflow_0018867224_excel_python_winapi.txt
Q: ERROR: Failed building wheel for pystan in Anaconda distribution. How to fix this error? When trying to install Darts library its dependencies Pystan and Prophet were throwing errors: ERROR: Failed building wheel for pystan Building wheel for prophet (setup.py) error Followed solution from here which redirected ...
ERROR: Failed building wheel for pystan in Anaconda distribution. How to fix this error?
When trying to install Darts library its dependencies Pystan and Prophet were throwing errors: ERROR: Failed building wheel for pystan Building wheel for prophet (setup.py) error Followed solution from here which redirected me to the pystan docs, https://pystan.readthedocs.io/en/latest/windows.html, which does not wo...
[ "The link that I share in the question directed me to an incorrect path for troubleshooting pystan installation for Windows. The correct link is https://pystan2.readthedocs.io/en/latest/windows.html?msclkid=eb5dcb49ac2511ec829bf25d2eab26d6\nWhen following all the steps from the above link I was successfully able to...
[ 1, 0 ]
[]
[]
[ "anaconda3", "pystan", "python", "python_wheel", "u8darts" ]
stackoverflow_0071616253_anaconda3_pystan_python_python_wheel_u8darts.txt
Q: Interpolate on Pandas groups if group ID is in list I'm trying to interpolate based on grouped pandas data using lambda. I know that with the below data: df = pd.DataFrame({'ID':[1, 1, 1, 2, 2, 2, 3, 3, 3], 'Value' : [np.nan, 5, np.nan, 7, np.nan, 9, 1, 3, np.nan]}) ID Value 0 1 NaN 1 ...
Interpolate on Pandas groups if group ID is in list
I'm trying to interpolate based on grouped pandas data using lambda. I know that with the below data: df = pd.DataFrame({'ID':[1, 1, 1, 2, 2, 2, 3, 3, 3], 'Value' : [np.nan, 5, np.nan, 7, np.nan, 9, 1, 3, np.nan]}) ID Value 0 1 NaN 1 1 5.0 2 1 NaN 3 2 7.0 4 2 NaN 5 2 ...
[ "Use a mask to restrict the groupby:\nint_IDs = [1, 3]\nm = df['ID'].isin(int_IDs)\ndf['New_Value'] = (df[m]\n .groupby('ID')['Value']\n .apply(lambda group: group.interpolate(limit_direction='both'))\n .combine_first(df['Value'])\n)\n\noutput:\n ID Value New_Value\n0 1 NaN 5.0\n1 1 5.0 ...
[ 1 ]
[]
[]
[ "group_by", "lambda", "pandas", "python" ]
stackoverflow_0074124849_group_by_lambda_pandas_python.txt
Q: command not found: django-admin I have downloaded anaconda and Django, but VS code shows ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? so, I check out Get out of root conda environment and Pr...
command not found: django-admin
I have downloaded anaconda and Django, but VS code shows ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? so, I check out Get out of root conda environment and Problem with django after installing an...
[ "According to what you describe, I believe that you didn't activate the env or you don't have one in your directory, run this command py -m venv env && .\\env\\Scripts\\activate then python -m pip install Django to create an env and activated and install Django if you have an env in your directory you need to activ...
[ 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0072466651_django_python.txt
Q: Python library newspaper is not returning the published date I am using newspaper python library to extract some data from new stories. The problem is that I am not getting this data for some URLs. These URLs work fine. They all return 200. I am doing this for a very large dataset but this is one of the URLs for w...
Python library newspaper is not returning the published date
I am using newspaper python library to extract some data from new stories. The problem is that I am not getting this data for some URLs. These URLs work fine. They all return 200. I am doing this for a very large dataset but this is one of the URLs for which the date extraction did not work. The code works for some lin...
[ "Please check the link, I checked the link and it's unavailable now.\nIf link is unavailable, the code will not be work.\n", "Try adding some error handling to your code to catch URLs that return a 404, such as this one: https://www.aljazeera.com/program/featured-documentaries/2020/12/29/lords-of-water-episode-o...
[ 1, 0 ]
[]
[]
[ "newspaper3k", "python", "python_newspaper" ]
stackoverflow_0074112676_newspaper3k_python_python_newspaper.txt
Q: SyntaxError: (unicode error) 'unicodeescape' codes can't decode bytes in position 12-13 truncated \UXXXXXXXX escape I tried using pd.read_csv("C:\Users\mfk15\Desktop\DM\tweets.xlsx") but there is still an error. I use windows anaconda Jupyter notebook. this is the error I faces now File "<ipython-input-4-200f7da6a...
SyntaxError: (unicode error) 'unicodeescape' codes can't decode bytes in position 12-13 truncated \UXXXXXXXX escape
I tried using pd.read_csv("C:\Users\mfk15\Desktop\DM\tweets.xlsx") but there is still an error. I use windows anaconda Jupyter notebook. this is the error I faces now File "<ipython-input-4-200f7da6a93c>", line 1 data_imdb = pd.read_csv("‪C:\Users\mfk15\Desktop\DM\tweets.xlsx", delimiter='\t', header=None) ...
[ "you are reading an excel file with a wrong pandas element, replace read_csv, with read_excel and it works!\n", "Just replace all the backslash with forward slash\npd.read_csv(\"‪C:/Users/mfk15/Desktop/DM/tweets.xlsx\", delimiter='\\t', header=None)\n\n" ]
[ 1, 0 ]
[ "Try this :\npd.read_csv(r\"C:\\Users\\mfk15\\Desktop\\DM\\tweets.xlsx\")\n\n" ]
[ -1 ]
[ "anaconda", "jupyter", "python", "syntax_error", "unicode_escapes" ]
stackoverflow_0064960519_anaconda_jupyter_python_syntax_error_unicode_escapes.txt
Q: Create a pandas dataframe from a nested json file I have the following json file: { "data": { "start_date": "2022-10-01", "end_date": "2022-10-04", "cur": "EUR", "prizes": { "2022-10-01": { "coffee": 0.1448939471560284, "usd": 1 ...
Create a pandas dataframe from a nested json file
I have the following json file: { "data": { "start_date": "2022-10-01", "end_date": "2022-10-04", "cur": "EUR", "prizes": { "2022-10-01": { "coffee": 0.1448939471560284, "usd": 1 }, "2022-10-02": { "c...
[ "One option assuming d the input variable:\ndf = (pd.DataFrame\n .from_dict(d['data']['prizes'], orient='index')\n .drop(columns='usd', errors='ignore') # or [['coffee']]\n )\n\noutput:\n coffee\n2022-10-01 0.144894\n2022-10-02 0.144879\n2022-10-03 0.145486\n\n", "Assume your j...
[ 4, 3, 2, 0 ]
[]
[]
[ "dataframe", "nested", "pandas", "python" ]
stackoverflow_0074122970_dataframe_nested_pandas_python.txt
Q: How do i disable a button in tkinter and change text in it python im making a restaurant management system and i want to disable a button and change its text to "Booked!" this is for the table booking system Table1 = Button(f1ab, padx=16, pady=1, bd=4, fg="black",font=("Clarity Gothic SF", 16, "bold"), width=5, ...
How do i disable a button in tkinter and change text in it python
im making a restaurant management system and i want to disable a button and change its text to "Booked!" this is for the table booking system Table1 = Button(f1ab, padx=16, pady=1, bd=4, fg="black",font=("Clarity Gothic SF", 16, "bold"), width=5, text="Table 1", command=button_click).grid(row=0, column=...
[ "Solution to change text and state:\nYou can change the button by using state.\nTable1['state'] = DISABLED or Table1.config(state=DISABLE)\nNote: To disable a button, use DISABLE, to enable it again, use NORMAL.\n\nUse the same method to change the text.\nTable1['text'] = 'something' or Table1.config(text='somethin...
[ 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074124626_python_tkinter.txt
Q: FastAPI is returning AttributeError: 'dict' object has no attribute 'encode' I am having a very simple FastAPI service, when I try to hit the /spell_checking endpoint, I get this error `AttributeError: 'dict' object has no attribute 'encode'. I am hitting the endpoint using postman, with Post request, and this is ...
FastAPI is returning AttributeError: 'dict' object has no attribute 'encode'
I am having a very simple FastAPI service, when I try to hit the /spell_checking endpoint, I get this error `AttributeError: 'dict' object has no attribute 'encode'. I am hitting the endpoint using postman, with Post request, and this is the url: http://127.0.0.1:8080/spell_checking, the payload is JSON with value: {"w...
[ "The problem happens when you try to create the Response object. This object expects a string as input (infact it tries to call .encode() on it).\nThere is no need to explicitly create one, you can just return the data and fastapi will do the rest.\nfrom typing import Dict\n\nimport uvicorn\nfrom fastapi import Fas...
[ 2 ]
[]
[]
[ "fastapi", "python", "python_3.9" ]
stackoverflow_0074124896_fastapi_python_python_3.9.txt
Q: Getting numpy.AxisError: axis 2 is out of bounds for array of dimension 2 ? python I am trying to build a machine learning model : def build_model(model,mlb_estimator,xtrain,ytrain,xtest,ytest): clf = mlb_estimator(model) clf.fit(xtrain,ytrain) clf_predictions = clf.predict(xtest) y_test_arg=np...
Getting numpy.AxisError: axis 2 is out of bounds for array of dimension 2 ? python
I am trying to build a machine learning model : def build_model(model,mlb_estimator,xtrain,ytrain,xtest,ytest): clf = mlb_estimator(model) clf.fit(xtrain,ytrain) clf_predictions = clf.predict(xtest) y_test_arg=np.argmax(ytest,axis=2,) Y_pred = np.argmax(model.predict(Xtest),axis=1) print('...
[ "You are trying to access the third dimension (index 2 when indexing starts in 0) of an array with 2 dimensions. Change axis=2 by axis=1.\n" ]
[ 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074124306_numpy_python.txt
Q: ImportError: cannot import name 'Celery' from 'celery' ImportError: cannot import name 'Celery' from 'celery' The code is running fine in my local machine. when i run this code on azure server then create this issue. I also renamed celery.py file to celeryy.py file and then checked the error is still same. here be...
ImportError: cannot import name 'Celery' from 'celery'
ImportError: cannot import name 'Celery' from 'celery' The code is running fine in my local machine. when i run this code on azure server then create this issue. I also renamed celery.py file to celeryy.py file and then checked the error is still same. here below is my project file structure in below screenshot. __ini...
[ "I had this exact same issue the way you described, and it started happening only recently (CI failed Oct 3, 2022 but worked fine Sep 25, 2022, with no related changes in between).\nWhat ended up being the cause was the fact that in my CI, importlib-metadata started installing version 5.0.0, which gave the error (W...
[ 3, 1 ]
[]
[]
[ "celery", "django", "python", "rabbitmq" ]
stackoverflow_0074025035_celery_django_python_rabbitmq.txt
Q: Subplot Not Aligning I was trying to make a subplot but the first plot is not showing its also not aligning by the side. Image this is my code below: # Plot of Total Number of Male and Female Athletes in each Year plt.figure(figsize=[20, 5]) plt.subplot(1, 2, 1) summer_gender_participants.plot(kind='bar', x='Yea...
Subplot Not Aligning
I was trying to make a subplot but the first plot is not showing its also not aligning by the side. Image this is my code below: # Plot of Total Number of Male and Female Athletes in each Year plt.figure(figsize=[20, 5]) plt.subplot(1, 2, 1) summer_gender_participants.plot(kind='bar', x='Year', y=['Male','Female'], e...
[ "My advice is to change to the object oriented programing style and try to get the data directly in a numpy array or a list, to have more control over your plot.\nAlso you need to note that these two lines of code\nsummer_gender_participants.plot(kind='bar', x='Year', y=['Male','Female'], edgecolor='Black')\n\nand ...
[ 0 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0074122697_matplotlib_python.txt
Q: Getting python NameError: name XY is not defined despite passing mypy typechecking I'm trying to write a generic class that has methods that take an argument of the class itself, as well as storing a pointer to a next instance of itself. I pass mypy (and feel my code should work), but running it with the python in...
Getting python NameError: name XY is not defined despite passing mypy typechecking
I'm trying to write a generic class that has methods that take an argument of the class itself, as well as storing a pointer to a next instance of itself. I pass mypy (and feel my code should work), but running it with the python interpreter gives me NameError: name 'MyTestClass' is not defined Minimum Code example: (...
[ "Add from __future__ import annotations import.\n" ]
[ 1 ]
[]
[]
[ "mypy", "python" ]
stackoverflow_0074124237_mypy_python.txt
Q: Convert string to google search link in python I need to convert any string to a google search link. For example: "google search link" -> https://www.google.com/search?q=google+search+link&oq=google+search+link&aqs=chrome..69i57j0l9.3500j0j4&sourceid=chrome&ie=UTF-8 Is there any python library or function for th...
Convert string to google search link in python
I need to convert any string to a google search link. For example: "google search link" -> https://www.google.com/search?q=google+search+link&oq=google+search+link&aqs=chrome..69i57j0l9.3500j0j4&sourceid=chrome&ie=UTF-8 Is there any python library or function for this conversion.
[ "An easy solution for your sample string:\nmy_str = \"google search link\"\nout_link = \"https://www.google.com/search?q=\" + '+'.join(my_str.split(' '))\n\nYou might be interested in deleting/handling special characters too\n", "import urllib.parse; \nquary = \"how to Convert string to google search link in pyth...
[ 1, 0 ]
[]
[]
[ "google_search", "python" ]
stackoverflow_0068174712_google_search_python.txt
Q: Django form fields not rendering when grouping fields I am using Django 4.0.3 with a bootstrap webinterface. For layout reasons I want my fields in a ModelForm to be grouped and I'm doing it with: class UserForm(ModelForm): template_name = "container/form.html" field_groups = [["email", "company"], ["last...
Django form fields not rendering when grouping fields
I am using Django 4.0.3 with a bootstrap webinterface. For layout reasons I want my fields in a ModelForm to be grouped and I'm doing it with: class UserForm(ModelForm): template_name = "container/form.html" field_groups = [["email", "company"], ["last_name", "first_name"]] grouped_fields = [] class M...
[ "After quiet a time of trying this and that I ended up writing a wrapper for ModelForm, define my field_groups there and rendered it in the template.\nIt is not nice, but it does the trick.\n<form action=\"\" method=\"post\">\n {% for fieldgroup in form.field_groups %}\n <div class=\"row fieldgroup\">\n ...
[ 0 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0072270921_django_django_forms_python.txt
Q: Extracting a mapping from a pandas dataframe I have a dataframe with two columns labelId and type. There are many entries with the same labelId, but given a labelId its type is unique. I want to extract this mapping from labelId to type as a dict. What is the best way to do this? For the dataframe below: Values l...
Extracting a mapping from a pandas dataframe
I have a dataframe with two columns labelId and type. There are many entries with the same labelId, but given a labelId its type is unique. I want to extract this mapping from labelId to type as a dict. What is the best way to do this? For the dataframe below: Values labelId Type 1 First high 5 First high 2...
[ "here is one way to do it,\ndrop the duplicates on labelId and type, then choose same columns\nand extract as dict\ndict(df.drop_duplicates(subset=['labelId','Type'])[['labelId','Type']].values)\n\nOR\nas Abhilash improved on it\ndict(df[['labelId','Type']].drop_duplicates().values)\n\n{'First ': 'high', 'Second ':...
[ 2 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074125126_pandas_python.txt
Q: aws s3 why my image not available publicly after upload? my image is uploading on s3 bucket and I added parameter ExtraArgs={"ACL":"public-read"} but my image not available for public view. here is my code: s3 = boto3.resource( 's3', aws_access_key_id = "" , aws_secret_access_key = "" ...
aws s3 why my image not available publicly after upload?
my image is uploading on s3 bucket and I added parameter ExtraArgs={"ACL":"public-read"} but my image not available for public view. here is my code: s3 = boto3.resource( 's3', aws_access_key_id = "" , aws_secret_access_key = "" ) bucket = s3.Bucket('my_bucket_name') ...
[ "I solved the problems after keep all images inside an single directory before I was keeping theme like /main_folder/sub_folder\nnow all images I keeping theme inside an single directory and my problem solved.\n" ]
[ 0 ]
[]
[]
[ "amazon_s3", "amazon_web_services", "boto3", "fastapi", "python" ]
stackoverflow_0074119864_amazon_s3_amazon_web_services_boto3_fastapi_python.txt
Q: IndexError: string index out of range in LEETCODE problem 5 In line 6(alternative 8). I am getting an error if I use value of range(lens), but if I reduce the value of range(lens-1). I am getting an error and not the correct answer. For example, for the input "III", I should be getting the value 3, but instead I g...
IndexError: string index out of range in LEETCODE problem 5
In line 6(alternative 8). I am getting an error if I use value of range(lens), but if I reduce the value of range(lens-1). I am getting an error and not the correct answer. For example, for the input "III", I should be getting the value 3, but instead I get the value 2. And for the input "MCMXCIV", I am getting the val...
[ "I figured it out in a few moments.\nThat using a check condition would help avoid the index out of range by not accessing s[i+1].\nif(i != lens-1 and s[i+1] == 'variable'\n", "You are trying to access an element that is not in your string when i is the last index. To prevent index error, you need to check i with...
[ 1, 0 ]
[]
[]
[ "python", "roman_numerals" ]
stackoverflow_0074124939_python_roman_numerals.txt
Q: What is faster? Two list comprehensions or one and a list.copy()? Which of the following is faster? a = [['' for _ in range(len(x))] b = [['' for _ in range(len(x))] or a = [['' for _ in range(len(x))] b = a.copy() Thanks in advance! A: You can see for yourself easily with a timing decorator: from functools im...
What is faster? Two list comprehensions or one and a list.copy()?
Which of the following is faster? a = [['' for _ in range(len(x))] b = [['' for _ in range(len(x))] or a = [['' for _ in range(len(x))] b = a.copy() Thanks in advance!
[ "You can see for yourself easily with a timing decorator:\nfrom functools import wraps\nfrom time import time\n\ndef timing(f):\n @wraps(f)\n def wrap(*args, **kw):\n ts = time()\n result = f(*args, **kw)\n te = time()\n print(f'func:{f.__name__} args:[{args}, {kw}] took: {te-ts} s...
[ 1 ]
[]
[]
[ "list_comprehension", "python", "python_3.x", "runtime" ]
stackoverflow_0074124520_list_comprehension_python_python_3.x_runtime.txt
Q: Python, finding all combinations of two arrays without using intertools I have a two dimensional array and a one dimensional array. I need to >find the combinations of the two and add that to another array. So for >instance the two arrays a[[1,2],[3,4]] and b[5,6] I should get array >c[[1,2,5],[1,2,6],[3,4,5],[3,4...
Python, finding all combinations of two arrays without using intertools
I have a two dimensional array and a one dimensional array. I need to >find the combinations of the two and add that to another array. So for >instance the two arrays a[[1,2],[3,4]] and b[5,6] I should get array >c[[1,2,5],[1,2,6],[3,4,5],[3,4,6]]. I have written code for this but >what I end up getting is c[[1,2,5,6]...
[ "You need to use the copy() function :\ne = d.copy()\n\nCheck the documentation: https://docs.python.org/3/library/copy.html\n" ]
[ 1 ]
[]
[]
[ "arrays", "python" ]
stackoverflow_0074125162_arrays_python.txt
Q: Tenserflow issue when tokenizing sentences I followed a tutorial about tokenizing sentences using Tensorflow, here's the code I'm trying: from tensorflow.keras.preprocessing.text import Tokenizer #API for tokenization t = Tokenizer(num_words=4) #meant to catch most imp _ listofsentences=['Apples are fruits', 'An ...
Tenserflow issue when tokenizing sentences
I followed a tutorial about tokenizing sentences using Tensorflow, here's the code I'm trying: from tensorflow.keras.preprocessing.text import Tokenizer #API for tokenization t = Tokenizer(num_words=4) #meant to catch most imp _ listofsentences=['Apples are fruits', 'An orange is a tasty fruit', 'Fruits are tasty!'] t...
[ "To specify an unlimited amount of tokens use:\nt = Tokenizer(num_words=None)\n\nOutput:\n{'are': 1, 'fruits': 2, 'tasty': 3, 'apples': 4, 'an': 5, 'orange': 6, 'is': 7, 'a': 8, 'fruit': 9}\n[[4, 1, 2], [5, 6, 7, 8, 3, 9], [2, 1, 3]]\n\n" ]
[ 2 ]
[]
[]
[ "nlp", "python", "tensorflow", "tokenize" ]
stackoverflow_0074123446_nlp_python_tensorflow_tokenize.txt
Q: Why isn't the JSON file being outputted to the folder being created? I am trying to implement openpose on google colab on a set of videos. My problem is I want to specifically output the JSON files to folders named according to the name of the video file. For example, the JSON files of hello.mp4 should be output i...
Why isn't the JSON file being outputted to the folder being created?
I am trying to implement openpose on google colab on a set of videos. My problem is I want to specifically output the JSON files to folders named according to the name of the video file. For example, the JSON files of hello.mp4 should be output in a folder named hello. I am using --write_json to output the JSON files a...
[ "Just create the folder beforehand. Change the last few lines:\njson_folder_path = '/content/drive/My Drive/Project/optest/output' + str(filename).replace('.mp4', '')\nos.makedirs(json_folder_path, exist_ok=True)\nif not exists(colab_openpose_video_path):\n !cd openpose && ./build/examples/openpose/openpose.bi...
[ 0 ]
[]
[]
[ "file_handling", "google_colaboratory", "json", "python" ]
stackoverflow_0074125182_file_handling_google_colaboratory_json_python.txt
Q: How to use multiple cases in structural pattern matching (switch case) in Python 3.10 Like in this question, I am trying to match an element in a list, and handle the cases accordingly. See the example below. direct_payments = ["creditcard", "debitcard"] on_credits = ["gift card", "rewards program"] def print_pay...
How to use multiple cases in structural pattern matching (switch case) in Python 3.10
Like in this question, I am trying to match an element in a list, and handle the cases accordingly. See the example below. direct_payments = ["creditcard", "debitcard"] on_credits = ["gift card", "rewards program"] def print_payment_type(payment_type): match payment_type: case in direct_payments: ...
[ "\ncase needs to a pattern (the feature is called structural pattern matching after all). So we cannot include a function there (e.g. case XX in direct_credits.) [Thanks to matszwecja for this clarification.]\n\nThe cases are generated by the match statement. So we cannot do this case in direct_payments:.\n\n\nI co...
[ 2, 1, 1, 0 ]
[]
[]
[ "python", "structural_pattern_matching", "switch_statement" ]
stackoverflow_0074123249_python_structural_pattern_matching_switch_statement.txt
Q: How to iterate through a list of objects without repeating the same line of code Would you know how i can iterate through the self.checkxxx values so that I do not have to repeat the same if else clause over and over again. I am not sure how to do it if someone could give me an example that could be very useful Ma...
How to iterate through a list of objects without repeating the same line of code
Would you know how i can iterate through the self.checkxxx values so that I do not have to repeat the same if else clause over and over again. I am not sure how to do it if someone could give me an example that could be very useful Maybe like a for loop but the for loops i have tried have just not worked. I just get th...
[ "Dispense with the entire if-else section and use a helper function when originally assigning attributes:\ndef checkbox_ledVA(self):\n self.LED = 'PASS'\n self.LED_fail = 'FAIL'\n\n pass_fail = lambda state: self.LED if state == 2 else self.LED_fail\n\n self.checkPWR_rot_va = pass_fail(self.ui.PWR_rot_V...
[ 2, 1, 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074125217_python_python_3.x.txt
Q: python3 command in Subprocess.Popen() not responding after converting python file to macOS executable Because my project is too big, this is a small example where you show the output of the command run on subprocess on tkinter. It works fine! But when I convert it to a macOS application it doesn't work and I think...
python3 command in Subprocess.Popen() not responding after converting python file to macOS executable
Because my project is too big, this is a small example where you show the output of the command run on subprocess on tkinter. It works fine! But when I convert it to a macOS application it doesn't work and I think I have found out that error is happening in line where I call subprocess.Popen(). I am using py2app to con...
[ "Try starting the python executable directly, not using shell:\nIn [10]: import sys, subprocess\n ...: \n ...: def run_python(*args, inp: str = '', python: str = sys.executable):\n ...: with subprocess.Popen(\n ...: ((python,) + args), # <- use the same interpreter executable\n ...: ...
[ 1 ]
[]
[]
[ "macos", "py2app", "python", "python_3.x", "subprocess" ]
stackoverflow_0074092894_macos_py2app_python_python_3.x_subprocess.txt
Q: Python and a customer QRcode using Segno I am looking for a library to use to generate a QR code that contains email contact details with a logo in the centre. It seems Segno seems to be quite popular and has the ability to create artistic QR codes, however, I can't seem to find any examples of a simple QR with a ...
Python and a customer QRcode using Segno
I am looking for a library to use to generate a QR code that contains email contact details with a logo in the centre. It seems Segno seems to be quite popular and has the ability to create artistic QR codes, however, I can't seem to find any examples of a simple QR with a logo in the centre. I've generated a few POC Q...
[ "I don't know how to do this with segno to be honest, but you can easily embbed a logo inside a QRcode using the pyqrcode library like this stack overflow post or using the qrcode library like this geeksforgeeks tutorial.\n" ]
[ 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074125209_python_python_3.x.txt
Q: Time until next occurence of value in pandas dataframe I am trying to find the time (in days) until next occurrence of each specific value. For example, say I have the data below: column1 created_at 0 A 2018-09-03 1 B 2018-09-07 2 B 2018-09-08 3 A 2018-09-09 4 B ...
Time until next occurence of value in pandas dataframe
I am trying to find the time (in days) until next occurrence of each specific value. For example, say I have the data below: column1 created_at 0 A 2018-09-03 1 B 2018-09-07 2 B 2018-09-08 3 A 2018-09-09 4 B 2018-09-12 The goal is to get time difference for each ...
[ "Assuming this is the dataframe df\ndf['created_at'] = pd.to_datetime(df['created_at']) \ndf['time_diff'] = df.groupby('column1')['created_at'].diff().dt.days\n\nFirst row converts is date time, you can skip this if you want.\nSecond row gives you what you want.\nTick this answer if this solves your problem.\n" ]
[ 0 ]
[]
[]
[ "dataframe", "datetime", "difference", "pandas", "python" ]
stackoverflow_0074125423_dataframe_datetime_difference_pandas_python.txt
Q: Remove the group of rows based on the condition of rows I have a dataframe which has two columns, 'Group' and 'Sample Number' The column 'Group' has sample number '11' which is UNIQUE. and each group will have only one '11' Sample Number, followed by the sample numbers in range of 21 to 29 ( for example, 21, 22 23...
Remove the group of rows based on the condition of rows
I have a dataframe which has two columns, 'Group' and 'Sample Number' The column 'Group' has sample number '11' which is UNIQUE. and each group will have only one '11' Sample Number, followed by the sample numbers in range of 21 to 29 ( for example, 21, 22 23, 24, 25, 26, 27 , 28 , 29) and followed by the sample number...
[ "Try this:\ngroups = set(df['Group'][df['Sample_Number'] == 11]) & set(df['Group'][df['Sample_Number'].isin(range(21,30))]) & set(df['Group'][df['Sample_Number'].isin(range(31,40))])\ndf = df[df['Group'].isin(groups)]\n\n\n Group Sample_Number\n0 Z007 11\n1 Z007 21\n2 Z007 ...
[ 1 ]
[]
[]
[ "dataframe", "group_by", "list", "pandas", "python" ]
stackoverflow_0074124691_dataframe_group_by_list_pandas_python.txt
Q: Add multiple columns for days in month using a start date and end date in Pandas I seem to be coming across an issue in trying to add columns to my dataframe, specific to each month for a given start date and end date. Input: In [1]: df = pd.DataFrame([[01/04/2022, 03/05/2022], [07/04/2022,01/05/2022]], columns=['...
Add multiple columns for days in month using a start date and end date in Pandas
I seem to be coming across an issue in trying to add columns to my dataframe, specific to each month for a given start date and end date. Input: In [1]: df = pd.DataFrame([[01/04/2022, 03/05/2022], [07/04/2022,01/05/2022]], columns=['Contract From', ' Contract To']) I apply the following to the specific columns I nee...
[ "Seems to work\n start_date = ['01/04/2022', '07/04/2022']\n end_date = ['03/05/2022', '01/05/2022']\n df = pd.DataFrame(list(zip(start_date, end_date)), columns=['start_date', 'end_date'])\n \n df['start_date'] = pd.to_datetime(df['start_date'],dayfirst=True)\n df['end_date'] = pd.to_datetime(df['e...
[ 0 ]
[]
[]
[ "date", "excel", "pandas", "python" ]
stackoverflow_0074124932_date_excel_pandas_python.txt
Q: How can I use pandas apply() to call a web service efficiently I need to populate a column in a dataframe based on the result of a web service which uses data from another column. The Web Service I am using only allows for 3 concurrent requests at the time. I was wondering if I can control that when using the pa...
How can I use pandas apply() to call a web service efficiently
I need to populate a column in a dataframe based on the result of a web service which uses data from another column. The Web Service I am using only allows for 3 concurrent requests at the time. I was wondering if I can control that when using the pandas dataframe apply() method or if I should look for a different al...
[ "Given that .apply() resolves each row before going into the next, I do not think you will have problems with concurrent requests. However, you might need to consider putting in a small sleep timer (e.g. time.sleep()) within your apply function if the web services has a limit on request frequency.\n" ]
[ 1 ]
[]
[]
[ "apply", "pandas", "python", "web_services" ]
stackoverflow_0074125170_apply_pandas_python_web_services.txt
Q: group cumsum on pandas, reset cumsum to 0 when cumsum is negative how to get "expected_output" column with cumsum? groupa = ['A', 'A', 'A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C', 'C'] valuesa = [-5, 4, 3, -4, -2, -2, 2, -2, 5, -2, 3, 6, 7, -11] expected_output = [0, 4, 7, 3, 1, 0, 2, 0, 5, 3, 3, 9, 16, ...
group cumsum on pandas, reset cumsum to 0 when cumsum is negative
how to get "expected_output" column with cumsum? groupa = ['A', 'A', 'A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C', 'C'] valuesa = [-5, 4, 3, -4, -2, -2, 2, -2, 5, -2, 3, 6, 7, -11] expected_output = [0, 4, 7, 3, 1, 0, 2, 0, 5, 3, 3, 9, 16, 5] dfa = pd.DataFrame(list(zip(groupa, valuesa)), columns=['group', 'va...
[ "An other solution is to use cummin :\ngroupa = ['A', 'A', 'A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C', 'C']\nvaluesa = [-5, 4, 3, -4, -2, -2, 2, -2, 5, -2, 3, 6, 7, -11]\nexpected_output = [0, 4, 7, 3, 1, 0, 2, 0, 5, 3, 3, 9, 16, 5]\ndfa = pd.DataFrame(list(zip(groupa, valuesa)), columns=['group', 'val']...
[ 1, 1 ]
[]
[]
[ "cumsum", "dataframe", "pandas", "python" ]
stackoverflow_0074124439_cumsum_dataframe_pandas_python.txt
Q: send variables or messages to page while script is doing tasks (django 4) I'm doing some python script with django, and I when the user submit a file, I process the file and do tons of tasks, it can last a few minutes. While the user is waiting, I got a loading screen in js, and I print in console what's happening...
send variables or messages to page while script is doing tasks (django 4)
I'm doing some python script with django, and I when the user submit a file, I process the file and do tons of tasks, it can last a few minutes. While the user is waiting, I got a loading screen in js, and I print in console what's happening. But I would like to print it in the page, on the loading screen, is there a s...
[ "You are trying to get information about the status of your running tasks.\nI would do a database table containing a token, a task name and a progression column.\nThis table should be fed with informations from your main function.\nYou can provide a token to your user when he uploads a file, then periodically call ...
[ 0 ]
[]
[]
[ "django", "django_models", "django_views", "javascript", "python" ]
stackoverflow_0074125163_django_django_models_django_views_javascript_python.txt
Q: sorting dictionary values asc in python I have a dictionary in python which is look like this : {'Term1': [6, 'd3', 'd5', 'd43', 'd4', 'd6', 'd7'], 'Term2': [6, 'd1', 'd15', 'd46', 'd2', 'd3', 'd4'], 'Term3': [6, 'd3', 'd5', 'd43', 'd5', 'd6', 'd77'], 'Term4': [6, 'd1', 'd15', 'd46', 'd16', 'd17', 'd77'], 'Term5':...
sorting dictionary values asc in python
I have a dictionary in python which is look like this : {'Term1': [6, 'd3', 'd5', 'd43', 'd4', 'd6', 'd7'], 'Term2': [6, 'd1', 'd15', 'd46', 'd2', 'd3', 'd4'], 'Term3': [6, 'd3', 'd5', 'd43', 'd5', 'd6', 'd77'], 'Term4': [6, 'd1', 'd15', 'd46', 'd16', 'd17', 'd77'], 'Term5': [6, 'd3', 'd5', 'd43', 'd4', 'd10', 'd22'], ...
[ "One way to do this is to split the values into the int and string, sort the strings and concatenate with the int. If you use key function for sort, you can get an actual number sorting instead of standard dictionary sorting for strings:\nd = {'Term1': [6, 'd3', 'd5', 'd43', 'd4', 'd6', 'd7']}\n\nd = {k: [v[0]] + s...
[ 1, 1 ]
[]
[]
[ "dictionary", "python", "sorting" ]
stackoverflow_0074125385_dictionary_python_sorting.txt
Q: local directory while using PyInstaller I'm using PyInstaller to convert .py to .exe. In the python code, the following command finds the local path of the .py file path=os.path.dirname(os.path.abspath(__file__)) While running the .exe, the path is diverted to: ...\AppData\Local\Temp\_MEI174042 What is the proper...
local directory while using PyInstaller
I'm using PyInstaller to convert .py to .exe. In the python code, the following command finds the local path of the .py file path=os.path.dirname(os.path.abspath(__file__)) While running the .exe, the path is diverted to: ...\AppData\Local\Temp\_MEI174042 What is the proper way to find the local path of the .exe file?...
[ "You should use this to determine if the application is an exe or not\nif getattr(sys, 'frozen', False):\n path = os.path.dirname(sys.executable)\nelif __file__:\n path = os.path.dirname(__file__)\n\n", "When deploying an application, relying on the script location is not recommended. As you can notice, pyi...
[ 1, 0 ]
[]
[]
[ "pyinstaller", "python" ]
stackoverflow_0074125426_pyinstaller_python.txt
Q: How can I print all links within a found elements? I'm new to BeautifulSoup, I found all the cards, about 12. But when I'm trying to loop through each card and print link href. I kept getting this error AttributeError: ResultSet object has no attribute 'find'. You're probably treating a list of elements like a si...
How can I print all links within a found elements?
I'm new to BeautifulSoup, I found all the cards, about 12. But when I'm trying to loop through each card and print link href. I kept getting this error AttributeError: ResultSet object has no attribute 'find'. You're probably treating a list of elements like a single element. Did you call find_all() when you meant to ...
[ "cards = soup.find_all('div', attrs={'class': 'up-card-section'})\n\nWill return a collection of all the div's found, you'll need to loop over them before finding the chil a's.\nThat said, you should probably use findChildren for finding the a elements.\n\nExample Demo with an minimal piece of HTML\nfrom bs4 import...
[ 1 ]
[]
[]
[ "beautifulsoup", "python", "python_3.x" ]
stackoverflow_0074125683_beautifulsoup_python_python_3.x.txt
Q: object of type 'ESC50Data' has no len() in my audio classification script so I'm running into the error that my class ESC50Data does not have any length. from torch.utils.data import Dataset, DataLoader class ESC50Data(Dataset): def __init__(self, base, df, in_col, out_col): self.df = df sel...
object of type 'ESC50Data' has no len() in my audio classification script
so I'm running into the error that my class ESC50Data does not have any length. from torch.utils.data import Dataset, DataLoader class ESC50Data(Dataset): def __init__(self, base, df, in_col, out_col): self.df = df self.data = [] self.labels = [] self.c2i={} self.i2c={} ...
[ "Check the indentation of __len__(self) and __getitem__(self, idx) methods in your class ESC50Data code. Right now, it seems like these methods are defined inside the __init__ method, and not under the class itself.\nSee, e.g., this answer.\n" ]
[ 1 ]
[]
[]
[ "audio", "python", "pytorch" ]
stackoverflow_0074117946_audio_python_pytorch.txt
Q: Python, Regex: Cannot get coefficients from the equation(s) I am trying to get coefficients from this equation using regex and later multiple equations: 2a+3b=c However I get this annoying error. I checked my code and everything looks fine for me. This is the error: AttributeError: 'int' object has no attribute 'g...
Python, Regex: Cannot get coefficients from the equation(s)
I am trying to get coefficients from this equation using regex and later multiple equations: 2a+3b=c However I get this annoying error. I checked my code and everything looks fine for me. This is the error: AttributeError: 'int' object has no attribute 'group' Here is my code: import re all_coefficients = [] def equ...
[ "It’s causing the error because re.match did not find any coefficient in the term c so if it didn’t find any coefficient (read carefully) you assigned the coefficient value as 1 BUT you cannot use group now because coefficient is an integer now!! So you use group function before you convert it to an integer, and it...
[ 1 ]
[]
[]
[ "python", "python_3.x", "regex" ]
stackoverflow_0074125767_python_python_3.x_regex.txt
Q: Django Extend Default User Model I am searching for a way to easily add more character fields to the default user model from Django. This question has been asked, but I couldn't find an up to date answer. I let Django handle all the authenticating and logging in, so I don't want to create a custom user model, any ...
Django Extend Default User Model
I am searching for a way to easily add more character fields to the default user model from Django. This question has been asked, but I couldn't find an up to date answer. I let Django handle all the authenticating and logging in, so I don't want to create a custom user model, any ideas?
[ "You can just inherit from AbstractUser.\nclass User(AbstractUser):\n custom_fields....\n\n\nYou can then set this as your AUTH_USER_MODEL in your settings.py:\nAUTH_USER_MODEL = \"<my-app>.User\"\n\nDjango should still be able to handle all the authentication, etc.\n", "from django.contrib.auth.models import ...
[ 1, 1 ]
[]
[]
[ "database", "django", "model", "python" ]
stackoverflow_0074125667_database_django_model_python.txt
Q: How to rename default django model field after creation in admin panel I am making a simple application in Django, where I want my admins to be able to go into the admin panel and create a Level object class Level(models.Model): content = models.CharField(max_length = 200) ^^ This is my simple layout for ...
How to rename default django model field after creation in admin panel
I am making a simple application in Django, where I want my admins to be able to go into the admin panel and create a Level object class Level(models.Model): content = models.CharField(max_length = 200) ^^ This is my simple layout for the model, only admins can create this. However, when my admins create the L...
[ "You just need to change the string to be the content:\nclass Level(models.Model):\n content = models.CharField(max_length = 200)\n\n def __str__(self):\n return f\"{self.content}\"\n\n", "class Level(models.Model):\n content = models.CharField(max_length = 200)\n\n def __str__(self):\n...
[ 1, 0 ]
[]
[]
[ "admin", "django", "model", "python" ]
stackoverflow_0074125769_admin_django_model_python.txt
Q: Pandas: distribute a number throughout a column until is over I have this kind of data frame df = pd.DataFrame(data={'Name': ['a1', 'a2','a1'], 'Quantity': [8,4,5], Order: [1,1,2], 'Result': [0,0,0]}) Name Quantity Order Result a1 8 1 0 a2 4 1 0 a1 5 2 0 I would like to distribute a number, N=10, over the row...
Pandas: distribute a number throughout a column until is over
I have this kind of data frame df = pd.DataFrame(data={'Name': ['a1', 'a2','a1'], 'Quantity': [8,4,5], Order: [1,1,2], 'Result': [0,0,0]}) Name Quantity Order Result a1 8 1 0 a2 4 1 0 a1 5 2 0 I would like to distribute a number, N=10, over the rows of the data frame according: Quantity -> each name sh...
[ "You can use:\nN = 10\n\n# ensure rows are sorted by priority and cumsum\ns = df.sort_values(by=['Order', 'Name'])['Quantity'].cumsum()\n# set the maximum sum to 10 and reverse the cumsum with diff\ndf['Result'] = s.clip(upper=N).diff().fillna(s.clip(upper=N), downcast='infer')\n\noutput:\n Name Quantity Order ...
[ 1, 1 ]
[]
[]
[ "for_loop", "pandas", "python" ]
stackoverflow_0074124900_for_loop_pandas_python.txt
Q: write a function that only extract certain keys from a dictionary I want to write a function where any keys can be extracted to give the values. Here is the dictionary and the code that I wrote and the input: DNAcodon2aa = {"aaa":"K", "aac":"N", "aag":"K", "aat":"N", "aca":"T", "acc":"T", "acg":"T", "...
write a function that only extract certain keys from a dictionary
I want to write a function where any keys can be extracted to give the values. Here is the dictionary and the code that I wrote and the input: DNAcodon2aa = {"aaa":"K", "aac":"N", "aag":"K", "aat":"N", "aca":"T", "acc":"T", "acg":"T", "act":"T", "aga":"R", "agc":"S", "agg":"R", "agt":"S", ...
[ "@quamrana's comment correctly diagnoses the problem with your code. You overwrite codon_list with the keys from DNAcodon2aa. Once that line is deleted, your code should work.\nThat said, here's a better implementation of your function:\ndef translate(codon_list):\n return ''.join(DNAcodon2aa[codon] for codon in...
[ 4, 1, 1 ]
[]
[]
[ "dictionary", "function", "python" ]
stackoverflow_0074125795_dictionary_function_python.txt
Q: Printing only 1's and 0's Link to the flowchart i made I want to make a program that accepts a string of 1’s and 0’s. It should output ‘ is valid’ if and only if the string starts with 1, the second with 0, and the last be 1. The string can be of any length. If the string does not follow the conditions and is comp...
Printing only 1's and 0's
Link to the flowchart i made I want to make a program that accepts a string of 1’s and 0’s. It should output ‘ is valid’ if and only if the string starts with 1, the second with 0, and the last be 1. The string can be of any length. If the string does not follow the conditions and is composed of letters or special char...
[ "This is checking that first characters are 1 and 0, checking last one is 1 and the string does contain only 0 or 1 characters.\nx = str(input('Enter numbers: '))\n\nif x.startswith('10') and x.endswith('1') and all(letter in '01' for letter in x):\n print('string is valid')\n\nelse:\n print('Invalid Input')\n\...
[ 2, 1, 0 ]
[]
[]
[ "if_statement", "python" ]
stackoverflow_0074125828_if_statement_python.txt
Q: 3D *.stl surface model convert to 2D image stack? OK to start with let me be clear, I am not interested in converting an image stack into a 3D model. I have an *.stl file (a triangulated surface mesh) & I would like to slice it back into an image stack. I've had a look at Slic3r & Meshmixer but they both only give...
3D *.stl surface model convert to 2D image stack?
OK to start with let me be clear, I am not interested in converting an image stack into a 3D model. I have an *.stl file (a triangulated surface mesh) & I would like to slice it back into an image stack. I've had a look at Slic3r & Meshmixer but they both only give out Gcode. So given I have the vertices of all the poi...
[ "For example if you got your mesh to render with OpenGL (by any means inside your app) then to get your slice you would simply:\n\nset your camera so screen projection plane is parallel to the slice...\nclear screen buffer as usual with glClearColor set to background color\nClear your depth buffer with glClearDept...
[ 1, 1, 0 ]
[]
[]
[ "3d", "c++", "graphics", "imaging", "python" ]
stackoverflow_0037863327_3d_c++_graphics_imaging_python.txt
Q: how to decode file when writing in yaml format I am trying to write a dictionary file that contains Tibetan language word into yaml format. Problem is i couldn't encode/decode the file when writing the yaml file. Here is code : with open('tibetan_dict.yml', 'w', encoding='utf-8') as outfile: yaml.dump(...
how to decode file when writing in yaml format
I am trying to write a dictionary file that contains Tibetan language word into yaml format. Problem is i couldn't encode/decode the file when writing the yaml file. Here is code : with open('tibetan_dict.yml', 'w', encoding='utf-8') as outfile: yaml.dump(tibetan_dict, outfile, default_flow_style=False) ti...
[ "If you want non-ascii characters in the yaml output, you need to pass allow_unicode=True when dumping.\n>>> yaml.dump(tibetan_dict)\n'\"\\\\u0F40\\\\u0F0B\\\\u0F45\": \"\\\\u0F21.\\\\u0F0B\\\\u0F53\\\\u0F7C\\\\u0F62\\\\u0F0B\\\\u0F62\\\\u0FAB\\\\u0F66\\\\u0F0B\\\\\\n \\\\u0F40\\\\u0FB1\\\\u0F72\\\\u0F0B\\\\u0F66\...
[ 0 ]
[]
[]
[ "encoding", "python", "python_3.x", "utf_8", "yaml" ]
stackoverflow_0074125803_encoding_python_python_3.x_utf_8_yaml.txt
Q: if statement for popping elements in pandas dict My pandas dict looks like this: import pandas as pd data = {'address': ["William J. Clare\\n290 Valley Dr.\\nCasper, WY 82604\\nUSA", "1180 Shelard Tower\\nMinneapolis, MN 55426\\nUSA", "William N. Barnard\\n145 S. Durbin\\nC...
if statement for popping elements in pandas dict
My pandas dict looks like this: import pandas as pd data = {'address': ["William J. Clare\\n290 Valley Dr.\\nCasper, WY 82604\\nUSA", "1180 Shelard Tower\\nMinneapolis, MN 55426\\nUSA", "William N. Barnard\\n145 S. Durbin\\nCasper, WY 82601\\nUSA", "215 S 11t...
[ "The add variable is actually a str.\nIf you want to remove an element from the splitted list you can do something like that:\nimport json\n\nimport pandas as pd\n\ndata = {'address': [\"William J. Clare\\\\n290 Valley Dr.\\\\nCasper, WY 82604\\\\nUSA\",\n \"1180 Shelard Tower\\\\nMinneapolis, MN...
[ 0, 0 ]
[]
[]
[ "dictionary", "pandas", "python" ]
stackoverflow_0074125774_dictionary_pandas_python.txt
Q: Why does extracting words using NLTK truncate the last 'S' on some ocassions? I have written a python script to extract words from a pandas dataframe column. I observed that while extracting words, if the last letter of the word is 's', the last 's' gets truncated. Below is the actual code and output My code impor...
Why does extracting words using NLTK truncate the last 'S' on some ocassions?
I have written a python script to extract words from a pandas dataframe column. I observed that while extracting words, if the last letter of the word is 's', the last 's' gets truncated. Below is the actual code and output My code import re import unicodedata import nltk # Create dataframe data = ['gautam das', ...
[ "This is because you are using the lemmatize() method from the WordNetLemmatizer() class. Although the class is called a lemmatizer, it uses a special _morphy method that actually stems the words instead of lemmatizing them. While I don't know what language model you're using, my guess is that the WordNetLemmatizer...
[ 3 ]
[]
[]
[ "nlp", "nltk", "python", "python_3.x", "text" ]
stackoverflow_0074125171_nlp_nltk_python_python_3.x_text.txt
Q: Roblox API - Token Validation Failed Whenever I try to send a request to the roblox api, I get the error "Token Validation Failed" Code: import requests cookie = "COOKIE HERE" session = requests.session() session.cookies[".ROBLOSECURITY"] = cookie def createBadge(id): data = { "name": "test", ...
Roblox API - Token Validation Failed
Whenever I try to send a request to the roblox api, I get the error "Token Validation Failed" Code: import requests cookie = "COOKIE HERE" session = requests.session() session.cookies[".ROBLOSECURITY"] = cookie def createBadge(id): data = { "name": "test", "description": "test badge", "en...
[ "That error means that you have to include the \"x-csrf-token\" header. To obtain the token you firstly need to make a request fail and it will be in the response headers.\n" ]
[ 1 ]
[]
[]
[ "python", "roblox" ]
stackoverflow_0074009465_python_roblox.txt
Q: How to avoid huggingface t5-based seq to seq suddenly reaching a loss of `nan` and start predicting only ``? I'm trying to train a t5 based LM head model (mrm8488/t5-base-finetuned-wikiSQL) using my custom data to turn text into SQL (based roughly on the SPIDER dataset). The current training loop I have is somethi...
How to avoid huggingface t5-based seq to seq suddenly reaching a loss of `nan` and start predicting only ``?
I'm trying to train a t5 based LM head model (mrm8488/t5-base-finetuned-wikiSQL) using my custom data to turn text into SQL (based roughly on the SPIDER dataset). The current training loop I have is something like this: parameters = self.model.parameters() optimizer = AdamW(parameters, lr=1e-5) # imported from `transfo...
[ "I had the same problem, but instead to use fp16=True, I used fp16_full_eval=True. This work for me, I hope it helps!\n" ]
[ 0 ]
[]
[]
[ "huggingface_tokenizers", "huggingface_transformers", "machine_learning", "nlp", "python" ]
stackoverflow_0070374173_huggingface_tokenizers_huggingface_transformers_machine_learning_nlp_python.txt
Q: Combining Scheduling and Multiprocessing in python script I am trying to run a script in which a specific function, run_script, is run at specific times using Scheduling as well as parallel with the same function with varying arguments using Multiprocessing. I have tried using Threading as well, however I still ru...
Combining Scheduling and Multiprocessing in python script
I am trying to run a script in which a specific function, run_script, is run at specific times using Scheduling as well as parallel with the same function with varying arguments using Multiprocessing. I have tried using Threading as well, however I still run into the same problem. The scheduling part works fine, but th...
[ "You want to schedule a single task to run every 10 seconds and that task runs 4 sub-tasks in parallel using a multiprocessing pool of size 4, which is allocated just once.\nI have changed the demo to use Python's built-in sched module:\nimport sched\nimport time\nfrom multiprocessing import Pool\n\n\ndef run_scrip...
[ 0 ]
[]
[]
[ "multiprocessing", "multithreading", "python", "scheduling" ]
stackoverflow_0074121247_multiprocessing_multithreading_python_scheduling.txt
Q: Difference between all elements in a row across two 2d NumPy arrays? I'm relatively new to programming/Python/NumPy, so I apologize if my ignorance is showing... Say I have two 2d NumPy arrays: import numpy as np a = np.array([[1, 5, 20], [2, 15, float("NaN")], ...
Difference between all elements in a row across two 2d NumPy arrays?
I'm relatively new to programming/Python/NumPy, so I apologize if my ignorance is showing... Say I have two 2d NumPy arrays: import numpy as np a = np.array([[1, 5, 20], [2, 15, float("NaN")], [4, float("NaN"), float("NaN")]]) b = np.array([[4, float("NaN"...
[ "It is still using a loop, but in a list comprehension fashion:\nnp.array([(b_row - a_row[:,None]).flatten() for a_row, b_row in zip(a, b)])\n\n", "You can transpose the array to avoid the shape differences when substructing, and then ravel and reshape the results\narr = b.T[:, None] - a.T\nnp.ravel([arr[0], arr[...
[ 1, 1 ]
[]
[]
[ "arrays", "numpy", "python", "vectorization" ]
stackoverflow_0074125593_arrays_numpy_python_vectorization.txt
Q: Private jupyter notebook Is there a way to make unavailable for others jupyter notebook contents? I want to share notebook with others so it would perform the necessary actions but users couldn’t see the inside code. A: It is not possible the way you said but you can save the output of notebook block. All you ne...
Private jupyter notebook
Is there a way to make unavailable for others jupyter notebook contents? I want to share notebook with others so it would perform the necessary actions but users couldn’t see the inside code.
[ "It is not possible the way you said but you can save the output of notebook block. All you need to do is execute the block and remove the code after getting the output. In this way you can share the outputs without sharing the code.\n", "If you save the code that's performing actions into an appropriately format...
[ 0, 0 ]
[]
[]
[ "jupyter_notebook", "private", "python" ]
stackoverflow_0074125951_jupyter_notebook_private_python.txt
Q: Update Links of Powerpoint using win32com (Python) I have a PowerPoint slide which has a linked image (table) and the data for that image is in excel. I am trying to open the PowerPoint but even after PPTApp.DisplayAlerts = False my script gets stuck due to Security pop up which asks me to update the external link...
Update Links of Powerpoint using win32com (Python)
I have a PowerPoint slide which has a linked image (table) and the data for that image is in excel. I am trying to open the PowerPoint but even after PPTApp.DisplayAlerts = False my script gets stuck due to Security pop up which asks me to update the external links. Here is my code: import win32com.client PPTApp = win3...
[ "Just call UpdateLinks() instead of setting the attribute UpdateLinks to True, and remove the line where you are invoking alerts PPTApp.DisplayAlerts = False :\nimport win32com.client\nPPTApp = win32com.client.Dispatch(\"PowerPoint.Application\")\n\nif not PPTApp.Visible:\n PPTApp.Visible = True\n\nPPTPresentatio...
[ 0, 0 ]
[]
[]
[ "powerpoint", "python", "win32com" ]
stackoverflow_0071430344_powerpoint_python_win32com.txt
Q: tkinter inserting space between button and label with grid I want between button and label to be at minimum 6 rows of grid framework based. I put ttk.Label(mainframe, text="enter url ").grid(column=3, row=1, sticky=('N')) row is one, and sticky which is North. If the cell is larger than the widget, the sticky op...
tkinter inserting space between button and label with grid
I want between button and label to be at minimum 6 rows of grid framework based. I put ttk.Label(mainframe, text="enter url ").grid(column=3, row=1, sticky=('N')) row is one, and sticky which is North. If the cell is larger than the widget, the sticky option specifies which side the widget should sticks to and how to...
[ "Answer from User @acw1668 helped to work out it;\nttk.Label(mainframe).grid(column=3, row=3, sticky=('N')) ttk.Label(mainframe).grid(column=3, row=3, sticky=('N'))#? \nBy putting two labels with row 3 and without text I managed to get 6 row space. Thanks for help\n" ]
[ 1 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074125752_python_tkinter.txt
Q: Python “name is not defined”? I have a question for my python programming. I started 3 days ago and seems to have trouble creating this simple code on Replit. Here it is [1]: https://i.stack.imgur.com/i4gld.jpg I have tried different things such as switching the identifier, but I get this error It seems only numb...
Python “name is not defined”?
I have a question for my python programming. I started 3 days ago and seems to have trouble creating this simple code on Replit. Here it is [1]: https://i.stack.imgur.com/i4gld.jpg I have tried different things such as switching the identifier, but I get this error It seems only number works, but what if I wanted to w...
[ "You need to do either e = 'hi' or e = \"hi\". This way python knows it is a string\n", "You need to quote the string type variable to make it work.\ne = \"hi\"\ny = 7\nif y == 7:\n print(e)\n\n", "here in your code (e) variable contain string python accept string with quotes '' or \"\" your are directly pas...
[ 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074125937_python.txt
Q: Possible combinations of the digits 1-9 using only 4 operators inclusive of two addition and two subtractions symbols This problem has been haunting me for the last 24 hours, and I've been messing around with my amateur python coding skills to no avail. The problem in question is this: You are given the numbers 1 ...
Possible combinations of the digits 1-9 using only 4 operators inclusive of two addition and two subtractions symbols
This problem has been haunting me for the last 24 hours, and I've been messing around with my amateur python coding skills to no avail. The problem in question is this: You are given the numbers 1 to 9 (inclusive). Inbetween each number is a space where you are able to insert a mathmatical operator. You are given 2 add...
[ "There's not many combinations to try (3^8=6561), and you can just go through all possibilities of '+', '-' and the empty string between each digit and discard the ones that don't have exactly 2 plusses and minuses. Then you can find out what the result is using eval.\nFor example:\nimport itertools\n\nfor x in ite...
[ 1, 1, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074125686_python.txt
Q: Using Mypy with `.pyi` stub files Lets say I have a simple function inside the file home/func.py, and I make one call to it. def f(x): return x print(f("example")) Now lets say I want to type check this function using a stub, home/stubs/func.pyi which looks like: def f(x: int): ... Now I want to check my cod...
Using Mypy with `.pyi` stub files
Lets say I have a simple function inside the file home/func.py, and I make one call to it. def f(x): return x print(f("example")) Now lets say I want to type check this function using a stub, home/stubs/func.pyi which looks like: def f(x: int): ... Now I want to check my code with mypy to see if I've made any typ...
[ "To this day (Python 3.10 and MyPy 0.982), as you, I haven't been able to separate stubs from code and make it work in my projects.\nFor now I either put the annotations in the code or use the alternatives (such as pytype, pyright, Pyre).\nI hope someone else to correct me, or maybe understand how is it done in oth...
[ 0 ]
[]
[]
[ "mypy", "pyi", "python", "stub", "typing" ]
stackoverflow_0072982795_mypy_pyi_python_stub_typing.txt
Q: Pass a keyword variable to a function as an argument I'm doing a project that is requiring a lot of input validation. I currently have a function defined as follows: def get_valid_float(inputMessage,errorMessage): while True: variableInput = input(inputMessage) try: variableInput = ...
Pass a keyword variable to a function as an argument
I'm doing a project that is requiring a lot of input validation. I currently have a function defined as follows: def get_valid_float(inputMessage,errorMessage): while True: variableInput = input(inputMessage) try: variableInput = float(variableInput) return variableInput ...
[ "Just pass as an argument the actual data type, rather than the name of the data type. E.g:\ndef get_valid_input(dataType, inputMessage, errorMessage):\n while True:\n value = input(inputMessage)\n try:\n value = dataType(value)\n break\n except ValueError:\n p...
[ 1, 0 ]
[]
[]
[ "python", "validation" ]
stackoverflow_0074126003_python_validation.txt
Q: Adding and removing bootstrap cards to DASH with automatic grid layout in Python What I would like to do is when adding a button interactively as in this example (https://github.com/facultyai/dash-bootstrap-components/issues/374#issuecomment-629619851 with this code https://gist.github.com/tcbegley/b7c49d0aec605e3...
Adding and removing bootstrap cards to DASH with automatic grid layout in Python
What I would like to do is when adding a button interactively as in this example (https://github.com/facultyai/dash-bootstrap-components/issues/374#issuecomment-629619851 with this code https://gist.github.com/tcbegley/b7c49d0aec605e383d3b8190448f45f2), to be able to have any kind of grid and not a vertical one where a...
[ "All you need to do is to replace html.Div([], id=\"output\") with dbc.Row([], style={\"width\":\"850px\"},id=\"output\") and everything works seamlessly:\nFull example:\nimport json\nimport dash\nimport dash_bootstrap_components as dbc\nimport dash_html_components as html\nfrom dash.dependencies import ALL, Input,...
[ 1 ]
[]
[]
[ "plotly_dash", "python" ]
stackoverflow_0074124998_plotly_dash_python.txt
Q: Replace column values with last occurance value based on another column I have a pandas dataframe has two columns, code and name, each duplicated code may have different names, How can I replace name for each code with last occurrence for each one code name 1 3 1 6 2 5 3 4 1 7 Required output code name 1 ...
Replace column values with last occurance value based on another column
I have a pandas dataframe has two columns, code and name, each duplicated code may have different names, How can I replace name for each code with last occurrence for each one code name 1 3 1 6 2 5 3 4 1 7 Required output code name 1 7 1 7 2 5 3 4 1 7
[ "You can use pd.groupby() to group by the column code and get the last value from the column name for each value of code. Use transform to get the complete column back and save it under the column name:\ndf['name'] = df.groupby('code').name.transform('last')\nprint(df)\n\nOutput:\n code name\n0 1 7\n1 ...
[ 2 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074126089_dataframe_pandas_python.txt
Q: FInding optimal threshold from the data in binary classification I have a classifier that outputs a proportion X between 0 and 1. I also have an associated ground truth which is the real proportion. I want to predict 1 when the output of the classifier is greater than some threshold and 0 otherwise . From data vis...
FInding optimal threshold from the data in binary classification
I have a classifier that outputs a proportion X between 0 and 1. I also have an associated ground truth which is the real proportion. I want to predict 1 when the output of the classifier is greater than some threshold and 0 otherwise . From data visualization I know that a good threshold is around 0.5. How can I estim...
[ "Precision, recall and f1-score values depend on the probability threshold. Changes in the threshold that we select to use as a cut-off to determine that a sample belongs to the positive class will affect the precision, recall and therefore f1-score. I share my attempt to plot precision, recall and f1-score dependi...
[ 1, 0 ]
[]
[]
[ "machine_learning", "math", "probability", "python" ]
stackoverflow_0064742991_machine_learning_math_probability_python.txt
Q: Censoring a txt file with python Hi I could really use some help on a python project that I'm working on. Basically I have a list of banned words and I must go through a .txt file and search for these specific words and change them from their original form to a ***. text_file = open('filename.txt','r') text_file_r...
Censoring a txt file with python
Hi I could really use some help on a python project that I'm working on. Basically I have a list of banned words and I must go through a .txt file and search for these specific words and change them from their original form to a ***. text_file = open('filename.txt','r') text_file_read = text_file.readlines() banned_wor...
[ "I cannot solve this for you (haven't touched python in a while), but the best debugging tip I can offer is: print everything. Take the first loop, print every iteration, or print what \"words\" is afterwards. It will give you an insight on what's going wrong, and once you know what is working in an unexpected way,...
[ 0, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074125918_python_python_3.x.txt
Q: Smartsheet - Error code 1006 and status code 404 I am trying to get details from a smart sheet and when I try to connect to it I am getting the following error {"response": {"statusCode": 404, "reason": "Not Found", "content": {"errorCode": 1006, "message": "Not Found", "refId": "1lxywzbrqxdq6"}}} Traceback (most ...
Smartsheet - Error code 1006 and status code 404
I am trying to get details from a smart sheet and when I try to connect to it I am getting the following error {"response": {"statusCode": 404, "reason": "Not Found", "content": {"errorCode": 1006, "message": "Not Found", "refId": "1lxywzbrqxdq6"}}} Traceback (most recent call last): File "smartsheet_test.py", line 3...
[ "A 404 (Not Found) error response to a GET Sheet request is typically caused by one of three things:\n\nThe request URL is malformed (i.e., the path specified isn't a valid API endpoint).\nThe sheet ID specified does not exist.\nThe sheet ID specified does exist, but the account (user) that owns the API access toke...
[ 0 ]
[]
[]
[ "python", "smartsheet_api", "smartsheet_api_2.0" ]
stackoverflow_0074125106_python_smartsheet_api_smartsheet_api_2.0.txt
Q: PEP 586: How does Literal actually help variable return types? Context I have just read the PEP 586. In the motivation the authors say the following: numpy.unique will return either a single array or a tuple containing anywhere from two to four arrays depending on three boolean flag values. (...) There is current...
PEP 586: How does Literal actually help variable return types?
Context I have just read the PEP 586. In the motivation the authors say the following: numpy.unique will return either a single array or a tuple containing anywhere from two to four arrays depending on three boolean flag values. (...) There is currently no way of expressing the type signatures of these functions: PEP ...
[ "The problem that Literal solves\nYou took exactly the right passage from PEP 586. To highlight the two crucial words here one more time, this is about\n\nsignatures where the return type varies depending on the value passed in.\n\nThat is one of the applications for the Literal type. And the statement is in fact c...
[ 4 ]
[]
[]
[ "numpy", "pep", "python", "python_typing" ]
stackoverflow_0074124522_numpy_pep_python_python_typing.txt
Q: How can I create multiple frames with a for loop on a Tkinter window? Note I tried to put this in stack overflow with correct formatting, but even when I pressed the code formatting button, it didn't process the response. Can someone help me with that as well?. I am posting here without the formatting as I need he...
How can I create multiple frames with a for loop on a Tkinter window?
Note I tried to put this in stack overflow with correct formatting, but even when I pressed the code formatting button, it didn't process the response. Can someone help me with that as well?. I am posting here without the formatting as I need help quite fast. I know many people on this forum are really good at programm...
[ "Solution\nAs you want the controller to be accessible, you can make the outline_info class inherit the Application class. Then, call super().__init__() in the outline_info class and DO NOT instantiate the Application class but the outline_info class. Here is your code with that:\nCode\nclass Application(tk.Tk):\n ...
[ 0 ]
[]
[]
[ "class", "object", "oop", "python", "tkinter" ]
stackoverflow_0062637033_class_object_oop_python_tkinter.txt
Q: tf.compat.v1 not recognizing the module contrib I run with TensorFlow 2 a python code initially developed with TensorFlow 1 : For a first quick test I transformed the code using tf.compat.v1 W = tf.compat.v1.get_variable( "W", shape=[num_filters_total, num_classes], initializer=tf.compat.v1.contrib.lay...
tf.compat.v1 not recognizing the module contrib
I run with TensorFlow 2 a python code initially developed with TensorFlow 1 : For a first quick test I transformed the code using tf.compat.v1 W = tf.compat.v1.get_variable( "W", shape=[num_filters_total, num_classes], initializer=tf.compat.v1.contrib.layers.xavier_initializer()) Strangely it shows Attribu...
[ "tf.keras.initializers.glorot_normal\n\nIs the equivalent in TF 2 of the defunct Xavier Initializer. Xavier Glorot.\n" ]
[ 1 ]
[]
[]
[ "python", "tensorflow", "tensorflow2.0" ]
stackoverflow_0074121777_python_tensorflow_tensorflow2.0.txt
Q: Pandas data frame with time-series data - grouping without aggregating data I have the following pandas dataframe: import pandas as pd df4 = pd.DataFrame({'timestamp':['2022-10-01 01:00:00', '2022-10-02 01:00:00', '2022-10-03 01:00...
Pandas data frame with time-series data - grouping without aggregating data
I have the following pandas dataframe: import pandas as pd df4 = pd.DataFrame({'timestamp':['2022-10-01 01:00:00', '2022-10-02 01:00:00', '2022-10-03 01:00:00', '2022-10-04 01:00:00', ...
[ "Add this to your code:\ndf4['day'] = df4['timestamp'].dt.strftime('%Y-%m-%d')\ngrouped = df4.groupby('day')[['A', 'B']].agg(list)\nresult = grouped.melt(ignore_index=False)\nprint(result)\n\n" ]
[ 0 ]
[]
[]
[ "datetime", "grouping", "pandas", "python", "time_series" ]
stackoverflow_0074125802_datetime_grouping_pandas_python_time_series.txt
Q: Trying to change a embed footer text with a for loop for footer in embed_dict["footer"]: footer["text"] = "new text" embed_new = discord.Embed.from_dict(embed_dict) await messageraids.edit(embed=raidedit1embed) I get the error: footer["text"] = "new text" TypeError: 'str' object does not support item assign...
Trying to change a embed footer text with a for loop
for footer in embed_dict["footer"]: footer["text"] = "new text" embed_new = discord.Embed.from_dict(embed_dict) await messageraids.edit(embed=raidedit1embed) I get the error: footer["text"] = "new text" TypeError: 'str' object does not support item assignment Anyone know how to fix this
[ "Based on your comment clarifying that embed_dict[\"footer\"] contains {'text': '0/10 Total'}, your problem is you're iterating over that value in the line:\nfor footer in embed_dict[\"footer\"]:\n\nDoing so iterates over the keys of that dictionary, so footer has a value of 'text', and you're doing footer[\"text\"...
[ 1 ]
[]
[]
[ "discord", "discord.py", "footer", "python" ]
stackoverflow_0074125903_discord_discord.py_footer_python.txt
Q: DRF Filtering model by another model id I have this models: class Organization(models.Model): name = models.CharField( "Organization name", max_length=100, unique=True ) description = models.TextField("Organization description") districts = models.ManyToManyField( "District", ...
DRF Filtering model by another model id
I have this models: class Organization(models.Model): name = models.CharField( "Organization name", max_length=100, unique=True ) description = models.TextField("Organization description") districts = models.ManyToManyField( "District", related_name="organizations", ...
[ "If your parameter is optional, I'd just use query parameters so you can have only one url for both cases:\n# views.py\nfrom rest_framework.generics import ListAPIView\n\nclass OrganizationsList(ListAPIView):\n serializer_class = OrganizationSerializer\n \n def get_queryset(self):\n queryset = Organi...
[ 0 ]
[]
[]
[ "django", "django_rest_framework", "django_urls", "filtering", "python" ]
stackoverflow_0074123336_django_django_rest_framework_django_urls_filtering_python.txt
Q: discord.py how could I create a spontaneous response to a random message? I'm trying to create a discord bot that, essentially, is really mean to the user. I'm trying to make it have a random chance of reading your message back to you and then insulting you. How would I go about detecting whenever a new message is...
discord.py how could I create a spontaneous response to a random message?
I'm trying to create a discord bot that, essentially, is really mean to the user. I'm trying to make it have a random chance of reading your message back to you and then insulting you. How would I go about detecting whenever a new message is sent and then rolling a random number, which, if met, will take the contents o...
[ "I think I understand what you're trying to do, maybe? Here's a sample code of how this could work with some notes attached\nimport random\n\n@client.event # client or bot or whatever you're using\nasync def on_message(message): # on message send event\n dice_roll = random.randint(# number one, # number two)\n ...
[ 0 ]
[]
[]
[ "discord", "discord.py", "python" ]
stackoverflow_0074125150_discord_discord.py_python.txt
Q: pyhton list - remove dictionares with certain key When running this python code: shapes = [{"label": "bad_stuff"}, {"label": "cat"}, {"label": "cat"},{"label": "cat"}, {"label": "bad_stuff"}, {"label": "bad_stuff"}] for elem in shapes: if elem['label'] == "bad_stuff": shapes.remove(elem) ... I get thi...
pyhton list - remove dictionares with certain key
When running this python code: shapes = [{"label": "bad_stuff"}, {"label": "cat"}, {"label": "cat"},{"label": "cat"}, {"label": "bad_stuff"}, {"label": "bad_stuff"}] for elem in shapes: if elem['label'] == "bad_stuff": shapes.remove(elem) ... I get this result: [{'label': 'cat'}, {'label': 'cat'}, {'label'...
[ "Because you are modifying list during for loop.\nLet's see what's happening in your code:\nOn 1st interation it removes shapes[0] item.\n2, 3, 4 iterations do not satisfy condition, so passed.\nOn 5th iteration the elem is {\"label\": \"bad_stuff\"}, and your shapes looks like this:\n[{\"label\": \"cat\"}, {\"labe...
[ 2, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074125279_list_python.txt
Q: Get first level li from ul with python I tried multiple ways to get the first level <li> elements but i couldn´t find the correct way. I´ve tried: for item in soup_inicio.find_all('div',{'class':'menu'}): sub_items = item.find_all('li', {'class':'categories'}) for sub_item in sub_items: print(sub_i...
Get first level li from ul with python
I tried multiple ways to get the first level <li> elements but i couldn´t find the correct way. I´ve tried: for item in soup_inicio.find_all('div',{'class':'menu'}): sub_items = item.find_all('li', {'class':'categories'}) for sub_item in sub_items: print(sub_item.text) This is what i´m trying to scrape...
[ "You can use recursive argument set to False:\nsoup_inicio \\\n .find('div',{'class':'menu'}) \\\n .find('ul', {'class': 'navigation'}) \\\n .find_all('li', recursive=False)\n\nthis returns:\n[<li class=\"categories\"> A </li>,\n <li class=\"categories\"> B </li>,\n <li class=\"categories\"> C </li>,\n <li class=\"...
[ 1, 0 ]
[]
[]
[ "beautifulsoup", "python", "web_scraping" ]
stackoverflow_0074124666_beautifulsoup_python_web_scraping.txt
Q: Only format df rows that are not NaN I have the following df: df = pd.DataFrame({'A': [0.0137, 0.1987, 'Decimal('NaN')', 0.7653]}) Output: A 0 0.0137 1 0.1987 2 NaN 3 0.7653 I am trying to format each row from column A, using .iloc (because I have many columns in my actual code) into, e.g. 1.37%. ...
Only format df rows that are not NaN
I have the following df: df = pd.DataFrame({'A': [0.0137, 0.1987, 'Decimal('NaN')', 0.7653]}) Output: A 0 0.0137 1 0.1987 2 NaN 3 0.7653 I am trying to format each row from column A, using .iloc (because I have many columns in my actual code) into, e.g. 1.37%. However, If I perform df.iloc[:, 0] = (df....
[ "use df.loc to choose not NA rows and apply the logic you already have built\n# your DF definition has 'NaN' as string, to converting it to np.nan\ndf.replace('NaN', np.nan, inplace=True)\n\n# Select rows where the value for A is notna() and\n# apply formatting\n\ndf.loc[df['A'].notna(), 'A']=(df.iloc[:, 0] * 100)....
[ 1, 1 ]
[]
[]
[ "dataframe", "format", "pandas", "python" ]
stackoverflow_0074126430_dataframe_format_pandas_python.txt
Q: Find all list elements that are in a string I have a string and a list: my_string = "one two three" my_list = ["one", "two", "three", "four"] I would like to find ALL the substrings of my_string that are in my_list. Here is what I tried: matches = [] if any((match := sub_string) in my_string for sub_string in my...
Find all list elements that are in a string
I have a string and a list: my_string = "one two three" my_list = ["one", "two", "three", "four"] I would like to find ALL the substrings of my_string that are in my_list. Here is what I tried: matches = [] if any((match := sub_string) in my_string for sub_string in my_list): matches.append(match) The result if I...
[ "You can do this with list comprehension,\nIn [1]: [item for item in my_list if item in my_string]\nOut[1]: ['one', 'two', 'three']\n\nEdit:\nIf my_string = \"onez two three\", You can do this,\nIn [2]: [item for item in my_list if item in my_string.split()]\nOut[2]: ['two', 'three']\n\nThis approach will work for ...
[ 2 ]
[]
[]
[ "list", "python", "string" ]
stackoverflow_0074126477_list_python_string.txt
Q: tensorflow 2.1.0: has no attribute 'random_normal' I'm trying to get Uber's Ludwig to run. I get an error about there being no attribute 'random_normal'. I can reproduce the error in Python with these commands. >>> import tensorflow as tf >>> tf.reduce_sum(tf.random_normal([1000,1000])) Traceback (most recent call...
tensorflow 2.1.0: has no attribute 'random_normal'
I'm trying to get Uber's Ludwig to run. I get an error about there being no attribute 'random_normal'. I can reproduce the error in Python with these commands. >>> import tensorflow as tf >>> tf.reduce_sum(tf.random_normal([1000,1000])) Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeE...
[ "It was moved to tf.random.normal (along with all the other tf.random_* functions)\n", "Tensorflow 2.0 comes with new aliases for random_normal. Using tf.random.normal instead of tf.random_normal should execute successfully.\n", "Use this method.\ntf.reduce_sum(tf.compat.v1.random_normal([1000,1000]))\n" ]
[ 44, 6, 0 ]
[]
[]
[ "ludwig", "python", "tensorflow" ]
stackoverflow_0059953127_ludwig_python_tensorflow.txt
Q: Hide certain categorical element from legend in Plotnine In Plotnine, is it possible to hide certain legend elements? mpg_select = mpg[mpg["manufacturer"].isin(pd.Series(["audi", "ford", "honda", "hyundai"]))] I have selected only 4 manufacturers. But when I plot the data, I still see the manufacturers that are n...
Hide certain categorical element from legend in Plotnine
In Plotnine, is it possible to hide certain legend elements? mpg_select = mpg[mpg["manufacturer"].isin(pd.Series(["audi", "ford", "honda", "hyundai"]))] I have selected only 4 manufacturers. But when I plot the data, I still see the manufacturers that are not in the data as elements for my legend. (ggplot(mpg_select, ...
[ "I had a similar issue and I found that remove_unused_categories() did a cleaner job. You don't need to create a new variable, it just removes the missing categories after the filtering:\n from plotnine.data import mpg\n\n desired_manufacturers = ['audi','ford','honda','hyundai']\n mpg_select = mpg.loc[mpg...
[ 1, 0 ]
[]
[]
[ "plotnine", "python" ]
stackoverflow_0069551683_plotnine_python.txt