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: Create a dataframe with and specific name within a function depends on input I need to create a dataframe with and specific name within a function depends on input. Here is my code: ` def filter_season (df_teams ,season): df_teams[season]= df_teams[df_teams['SEASON']== season ] return df_teams[season]...
Create a dataframe with and specific name within a function depends on input
I need to create a dataframe with and specific name within a function depends on input. Here is my code: ` def filter_season (df_teams ,season): df_teams[season]= df_teams[df_teams['SEASON']== season ] return df_teams[season] ` Error got: ValueError: Wrong number of items passed 34, placement implies 1 I ...
[ "IIUC, use varname with globals :\ndef filter_name(df, season):\n sub_df = df.loc[df['SEASON'].eq(season)].copy()\n globals()[nameof(df) + \"_\" + season] = sub_df\n\nAnd here is an example to give you the general logic.\nimport pandas as pd\nfrom varname import nameof\n\ndf = pd.DataFrame({'character': ['cob...
[ 0 ]
[]
[]
[ "dataframe", "function", "python", "python_3.x" ]
stackoverflow_0074672040_dataframe_function_python_python_3.x.txt
Q: Python WebScraping - Sleep oscillate in slow websites I have a webscraping, but the site I'm using in some days is slow and sometimes not. Using the fixed SLEEP, it gives an error in a few days. How to fix this? I use SLEEP in the intervals of the tasks that I have placed, because the site is sometimes slow and do...
Python WebScraping - Sleep oscillate in slow websites
I have a webscraping, but the site I'm using in some days is slow and sometimes not. Using the fixed SLEEP, it gives an error in a few days. How to fix this? I use SLEEP in the intervals of the tasks that I have placed, because the site is sometimes slow and does not return the result giving me an error. from bs4 impor...
[ "Instead of all these hardcoded sleeps you need to use WebDriverWait expected_conditions explicit waits.\nWith it you can set some timeout period so Selenium will poll the page periodically until the expected condition is fulfilled.\nFor example if you need to click a button you will wait for that element clickabil...
[ 1 ]
[]
[]
[ "python", "selenium", "sleep", "web_scraping", "webdriverwait" ]
stackoverflow_0074670711_python_selenium_sleep_web_scraping_webdriverwait.txt
Q: Get current learning rate when using ReduceLROnPlateau I am using ReduceLROnPlateau to modify the learning rate during training of a PyTorch mode. ReduceLROnPlateau does not inherit from LRScheduler and does not implement the get_last_lr method which is PyTorch's recommended way of getting the current learning rat...
Get current learning rate when using ReduceLROnPlateau
I am using ReduceLROnPlateau to modify the learning rate during training of a PyTorch mode. ReduceLROnPlateau does not inherit from LRScheduler and does not implement the get_last_lr method which is PyTorch's recommended way of getting the current learning rate when using a learning rate scheduler. How can I get the le...
[ "You can skip the state_dict of the optimizer and access the learning rate directly:\noptimizer.param_groups[0][\"lr\"]\n\n" ]
[ 0 ]
[]
[]
[ "learning_rate", "python", "pytorch" ]
stackoverflow_0074668086_learning_rate_python_pytorch.txt
Q: Python http server with multiple directories Is it possible to add multiple paths from different driver in os,chdir method? like, 'd:\\folder1' , 'e:\\folder2' I tried to add two paths, but could not join them, got syntax error A: I managed to do it using symbolic links: On windows, you can create symbolic links...
Python http server with multiple directories
Is it possible to add multiple paths from different driver in os,chdir method? like, 'd:\\folder1' , 'e:\\folder2' I tried to add two paths, but could not join them, got syntax error
[ "I managed to do it using symbolic links:\nOn windows, you can create symbolic links to directories as so:\nmklink /D <symbolic link name> <destination directory>\n\nSo in a new folder you can run:\nmklink /D folder1 \"D:\\folder1\"\nmklink /D folder2 \"E:\\folder2\"\n\nOn linux this would be:\nln -s <destination d...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074673599_python.txt
Q: Vector field with numpy and mathplotlib I know how to generate a vector field in all plane, but know I'm trying to create the vector just in some specific line, my code is import numpy as np import matplotlib.pyplot as plt x = np.linspace(-3,3,15) y = np.linspace(-3,3,15) x,y = np.meshgrid(x,y) u = x v = (x-y) ...
Vector field with numpy and mathplotlib
I know how to generate a vector field in all plane, but know I'm trying to create the vector just in some specific line, my code is import numpy as np import matplotlib.pyplot as plt x = np.linspace(-3,3,15) y = np.linspace(-3,3,15) x,y = np.meshgrid(x,y) u = x v = (x-y) plt.quiver(x,y,u,v,color = "purple") plt.sho...
[ "For the case along the line x=y, you can define the coordinates as follows:\nX = np.linspace(0,9,10)\nY = np.linspace(0,13.5,10) \nU = np.ones(10)\nV = np.ones(10) \n \nplt.quiver(X, Y, U, V, color='b', units='xy', scale=1)\nplt.xlim(-2, 15)\nplt.ylim(-2, 15)\nplt.show()\n\nOutput\n\n" ]
[ 0 ]
[]
[]
[ "python", "vector_graphics" ]
stackoverflow_0074672574_python_vector_graphics.txt
Q: Trying to append csv into another csv AS A ROW but I am getting this AttributeError: '_io.TextIOWrapper' object has no attribute 'writerows' i am trying to append the content in one of my CSV as a ROW to another csv but i am getting this attribute error...I am unsure how to fix it. I think the issue is with writer...
Trying to append csv into another csv AS A ROW but I am getting this AttributeError: '_io.TextIOWrapper' object has no attribute 'writerows'
i am trying to append the content in one of my CSV as a ROW to another csv but i am getting this attribute error...I am unsure how to fix it. I think the issue is with writer.writerows(row) but I don't what i should change it to for .writerows(row) to work This is my below code for appending the first csv to the second...
[ "Use write() instead because writerows() is belong to csv.writer, not normal io. However, if you want to append at the end of the file, you need to make sure that the last row contain new line (i.e., \\n) already.\nwith open('test1.csv', 'r', encoding='utf8') as reader:\n with open('test2.csv', 'a', encoding='ut...
[ 1 ]
[]
[]
[ "append", "attributeerror", "csv", "python" ]
stackoverflow_0074673250_append_attributeerror_csv_python.txt
Q: AttributeError: 'str' object has no attribute 'append' I am completely newbee in programming. So I started learning python. In this proram i want to print the name of second lowest scorers and for multiple students print them alphabetically. So I have written this program and I am trying to add those student who h...
AttributeError: 'str' object has no attribute 'append'
I am completely newbee in programming. So I started learning python. In this proram i want to print the name of second lowest scorers and for multiple students print them alphabetically. So I have written this program and I am trying to add those student who has second lowest score. So I add in list named "name". But i...
[ "I've spotted a couple of issues in your code and hope this helps.\n\nYour name variable has been assigned by the input(), which is a\nstring type. So declare a different variable name.\n\nFor getting the student name, it should be\nname.append(student_info[i][0]).\n\n\nif __name__ == '__main__':\n student_info ...
[ 0 ]
[]
[]
[ "append", "list", "python" ]
stackoverflow_0074673687_append_list_python.txt
Q: Apache Airflow not starting in local Getting below error on running the command airflow standalone Error scheduler | [2022-12-04 13:18:14 +0530] [47519] [ERROR] Can't connect to ('::', 8793) webserver | [2022-12-04 13:18:14 +0530] [47517] [ERROR] Can't connect to ('0.0.0.0', 8080) I have tried installing apache ai...
Apache Airflow not starting in local
Getting below error on running the command airflow standalone Error scheduler | [2022-12-04 13:18:14 +0530] [47519] [ERROR] Can't connect to ('::', 8793) webserver | [2022-12-04 13:18:14 +0530] [47517] [ERROR] Can't connect to ('0.0.0.0', 8080) I have tried installing apache airflow multiple times, killing the processe...
[ "This error typically indicates that there is another process or service running on the same ports that the Apache Airflow webserver and scheduler are trying to use. This can cause a conflict and prevent Apache Airflow from starting properly.\nTo resolve this error, you will need to identify and stop the process or...
[ 0 ]
[]
[]
[ "airflow", "python" ]
stackoverflow_0074673719_airflow_python.txt
Q: Scrape all possible results from a search bar with search result limit Trying to scrape all the names from this website with Python: https://profile.tmb.state.tx.us/Search.aspx?9e94dec6-c7e7-4054-b5fb-20a1fcdbab53 The issue is that it limits each search to the top 50 results. Since the last name search allows wild...
Scrape all possible results from a search bar with search result limit
Trying to scrape all the names from this website with Python: https://profile.tmb.state.tx.us/Search.aspx?9e94dec6-c7e7-4054-b5fb-20a1fcdbab53 The issue is that it limits each search to the top 50 results. Since the last name search allows wildcards, I tried using one search result to narrow down subsequent search resu...
[ "Looking at the request and JS, it seems like this limit is server-side. I don't see any way to retrieve more than 50 results.\nBrute-force is the only way I think you could scrape this site, and it's not so trivial. You would need to generate queries more and more specific until the response has less than 50 resul...
[ 1, 0 ]
[]
[]
[ "python", "scrapy", "search", "selenium", "web_scraping" ]
stackoverflow_0074673245_python_scrapy_search_selenium_web_scraping.txt
Q: Create 3D array using Python I would like to create a 3D array in Python (2.7) to use like this: distance[i][j][k] And the sizes of the array should be the size of a variable I have. (nnn) I tried using: distance = [[[]*n]*n] but that didn't seem to work. I can only use the default libraries, and the method of m...
Create 3D array using Python
I would like to create a 3D array in Python (2.7) to use like this: distance[i][j][k] And the sizes of the array should be the size of a variable I have. (nnn) I tried using: distance = [[[]*n]*n] but that didn't seem to work. I can only use the default libraries, and the method of multiplying (i.e.,[[0]*n]*n) wont w...
[ "You should use a list comprehension:\n>>> import pprint\n>>> n = 3\n>>> distance = [[[0 for k in xrange(n)] for j in xrange(n)] for i in xrange(n)]\n>>> pprint.pprint(distance)\n[[[0, 0, 0], [0, 0, 0], [0, 0, 0]],\n [[0, 0, 0], [0, 0, 0], [0, 0, 0]],\n [[0, 0, 0], [0, 0, 0], [0, 0, 0]]]\n>>> distance[0][1]\n[0, 0,...
[ 79, 46, 9, 5, 5, 4, 1, 1, 0, 0 ]
[ "If you insist on everything initializing as empty, you need an extra set of brackets on the inside ([[]] instead of [], since this is \"a list containing 1 empty list to be duplicated\" as opposed to \"a list containing nothing to duplicate\"):\ndistance=[[[[]]*n]*n]*n\n\n" ]
[ -3 ]
[ "arrays", "multidimensional_array", "python", "python_2.7" ]
stackoverflow_0010668341_arrays_multidimensional_array_python_python_2.7.txt
Q: Rps game not working as expected from the shown website that I posted ROCK, PAPER, SCISSORS 0 Wins,0 Losses, 0 Ties Enter your move: (r)ock (p)aper (s)cissors or (q)uit P Enter your move: (r)ock (p)aper (s)cissors or (q)uit S Enter your move: (r)ock (p)aper (s)cissors or (q)uit Q Enter your move: (r)ock (p)aper (s...
Rps game not working as expected from the shown website that I posted
ROCK, PAPER, SCISSORS 0 Wins,0 Losses, 0 Ties Enter your move: (r)ock (p)aper (s)cissors or (q)uit P Enter your move: (r)ock (p)aper (s)cissors or (q)uit S Enter your move: (r)ock (p)aper (s)cissors or (q)uit Q Enter your move: (r)ock (p)aper (s)cissors or (q)uit p Enter your move: (r)ock (p)aper (s)cissors or (q)uit r...
[ "Your solution with a few changes to make it work.\nReindented some parts :\n\nparts of the code were unreachable : the player could never enter his move\nall the game logic was outside of the loop\n\nNote the new position of if playerMove == \"r\" that is now at the same indentation level as if playerMove == \"q\"...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074656256_python.txt
Q: AttributeError: 'Series' object has no attribute 'Mean_μg_L' Why am I getting this error if the column name exists. I have tried everything. I am out of ideas A: Since the AttributeError is raised at the first column with a name containing a mathematical symbol (µ), I would suggest you these two solutions : Use...
AttributeError: 'Series' object has no attribute 'Mean_μg_L'
Why am I getting this error if the column name exists. I have tried everything. I am out of ideas
[ "Since the AttributeError is raised at the first column with a name containing a mathematical symbol (µ), I would suggest you these two solutions :\n\nUse replace right before the loop to get rid of this special character\ndf.columns = df.columns.str.replace(\"_\\wg_\", \"_ug_\", regex=True)\n#change df to Table_1_...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python", "sqlite" ]
stackoverflow_0074673550_dataframe_pandas_python_sqlite.txt
Q: PyCharm doesn't recognize installed module I'm having trouble with using 'requests' module on my Mac. I use python34 and I installed 'requests' module via pip. I can verify this via running installation again and it'll show me that module is already installed. 15:49:29|mymac [~]:pip install requests Requirement al...
PyCharm doesn't recognize installed module
I'm having trouble with using 'requests' module on my Mac. I use python34 and I installed 'requests' module via pip. I can verify this via running installation again and it'll show me that module is already installed. 15:49:29|mymac [~]:pip install requests Requirement already satisfied (use --upgrade to upgrade): requ...
[ "If you are using PyCharms CE (Community Edition), then click on:\nFile->Default Settings->Project Interpretor\n\nSee the + sign at the bottom, click on it. It will open another dialog with a host of modules available. Select your package (e.g. requests) and PyCharm will do the rest.\nMD\n", "In my case, using a ...
[ 43, 42, 12, 11, 8, 7, 6, 3, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ "In your pycharm terminal run pip/pip3 install package_name\n" ]
[ -2 ]
[ "anaconda", "pip", "pycharm", "python", "virtualenv" ]
stackoverflow_0031235376_anaconda_pip_pycharm_python_virtualenv.txt
Q: Tkinter: Calling function when button is pressed but i am getting attribute error 'Application' object has no attribute 'hi' from tkinter import * import sqlite3 conn = sqlite3.connect('database.db') c = conn.cursor() class Application: def __init__(self, master): self.master = master self.le...
Tkinter: Calling function when button is pressed but i am getting attribute error 'Application' object has no attribute 'hi'
from tkinter import * import sqlite3 conn = sqlite3.connect('database.db') c = conn.cursor() class Application: def __init__(self, master): self.master = master self.left = Frame(master, width=800, height=720, bg='lightgreen') self.left.pack(side=LEFT) self.right = Frame(master, ...
[ "To fix the error you are seeing, you need to move the definition of the hi function inside the Application class and not inside __init__, like this:\nclass Application:\n def __init__(self, master):\n # code for the rest of the __init__ method\n\n self.submit=Button(self.left,text=\"Add appointmen...
[ 4 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074673731_python_tkinter.txt
Q: Can you explain how the feature is extracted from the following code of CNN How the Image Features are extracted from the following convolutional neural network code import tensorflow as tf from tensorflow.keras.utils import img_to_array df['PubChem_ID'] = df['PubChem_ID'].apply(str) df_image = [] for i in tqdm(ra...
Can you explain how the feature is extracted from the following code of CNN
How the Image Features are extracted from the following convolutional neural network code import tensorflow as tf from tensorflow.keras.utils import img_to_array df['PubChem_ID'] = df['PubChem_ID'].apply(str) df_image = [] for i in tqdm(range(df.shape[0])): img = image.load_img('/content/drive/MyDrive/3D Conformer/...
[ "In the given code, a convolutional neural network (CNN) is used to extract image features from a dataset of images. The images in the dataset are first converted to a size of 256 x 256 x 3, where the 3 represents the 3 color channels (red, green, and blue) of the image.\nThe image features are extracted using the ...
[ 1 ]
[]
[]
[ "conv_neural_network", "feature_extraction", "image_preprocessing", "python" ]
stackoverflow_0074673792_conv_neural_network_feature_extraction_image_preprocessing_python.txt
Q: Command does not work during discord bot creation I typed !mycommand2 [name] [role] because it didn't come out even when I typed command !캐릭터생성 [name] [role], but it's still the same. Why? And description's role(Is it like an annotation? Explain to the developer what command this is without a role?) and...I also w...
Command does not work during discord bot creation
I typed !mycommand2 [name] [role] because it didn't come out even when I typed command !캐릭터생성 [name] [role], but it's still the same. Why? And description's role(Is it like an annotation? Explain to the developer what command this is without a role?) and...I also wonder about command hidden. char = I want to mack a ins...
[ "Change the function name to the command name\nasync def urcommandname(ctx,arg1,arg2):\n\n" ]
[ 0 ]
[]
[]
[ "discord", "python" ]
stackoverflow_0074673267_discord_python.txt
Q: Python(sympy) : How to graph smoothly in 2nd ODE solution with Sympy? I'm studing about structural dynamic analysis. I solved a problem : 1 degree of freedom The question is m*y'' + cy' + ky = 900 sin(5.3x) m=6938.78, c=5129.907, k=379259, y is the function of x I solved it's response using by Python and Sympy lib...
Python(sympy) : How to graph smoothly in 2nd ODE solution with Sympy?
I'm studing about structural dynamic analysis. I solved a problem : 1 degree of freedom The question is m*y'' + cy' + ky = 900 sin(5.3x) m=6938.78, c=5129.907, k=379259, y is the function of x I solved it's response using by Python and Sympy library. I drew the response by pyplot. But it's shape is not smooth like belo...
[ "To get a smoother line you can turn off the adaptive algorithm and set the number of points per line:\nplot(eq_done.rhs,(x,0,10), adaptive=False, nb_of_points=1000)\n\nAlso, the help() function is your friend, as it allows to quickly access the documentation of a particular function. Execute help(plot) to learn mo...
[ 0 ]
[]
[]
[ "graphing", "python", "sympy" ]
stackoverflow_0074664776_graphing_python_sympy.txt
Q: Visual Studio Code does not detect Virtual Environments Visual Studio Code does not detect virtual environments. I run vscode in the folder where the venv folder is located, when I try to select the kernel in vscode I can see the main environment and one located elsewhere on the disk. Jupyter running in vscode als...
Visual Studio Code does not detect Virtual Environments
Visual Studio Code does not detect virtual environments. I run vscode in the folder where the venv folder is located, when I try to select the kernel in vscode I can see the main environment and one located elsewhere on the disk. Jupyter running in vscode also doesn't see this environment. I have installed ipykernel in...
[ "\nIn VSCode open your command palette — Ctrl+Shift+P by default\n\nLook for Python: Select Interpreter\n\nIn Select Interpreter choose Enter interpreter path... and then Find...\n\nNavigate to your venv folder — eg, ~/pyenvs/myenv/ or \\Users\\Foo\\Bar\\PyEnvs\\MyEnv\\\n\nIn the virtual environment folder choose <...
[ 36, 5, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "jupyter", "python", "virtual_environment", "visual_studio_code" ]
stackoverflow_0066869413_jupyter_python_virtual_environment_visual_studio_code.txt
Q: I get error "unmatched '}'" when I scrape website(korter.az) I want to crawl all advertisements but output is "unmatched '}'". Is there any easy way to do it? I tried Beautifulsoup before but I think It's not correct way to do it or I'm using it wrong way. How can I scrape all '199 yeni tikili binalar' from the we...
I get error "unmatched '}'" when I scrape website(korter.az)
I want to crawl all advertisements but output is "unmatched '}'". Is there any easy way to do it? I tried Beautifulsoup before but I think It's not correct way to do it or I'm using it wrong way. How can I scrape all '199 yeni tikili binalar' from the website. from ast import literal_eval from bs4 import BeautifulSoup ...
[ "The site has an api which can be accessed by request\nUrl of the API is : \"https://korter.az/api/building/listing?mainGeoObjectId=1&page=1&lang=az-AZ&locale=az-AZ\"\nFull Code\nimport requests\nimport math\nimport pandas as pd\n\n\ndef roundup(x):\n return int(math.ceil(x / 20.0)) * 20\n\n\n# Gettig no of resu...
[ 0 ]
[]
[]
[ "python", "python_re", "web_scraping" ]
stackoverflow_0074673490_python_python_re_web_scraping.txt
Q: How to create a random list that satisfy a condition (in one try)? I have written the following code to generate a random list. I want the list to have elements between 0 and 500, but the summation of all elements does not exceed 1300. I dont know how to continue my code to do that. I have written other codes; for...
How to create a random list that satisfy a condition (in one try)?
I have written the following code to generate a random list. I want the list to have elements between 0 and 500, but the summation of all elements does not exceed 1300. I dont know how to continue my code to do that. I have written other codes; for example, to create a list of random vectors and then pick among those t...
[ "Don't append until after you've validated the value.\nUse while len() < maxLen so that you can handle repeat attempts.\nYou don't really need nv since len(bounds) dictates the final value of len(var).\nlen(var) is also the next index of the var list that is unused so you can use that to keep track of where you are...
[ 1, 0 ]
[]
[]
[ "list", "numpy", "python", "random" ]
stackoverflow_0074673377_list_numpy_python_random.txt
Q: Calling mean() Function Without Removing Non-Numeric Columns In Dataframe I have the following dataframe: import pandas as pd fertilityRates = pd.read_csv('fertility_rate.csv') fertilityRatesRowCount = len(fertilityRates.axes[0]) fertilityRates.head(fertilityRatesRowCount) I have found a way to find the mean f...
Calling mean() Function Without Removing Non-Numeric Columns In Dataframe
I have the following dataframe: import pandas as pd fertilityRates = pd.read_csv('fertility_rate.csv') fertilityRatesRowCount = len(fertilityRates.axes[0]) fertilityRates.head(fertilityRatesRowCount) I have found a way to find the mean for each row over columns 1960-1969, but would like to do so without removing t...
[ "You can use pandas.DataFrame.loc to select a range of years (e.g \"1960\":\"1968\" means from 1960 to 1968).\nTry this :\nMean1960To1968 = (\n fertilityRates[[\"Country\"]]\n .assign(Mean= fertilityRates.loc[:, \"1960\":\"1968\"].mean(axis=1))\n )\n\n# Outp...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074673594_dataframe_pandas_python.txt
Q: Cython Buffer types only allowed as function local variables I create a function that take x, y, batch size as input and yield mini batch as output with cython to sped up the process. import numpy as np cimport cython cimport numpy as np ctypedef np.float64_t DTYPE_t @cython.boundscheck(False) def create_mini_ba...
Cython Buffer types only allowed as function local variables
I create a function that take x, y, batch size as input and yield mini batch as output with cython to sped up the process. import numpy as np cimport cython cimport numpy as np ctypedef np.float64_t DTYPE_t @cython.boundscheck(False) def create_mini_batches(np.ndarray[DTYPE_t, ndim=2] X, np.ndarray[DTYPE_t, ndim=2] y...
[ "It's a sightly confusing error message in this case but you're getting it because it's a generator rather than a function. This means that Cython has to create an internal data structure to hold the generator state while it works.\nTyped Numpy array variables (e.g. np.ndarray[DTYPE_t, ndim=2]) were implemented in ...
[ 0 ]
[]
[]
[ "cython", "numpy", "numpy_ndarray", "python" ]
stackoverflow_0074673759_cython_numpy_numpy_ndarray_python.txt
Q: How to create 3D array with filled value along one dimension? It's easy to create a 2D array with filled values: import numpy as np np.full((5, 3), [1]) np.full((5, 3), [1, 2, 3]) Then, I wanna create a 3D array with same value for last two dimensions: import numpy as np np.full((2, 3, 1), [[1], [2]]) ''' # pe...
How to create 3D array with filled value along one dimension?
It's easy to create a 2D array with filled values: import numpy as np np.full((5, 3), [1]) np.full((5, 3), [1, 2, 3]) Then, I wanna create a 3D array with same value for last two dimensions: import numpy as np np.full((2, 3, 1), [[1], [2]]) ''' # perferred result [[[1], [1], [1]] [[2], [2], [2]]] ''' Howe...
[ "In order to boardcast the value to the desired shape, you require the value in shape (2, 1, 1) to match with the input shape (2, 3, 1)\nnp.full((2, 3, 1), [[[1]], [[2]]])\n\noutput:\narray([[[1],\n [1],\n [1]],\n\n [[2],\n [2],\n [2]]])\n\n" ]
[ 0 ]
[]
[]
[ "arrays", "numpy", "numpy_ndarray", "python" ]
stackoverflow_0074673888_arrays_numpy_numpy_ndarray_python.txt
Q: Why nested When().Then() is slower than Left Join in Rust Polars? In Rust Polars(might apply to python pandas as well) assigning values in a new column with a complex logic involving values of other columns can be achieved in two ways. The default way is using a nested WhenThen expression. Another way to achieve s...
Why nested When().Then() is slower than Left Join in Rust Polars?
In Rust Polars(might apply to python pandas as well) assigning values in a new column with a complex logic involving values of other columns can be achieved in two ways. The default way is using a nested WhenThen expression. Another way to achieve same thing is with LeftJoin. Naturally I would expect When Then to be mu...
[ "It's difficult to say for certain without more context, but the difference in performance between using a nested When().Then() expression and a LeftJoin in Rust Polars may be due to the implementation of each method. LeftJoin is likely more optimized for this kind of operation than a nested When().Then() expressio...
[ 0, 0 ]
[]
[]
[ "dataframe", "pandas", "python", "python_polars", "rust" ]
stackoverflow_0074671361_dataframe_pandas_python_python_polars_rust.txt
Q: I cannot get over 50% accuracy on my test data in this simple CNN Tensorflow Keras model for image classification The code is as follows. I have a highly imbalanced dataset for chest x rays with heart enlargement. The images are separated into a training folder split into positive for cardiomegaly and negative for...
I cannot get over 50% accuracy on my test data in this simple CNN Tensorflow Keras model for image classification
The code is as follows. I have a highly imbalanced dataset for chest x rays with heart enlargement. The images are separated into a training folder split into positive for cardiomegaly and negative for cardiomegaly subfolders (467 pos images and ~20,000 neg). (Then I have a testing folder with two subfolders (300 pos, ...
[ "The best thing to do is to eliminate the imbalance to begin with. You have 467 positive images which is more than enough for a model to perform on. So randomly select only 467 negative images from the 20,000 available. This is called under sampling and it works well. Another method is to use both undersampling an...
[ 0 ]
[]
[]
[ "conv_neural_network", "image_classification", "overfitting_underfitting", "python", "tensorflow" ]
stackoverflow_0074672833_conv_neural_network_image_classification_overfitting_underfitting_python_tensorflow.txt
Q: auto built cli tool in to an object in python first sorry for my bad terminology, I am an electrical engineer, so maybe my coding terms are not so accurate or even far from that. we have a CLI in the company, accessed from the Linux terminal, you know usual stuff, `{command.exe} {plugin} {options}, and you get the...
auto built cli tool in to an object in python
first sorry for my bad terminology, I am an electrical engineer, so maybe my coding terms are not so accurate or even far from that. we have a CLI in the company, accessed from the Linux terminal, you know usual stuff, `{command.exe} {plugin} {options}, and you get the output on the terminal screen. In order to unit te...
[ "I found my answer, this code worked for me yo achieve what I was looking for.\nthanks for the commenters.\nimport re\nimport subprocess\n\nPKG_NAME = \"sudo mycli\"\nPKG_PLUGIN_START = \"The following are all installed plugin extensions:\" # this is the message before the commands list in the cli help\nPKG_PLUGIN_...
[ 0 ]
[]
[]
[ "api", "auto_generate", "command_line_interface", "python", "python_3.x" ]
stackoverflow_0074612528_api_auto_generate_command_line_interface_python_python_3.x.txt
Q: Subprocess not opening files I am writing a program to open other programs for me. os.system() would always freeze my app, so I switched to subprocess. I did some research and this is how a tutorial told me to open a program. I have only replaced the path for my variable, which contains the path. After I run this,...
Subprocess not opening files
I am writing a program to open other programs for me. os.system() would always freeze my app, so I switched to subprocess. I did some research and this is how a tutorial told me to open a program. I have only replaced the path for my variable, which contains the path. After I run this, only a commabd prompt window open...
[ "You need to create a single string with double quotes around it. In Python terms, you basically want r'\"c:\\torture\\thanks Microsoft\"' where the single quotes and the r create a Python string, which contains the file name inside double quotes.\nfrom subprocess import Popen\n\nfilename1 = \"C:/Program Files/Goog...
[ 0, 0 ]
[]
[]
[ "popen", "python", "python_3.x", "subprocess" ]
stackoverflow_0074181574_popen_python_python_3.x_subprocess.txt
Q: How to open jupyter notebook from Windows 10 task bar Through some wizardry I cannot recall, I managed to install and implement Jupyter Notebook with an icon that opens Jupyter directly in browser I am occasionally asked how I did this. However, and slightly emparisingly, I cannot remember how I did this and am un...
How to open jupyter notebook from Windows 10 task bar
Through some wizardry I cannot recall, I managed to install and implement Jupyter Notebook with an icon that opens Jupyter directly in browser I am occasionally asked how I did this. However, and slightly emparisingly, I cannot remember how I did this and am unable to help. I cannot seem to recreate this Jupyter Icon i...
[ "\nI somehow managed to implement two Anaconda Prompts, Anaconda PowerShell Prompt and Anaconda Prompt\n\nThat is standard. The first Anaconda Prompt, will open the legacy cmd configured for conda. The second will open a powershell configured for conda. SO just keep both and use the one you are more comfortable wit...
[ 2, 0 ]
[]
[]
[ "anaconda", "jupyter_notebook", "miniconda", "powershell", "python" ]
stackoverflow_0068420377_anaconda_jupyter_notebook_miniconda_powershell_python.txt
Q: how to merge two json data by mapping I have two json datas as json_1 = [{'purchasedPerson__id': 2, 'credit': 3000}, {'purchasedPerson__id': 4, 'credit': 5000}] json_2 = [{'purchasedPerson__id': 1, 'debit': 8526}, {'purchasedPerson__id': 4, 'debit': 2000}] i want to merge both the json and needed optput as json_f...
how to merge two json data by mapping
I have two json datas as json_1 = [{'purchasedPerson__id': 2, 'credit': 3000}, {'purchasedPerson__id': 4, 'credit': 5000}] json_2 = [{'purchasedPerson__id': 1, 'debit': 8526}, {'purchasedPerson__id': 4, 'debit': 2000}] i want to merge both the json and needed optput as json_final = [{'purchasedPerson__id': 2, 'credit'...
[ "This is a case where pandascan be very convenient. By converting to dataframes and merging on \"purchasedPerson__id\", you will get the desired output:\nimport pandas as pd\n\njson_1 = [{'purchasedPerson__id': 2, 'credit': 3000}, {'purchasedPerson__id': 4, 'credit': 5000}]\njson_2 = [{'purchasedPerson__id': 1, 'de...
[ 1, 1, 0 ]
[]
[]
[ "json", "python", "python_jsons", "python_jsonschema" ]
stackoverflow_0074673859_json_python_python_jsons_python_jsonschema.txt
Q: How to convolution integration(Duhamel Integration) by python? Hi~ I'm studying about structural dynamics. I want to make a code about Duhamel Integration which is kind of Convoution Integration. If the initial conditions are y(0)=0 and y'(0)=0, Duhamel Integration is like this. enter image description here Using ...
How to convolution integration(Duhamel Integration) by python?
Hi~ I'm studying about structural dynamics. I want to make a code about Duhamel Integration which is kind of Convoution Integration. If the initial conditions are y(0)=0 and y'(0)=0, Duhamel Integration is like this. enter image description here Using Ti Nspire I solved this problem with my Ti Npire softwere. The resul...
[ "Use the unevaluated Integral and then substitute in a value for t and use the doit method:\n...\n>>> y0=1/(m*wd)*Integral(eq1*eq2*eq3,(tau,0,t))\n>>> y0.subs(t,1).doit()\n-0.00623772329557205\n\n" ]
[ 1 ]
[]
[]
[ "convolution", "integrate", "python", "response", "sympy" ]
stackoverflow_0074672385_convolution_integrate_python_response_sympy.txt
Q: My Django Admin input doesn't allow me to add more than one image I'm trying to make a Django model, with Django Rest Framework. I want this to allow me to load one or more images in the same input. MODELS: from django.db import models from datetime import datetime from apps.category.models import Category from d...
My Django Admin input doesn't allow me to add more than one image
I'm trying to make a Django model, with Django Rest Framework. I want this to allow me to load one or more images in the same input. MODELS: from django.db import models from datetime import datetime from apps.category.models import Category from django.conf import settings class Product(models.Model): code = mod...
[ "You didn't post your admin.py but my guess is that you also need to register your ProductImage model as an inlines since you already use a One2Many relationship between Product and ProductImage:\nIn your admin.py:\nclass ProductImageAdmin(admin.StackedInline):\n model = ProductImage\n\nclass ProductAdmin(admin....
[ 0 ]
[]
[]
[ "backend", "django", "django_admin", "django_rest_framework", "python" ]
stackoverflow_0074672857_backend_django_django_admin_django_rest_framework_python.txt
Q: Difficulty importing ThemedTK from ttkthemes I'm trying to import ThemedTK from ttkthemes in Python3 but am getting the following error message: line 4, in from ttkthemes import Themed_TK ImportError: cannot import name 'Themed_TK' from 'ttkthemes' Any ideas? from tkinter import filedialog from tkinter import ttk...
Difficulty importing ThemedTK from ttkthemes
I'm trying to import ThemedTK from ttkthemes in Python3 but am getting the following error message: line 4, in from ttkthemes import Themed_TK ImportError: cannot import name 'Themed_TK' from 'ttkthemes' Any ideas? from tkinter import filedialog from tkinter import ttk from ttkthemes import ThemedTK from reportlab.lib...
[ "Apparently it's ThemedTk. With lowercase \"k\".\n" ]
[ 0 ]
[]
[]
[ "python", "ttk" ]
stackoverflow_0068376097_python_ttk.txt
Q: Dynamically create matrix from a vectors in numpy I'm trying to create a matrix of shape Nx3 where N is not known at first. This is what I'm basically trying to do: F = np.array([[],[],[]]) for contact in contacts: xp,yp,theta = contact # Create vectors for points and normal P = [xp...
Dynamically create matrix from a vectors in numpy
I'm trying to create a matrix of shape Nx3 where N is not known at first. This is what I'm basically trying to do: F = np.array([[],[],[]]) for contact in contacts: xp,yp,theta = contact # Create vectors for points and normal P = [xp, yp, 0] N = [np.cos(theta), np.sin(theta), 0] ...
[ "The error you are seeing is caused by trying to stack empty arrays together using np.vstack(). When you create an empty array with np.array([[],[],[]]), the resulting array has shape (3, 0), which means that it has 3 rows but no columns. When you try to stack this empty array with another array using np.vstack(), ...
[ 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074673656_numpy_python.txt
Q: How to send a DM to a user using just their user id I would like to send a dm to a user just by using their user id that I copied from their profile. This is the code that I made, but it didn't work. @client.command() async def dm(userID, *, message): user = client.get_user(userID) await user.send(message)...
How to send a DM to a user using just their user id
I would like to send a dm to a user just by using their user id that I copied from their profile. This is the code that I made, but it didn't work. @client.command() async def dm(userID, *, message): user = client.get_user(userID) await user.send(message) This is the error that appeared: discord.ext.commands.e...
[ "All you have to do is change the userID argument to user: discord.User. That argument will accept user mentions (@user), usernames (user), and ids (904360748455698502). The full code would now be:\n@client.command()\nasync def dm(user: discord.User, *, message):\n channel = await user.create_dm()\n await cha...
[ 0, 0, 0 ]
[]
[]
[ "discord", "discord.py", "python" ]
stackoverflow_0074636410_discord_discord.py_python.txt
Q: How to add new key value to yaml without overwriting it in python? I have small python script which responsible for updating my yaml file by adding new records: data = yaml.load(file) data['WIN']['Machine'] = dict(node_labels='+> tfs vs2022') data['WIN']['Machine'] = dict(vs='vs2022') yaml.dump(data, file) Every ...
How to add new key value to yaml without overwriting it in python?
I have small python script which responsible for updating my yaml file by adding new records: data = yaml.load(file) data['WIN']['Machine'] = dict(node_labels='+> tfs vs2022') data['WIN']['Machine'] = dict(vs='vs2022') yaml.dump(data, file) Every time when I run above script I will get updated yaml file like below: WI...
[ "This is not a YAML related problem, but a conceptual problem in your non-yaml related Python code.\nBy assigning a dict as value to the key Machine, you set that value. By assigning\nanother dict to the key, you overwrite that value completely, erasing the previous key-value pair.\nIf you simplify your code:\ndata...
[ 0 ]
[]
[]
[ "python", "python_3.x", "yaml" ]
stackoverflow_0074669180_python_python_3.x_yaml.txt
Q: Is there any possibility to speed the nested for loop in pandas dataframe? Is there any possibility to speed the nested for loop in pandas dataframe? I have tried itertuples instead of iterrows. But the expected outcome(speed) was not good enough. How to use list comprehension and vectorization in this code. lst3 ...
Is there any possibility to speed the nested for loop in pandas dataframe?
Is there any possibility to speed the nested for loop in pandas dataframe? I have tried itertuples instead of iterrows. But the expected outcome(speed) was not good enough. How to use list comprehension and vectorization in this code. lst3 = [] for i,j in enumerate(df2.itertuples()): Tagging1=False #if ("Con" i...
[ "Yes, it is possible to improve the performance of the nested for loop in your code by using vectorized operations and list comprehension in Pandas. Instead of using for loops to iterate over the rows of the DataFrame, you can use the apply() method and a lambda function to apply a function to each row of the DataF...
[ 0 ]
[]
[]
[ "list", "numpy", "pandas", "python" ]
stackoverflow_0074673201_list_numpy_pandas_python.txt
Q: Python function to get the t-statistic I am looking for a Python function (or to write my own if there is not one) to get the t-statistic in order to use in a confidence interval calculation. I have found tables that give answers for various probabilities / degrees of freedom like this one, but I would like to be ...
Python function to get the t-statistic
I am looking for a Python function (or to write my own if there is not one) to get the t-statistic in order to use in a confidence interval calculation. I have found tables that give answers for various probabilities / degrees of freedom like this one, but I would like to be able to calculate this for any given probabi...
[ "Have you tried scipy?\nYou will need to installl the scipy library...more about installing it here: http://www.scipy.org/install.html\nOnce installed, you can replicate the Excel functionality like such:\nfrom scipy import stats\n#Studnt, n=999, p<0.05, 2-tail\n#equivalent to Excel TINV(0.05,999)\nprint stats.t.p...
[ 60, 3, 0, 0 ]
[]
[]
[ "confidence_interval", "python", "python_2.7", "statistics" ]
stackoverflow_0019339305_confidence_interval_python_python_2.7_statistics.txt
Q: How to Change the Format of a DateTimeField Object when it is Displayed in HTML through Ajax? models.py class Log(models.Model): source = models.CharField(max_length=1000, default='') date = models.DateTimeField(default=datetime.now, blank = True) views.py The objects in the Log model are filtered so that...
How to Change the Format of a DateTimeField Object when it is Displayed in HTML through Ajax?
models.py class Log(models.Model): source = models.CharField(max_length=1000, default='') date = models.DateTimeField(default=datetime.now, blank = True) views.py The objects in the Log model are filtered so that only those with source names that match a specific account name are considered. The values of thes...
[ "You're trying to format the date in the HTML by appending it to a string. Unfortunately, this won't work because the date value will be treated as a string and not as a date object.\nTo format the date in the desired way, you will need to convert it to a date object in JavaScript and then use a date formatting fun...
[ 0, 0 ]
[]
[]
[ "ajax", "datetime", "django", "python" ]
stackoverflow_0074673906_ajax_datetime_django_python.txt
Q: How can I remove the values on top of the grouped bars with the bar_plot using axes.bar in matplotlib? I want to remove the percentage values on top of each plot, or possibly round them width = 0.2 x = np.arange(len(labels)) fig2,ax = plt.subplots() rects1 = ax.bar(x - width/2, precision_data, width, label='preci...
How can I remove the values on top of the grouped bars with the bar_plot using axes.bar in matplotlib?
I want to remove the percentage values on top of each plot, or possibly round them width = 0.2 x = np.arange(len(labels)) fig2,ax = plt.subplots() rects1 = ax.bar(x - width/2, precision_data, width, label='precision',color ='firebrick') rects2 = ax.bar(x + width/2 , recall_data, width, label='recall',color = 'royalbl...
[ "\nTo remove the text on top of your bars, simply comment out ax.bar_label(rects1) and ax.bar_label(rects2):\n\nTo round the labels, you may use the fmt argument: ax.bar_label(labels, fmt='%.2f')\n\n\n" ]
[ 1 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0074674124_matplotlib_python.txt
Q: Why getting this selenium.common.exceptions.ElementClickInterceptedException: Message: element click intercepted: Element I know already upload answer to this same question but I try them they are not working for me because there is also some some update in selenium code too. Getting this Error selenium.common.exc...
Why getting this selenium.common.exceptions.ElementClickInterceptedException: Message: element click intercepted: Element
I know already upload answer to this same question but I try them they are not working for me because there is also some some update in selenium code too. Getting this Error selenium.common.exceptions.ElementClickInterceptedException: Message: element click intercepted: Element <div class="up-typeahead-fake" data-test=...
[ "That error indicates that you have to click using JS execution like:\n import time\n\n skill = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH,'//div[contains(@class,\"up-typeahead\")]')))\n driver.execute_script(\"arguments[0].click();\" ,skill)\n time.sleep(1)\n\n", "By clicking on \"Advan...
[ 1, 0 ]
[]
[]
[ "automation", "python", "selenium", "selenium_webdriver", "xpath" ]
stackoverflow_0074673772_automation_python_selenium_selenium_webdriver_xpath.txt
Q: Python: How to print a looping nested list as a Matrix I want to print a matrix of p*p (where p is an input taken from the user). The matrix should be in a format of [m,n] i.e [[[3,0],[3,1],[3,2],[3,3]],[2,0],[2,1],[2,2],[2,3]]... and so on. a = int(input()) l1 = [] for i in range(a): l1.append([]) ...
Python: How to print a looping nested list as a Matrix
I want to print a matrix of p*p (where p is an input taken from the user). The matrix should be in a format of [m,n] i.e [[[3,0],[3,1],[3,2],[3,3]],[2,0],[2,1],[2,2],[2,3]]... and so on. a = int(input()) l1 = [] for i in range(a): l1.append([]) for j in range(a): l1[i] = [j,i] print(l...
[ "# Take input from the user\np = int(input())\n\n# Create an empty list\nl1 = []\n\n# Iterate over the range 0 to p\nfor i in range(p):\n # Create a new empty sublist for each iteration of the outer loop\n l1.append([])\n\n # Iterate over the range 0 to p\n for j in range(p):\n # Append the value...
[ 0 ]
[]
[]
[ "list", "loops", "matrix", "python" ]
stackoverflow_0074672951_list_loops_matrix_python.txt
Q: How to use multiprocessing in Python for for loop? I'm new to Python and multiprocessing, I would like to speed up my current code processing speed as it takes around 8 mins for 80 images. I only show 1 image for this code for reference purpose. I got into know that multiprocessing helps on this and gave it a try ...
How to use multiprocessing in Python for for loop?
I'm new to Python and multiprocessing, I would like to speed up my current code processing speed as it takes around 8 mins for 80 images. I only show 1 image for this code for reference purpose. I got into know that multiprocessing helps on this and gave it a try but somehow not working as what I expected. import numpy...
[ "To use multiprocessing to speed up your code, you can use the Pool class from the multiprocessing module. The Pool class allows you to run multiple processes in parallel, which can help speed up your code.\nTo use the Pool class, you need to first create a Pool object and then use the map method to apply a functio...
[ 1 ]
[]
[]
[ "multiprocessing", "python", "python_3.x", "python_multiprocessing" ]
stackoverflow_0074674131_multiprocessing_python_python_3.x_python_multiprocessing.txt
Q: Parser unrecognized arguments I accept a file path as an argument for my .huy file type python editor but when i change to exe and run it it says: Editor.exe: error: unrecognized arguments: C:\Users\Doan 1\Desktop\test.huy but when i run the python file: Editor.py -f "C:\Users\Doan 1\Desktop\test.huy" it works ho...
Parser unrecognized arguments
I accept a file path as an argument for my .huy file type python editor but when i change to exe and run it it says: Editor.exe: error: unrecognized arguments: C:\Users\Doan 1\Desktop\test.huy but when i run the python file: Editor.py -f "C:\Users\Doan 1\Desktop\test.huy" it works how do i fix this? this was the pars...
[ "To fix this issue, you need to pass the -f flag and the file path to the EXE file when you run it from the command line, just like you do when running the Python file.\nHere is an example of how you can run the EXE file and pass the required arguments:\nEditor.exe -f \"C:\\Users\\Doan 1\\Desktop\\test.huy\"\n\nMak...
[ 0 ]
[]
[]
[ "argparse", "python", "python_3.x" ]
stackoverflow_0074672656_argparse_python_python_3.x.txt
Q: Discord bot cannot connect a voice channel I'm trying to make a discord bot first time, but the bot can't connect to the voice channel without any error, please help me, thanks. This command worked successfully but the bot cannot connect my voice channel when enter 'else' statement. Please help me.Thanks a lot. `...
Discord bot cannot connect a voice channel
I'm trying to make a discord bot first time, but the bot can't connect to the voice channel without any error, please help me, thanks. This command worked successfully but the bot cannot connect my voice channel when enter 'else' statement. Please help me.Thanks a lot. ` class music_cog(commands.Cog): def __init__...
[ "Simple all u need to do is to download PyNaCl,\npip install PyNaCl\n\nhere is the error that u got\n" ]
[ 0 ]
[]
[]
[ "discord", "discord.py", "python" ]
stackoverflow_0074672935_discord_discord.py_python.txt
Q: Error while executing bash for loop from python subprocess I want to run this command from python mentioned here: ffmpeg -f concat -safe 0 -i <(for f in ./*.wav; do echo "file '$PWD/$f'"; done) -c copy output.wav But i can't even run this: subprocess.run('for i in {1..3}; do echo $i; done'.split(), capture_output...
Error while executing bash for loop from python subprocess
I want to run this command from python mentioned here: ffmpeg -f concat -safe 0 -i <(for f in ./*.wav; do echo "file '$PWD/$f'"; done) -c copy output.wav But i can't even run this: subprocess.run('for i in {1..3}; do echo $i; done'.split(), capture_output=True) Error: Traceback (most recent call last): File "/media...
[ "There are two errors here, or really, three;\n\nYou are trying to use shell features without shell=True\nYou are trying to use Bash features, but the default shell on non-Windows platforms is POSIX sh; you can fix that with executable='/bin/bash' (obviously, adjust the path if necessary).\n\nMore fundamentally, th...
[ 1 ]
[]
[]
[ "bash", "python", "subprocess" ]
stackoverflow_0074673644_bash_python_subprocess.txt
Q: Python - open file in paint with whitespaces I am trying to open an image in paint with python, however, the path contains a space, paint throws an error saying it cannot find the path because it has just split the string until the first space. Can someone tell me how to solve this without changing the path? Here ...
Python - open file in paint with whitespaces
I am trying to open an image in paint with python, however, the path contains a space, paint throws an error saying it cannot find the path because it has just split the string until the first space. Can someone tell me how to solve this without changing the path? Here is my code: import subprocess, os paintImage = "C...
[ "You can rewrite the following line\npaintImage = \"C:\\\\Users\\\\Me\\MY Images\\\\image.png\" \n\nto\npaintImage = \"C:\\\\Users\\\\Me\\MYImages\\\\image.png\"\n\nMYImages should be the new name of the folder no spaces.\n" ]
[ 0 ]
[]
[]
[ "image", "paint", "python" ]
stackoverflow_0063423058_image_paint_python.txt
Q: Error status code 403 even with headers, Python Requests I am sending a request to some url. I Copied the curl url to get the code from curl to python tool. So all the headers are included, but my request is not working and I recieve status code 403 on printing and error code 1020 in the html output. The code is i...
Error status code 403 even with headers, Python Requests
I am sending a request to some url. I Copied the curl url to get the code from curl to python tool. So all the headers are included, but my request is not working and I recieve status code 403 on printing and error code 1020 in the html output. The code is import requests headers = { 'User-Agent': 'Mozilla/5.0 (Wi...
[ "It works on my machine, so I am not sure what the problem is.\nHowever, when I want send a request which does not work, I often try if it works using playwright. Playwright uses a browser driver and thus mimics your actual browser when visiting the page. It can be installed using pip install playwright. When you t...
[ 1, 1 ]
[]
[]
[ "python", "python_requests" ]
stackoverflow_0074446830_python_python_requests.txt
Q: No module named 'graphql.type' in Django I am New in Django and GraphQL, following the the article, I am using python 3.8 in virtual env and 3.10 in windows, but same error occurs on both side, also tried the this Question, i also heard that GraphQL generate queries, But dont know how to generate it, But this erro...
No module named 'graphql.type' in Django
I am New in Django and GraphQL, following the the article, I am using python 3.8 in virtual env and 3.10 in windows, but same error occurs on both side, also tried the this Question, i also heard that GraphQL generate queries, But dont know how to generate it, But this error occurs: Traceback (most recent call last): ...
[ "You can try these following ways,\nOne, you can find graphql directory in the project, on python path. renaming it will fix the issue.\nAnd also you can try these commands,\npip install pip --upgrade\npip install setuptools --upgrade\npip install gql[all]\n\nHope this helps, if not please let know. Thanks\n" ]
[ 0 ]
[]
[]
[ "ariadne_graphql", "django", "graphql", "python" ]
stackoverflow_0074674006_ariadne_graphql_django_graphql_python.txt
Q: Convert bytes to a string I captured the standard output of an external program into a bytes object: >>> from subprocess import * >>> command_stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0] >>> >>> command_stdout b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Ma...
Convert bytes to a string
I captured the standard output of an external program into a bytes object: >>> from subprocess import * >>> command_stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0] >>> >>> command_stdout b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2\n' I want to ...
[ "Decode the bytes object to produce a string:\n>>> b\"abcde\".decode(\"utf-8\") \n'abcde'\n\nThe above example assumes that the bytes object is in UTF-8, because it is a common encoding. However, you should use the encoding your data is actually in!\n", "Decode the byte string and turn it in to a character (Unico...
[ 5363, 393, 256, 127, 120, 48, 43, 38, 34, 28, 20, 19, 19, 9, 8, 8, 5, 4, 3, 3, 2, 2, 1, 0 ]
[]
[]
[ "python", "python_3.x", "string" ]
stackoverflow_0000606191_python_python_3.x_string.txt
Q: Kivymd APK App (created with Buildozer) closes after opening up I have created an APK file from Python Kivy & KivyMD, using Buildozer. When I open the app after installing it, it shows the splash image and then closes. I have checked and found that their seems no issue in the main.py, as I have correctly listed Ki...
Kivymd APK App (created with Buildozer) closes after opening up
I have created an APK file from Python Kivy & KivyMD, using Buildozer. When I open the app after installing it, it shows the splash image and then closes. I have checked and found that their seems no issue in the main.py, as I have correctly listed Kivy & KivyMD in the requirements in the Buildozer.spec file. (kivy==2....
[ "If you have some other plugins just add them like this:\n# comma separated e.g. requirements = sqlite3,kivy\nrequirements = python3,kivy==2.0.0,kivymd==0.104.1,pluginname==version\n\n", "requirements = python3,kivy==2.0.0,kivymd==0.104.1,nltk,numpy,keras\nThat's all you need\n" ]
[ 1, 0 ]
[]
[]
[ "buildozer", "keras", "kivy", "kivymd", "python" ]
stackoverflow_0069593107_buildozer_keras_kivy_kivymd_python.txt
Q: analyze the train-validation accuracy learning curve I am building a two-layer neural network from scratch on the Fashion MNIST dataset. In between, using the RELU as activation and on the last layer, I am using softmax cross entropy. I am getting the below learning curve between train and validation accuracy whic...
analyze the train-validation accuracy learning curve
I am building a two-layer neural network from scratch on the Fashion MNIST dataset. In between, using the RELU as activation and on the last layer, I am using softmax cross entropy. I am getting the below learning curve between train and validation accuracy which is wrong obviously. But if you see my loss curve, it's d...
[ "I don't know exactly what you are doing, and I don't know anything about your architecture, but it's wrong to use ReLU on the last layer.\nUsually you leave the last layer as linear (no activation). This will produce the logits that enter the Softmax. The output of the softmax will try to approximate the probabili...
[ 0 ]
[]
[]
[ "cross_entropy", "neural_network", "numpy", "python", "softmax" ]
stackoverflow_0074671726_cross_entropy_neural_network_numpy_python_softmax.txt
Q: Django Rest Framework Cannot save a model it tells me the date must be a str I have this Profile model that also has location attached to it but not trying to save the location now only trying to save the Profile but get an error: class Profile(models.Model): # Gender M = 'M' F = 'F' O = 'O' G...
Django Rest Framework Cannot save a model it tells me the date must be a str
I have this Profile model that also has location attached to it but not trying to save the location now only trying to save the Profile but get an error: class Profile(models.Model): # Gender M = 'M' F = 'F' O = 'O' GENDER = [ (M, "male"), (F, "female"), (O, "Other") ] ...
[ "The error you are encountering is likely due to the birthdate field in your Profile model being a DateField, but the value you are trying to save is a string. You must convert the string value to a date object before saving it to the birthdate field.\nHere is an example of how you can do this:\nfrom datetime impor...
[ 1 ]
[]
[]
[ "django", "django_rest_framework", "python" ]
stackoverflow_0074674389_django_django_rest_framework_python.txt
Q: ValueError: could not convert string to float: '"815745789754417152"' This is error code ValueError Traceback (most recent call last) Input In [42], in <cell line: 3>() 1 from sklearn.neighbors import KNeighborsClassifier as knn 2 classifier=knn(n_neighbors=5) ----> 3 cla...
ValueError: could not convert string to float: '"815745789754417152"'
This is error code ValueError Traceback (most recent call last) Input In [42], in <cell line: 3>() 1 from sklearn.neighbors import KNeighborsClassifier as knn 2 classifier=knn(n_neighbors=5) ----> 3 classifier.fit(X,y) 4 bots = training_data[training_data.bot==1] 5...
[ "The string itself seems to be \"815745789754417152\". It can't convert \" to a numeric value.\nYou can strip it off by:\nstring = string[1:-1]\n\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074674430_python.txt
Q: How to get the continent given the coordinates (latitude and longitude) in Python? Is there a method that allows to get the continent where it is in place given its coordinates (without an API key)? I'm using: from geopy.geocoders import Nominatim geolocator = Nominatim(user_agent='...') location = geolocator.reve...
How to get the continent given the coordinates (latitude and longitude) in Python?
Is there a method that allows to get the continent where it is in place given its coordinates (without an API key)? I'm using: from geopy.geocoders import Nominatim geolocator = Nominatim(user_agent='...') location = geolocator.reverse('51.0456448, 3.7273618') print(location.address) print((location.latitude, location....
[ "A bit late, but for future reference and those who could need it, like me recently, here is one way to do it with Wikipedia and the use of Pandas, requests and geopy:\nimport pandas as pd\nimport requests\nfrom geopy.geocoders import Nominatim\n\nURLS = {\n \"Africa\": \"https://en.wikipedia.org/wiki/List_of_so...
[ 0 ]
[]
[]
[ "coordinates", "geolocation", "geopy", "python", "python_requests" ]
stackoverflow_0069771711_coordinates_geolocation_geopy_python_python_requests.txt
Q: Telegram Inline Bot - Buttons get stuck loading I am working on a inline telegram bot. The bot should be invoked through any chat so I am using the inline method, however the bot now uses a conversation flow that requires the conversation to be started by using the /start command which is not what I want. After ca...
Telegram Inline Bot - Buttons get stuck loading
I am working on a inline telegram bot. The bot should be invoked through any chat so I am using the inline method, however the bot now uses a conversation flow that requires the conversation to be started by using the /start command which is not what I want. After calling the bot with the command I set the user should ...
[ "\nthat requires the conversation to be started by using the /start command which is not what I want.\n\nThis is not the case - you can use any handler as entry point.\n\nI tried switching out the Command handler to be a InlineQueryHandler, but that didn't give any results\n\nThis is one caveat here: The per_chat s...
[ 0 ]
[]
[]
[ "py_telegram_bot_api", "python", "python_telegram_bot" ]
stackoverflow_0074672289_py_telegram_bot_api_python_python_telegram_bot.txt
Q: How do I deal with and it is returning ``` HTTPError: HTTP Error 403: Forbidden? I am trying to copy a table from a website using this code covid = pd.read_html("https://covid19.ncdc.gov.ng/")[0].head() and it is returning HTTPError: HTTP Error 403: Forbidden A: You can use requests: import pandas as pd import ...
How do I deal with and it is returning ``` HTTPError: HTTP Error 403: Forbidden?
I am trying to copy a table from a website using this code covid = pd.read_html("https://covid19.ncdc.gov.ng/")[0].head() and it is returning HTTPError: HTTP Error 403: Forbidden
[ "You can use requests:\nimport pandas as pd\nimport requests\nreq=requests.get('https://covid19.ncdc.gov.ng/')\ncovid = pd.read_html(req.text)[0].head()\n'''\n| | States Affected | No. of Cases (Lab Confirmed) | No. of Cases (on admission) | No. Discharged | No. of Deaths |\n|---:|:------------------|-...
[ 0 ]
[]
[]
[ "dataframe", "error_handling", "html", "list", "python" ]
stackoverflow_0074670041_dataframe_error_handling_html_list_python.txt
Q: numpy: multiply uint16 ndarray by scalar I have a ndarray 'a' of dtype uint16. I would like to multiply all entries by a scalar, let's say 2. The max value for uint16 is 65535. Let's assume some entries of a are greater than 65535/2. Because of numerical issues, these values will become small values after applying...
numpy: multiply uint16 ndarray by scalar
I have a ndarray 'a' of dtype uint16. I would like to multiply all entries by a scalar, let's say 2. The max value for uint16 is 65535. Let's assume some entries of a are greater than 65535/2. Because of numerical issues, these values will become small values after applying the multiplication For example, if a is: 1, 1...
[ "I think the only way is to cast the array to a bigger data type and then clip the values before casting it back to uint16.\nFor example:\nimport numpy as np\n\na = np.array([*stuff], dtype=np.uint16)\nres = np.clip(a.astype(np.uint32) * 2, 0, 65535).astype(np.uint16)\n\n" ]
[ 2 ]
[]
[]
[ "multidimensional_array", "numeric", "numpy", "python", "type_conversion" ]
stackoverflow_0074670564_multidimensional_array_numeric_numpy_python_type_conversion.txt
Q: How do versions after py3.10 implement asyncio.get_event_loop with the same behavior as previous versions python3.10-asyncio-get_event_loop Deprecated since version 3.10: Emits a deprecation warning if there is no running event loop. In future Python releases, this function may become an alias of get_running_loop(...
How do versions after py3.10 implement asyncio.get_event_loop with the same behavior as previous versions
python3.10-asyncio-get_event_loop Deprecated since version 3.10: Emits a deprecation warning if there is no running event loop. In future Python releases, this function may become an alias of get_running_loop() and will accordingly raise a RuntimeError if there is no running event loop. The behavior of get_event_loop h...
[ "If you want to hide the DeprecationWarning, set a higher logging level. Or if you have to use Python3.10+, then you can do something like:\nimport asyncio\n\ndef get_event_loop() -> asyncio.AbstractEventLoop:\n try:\n return asyncio.get_running_loop()\n except (RuntimeError, Exception):\n retur...
[ 0 ]
[]
[]
[ "python", "python_3.x", "python_asyncio", "sanic" ]
stackoverflow_0074673969_python_python_3.x_python_asyncio_sanic.txt
Q: pattern matching in Python with regex problem I am trying to learn pattern matching with regex, the course is through coursera and hasn't been updated since python 3 came out so the instructors code is not working correctly. Here's what I have so far: # example Wiki data wiki= """There are several Buddhist univers...
pattern matching in Python with regex problem
I am trying to learn pattern matching with regex, the course is through coursera and hasn't been updated since python 3 came out so the instructors code is not working correctly. Here's what I have so far: # example Wiki data wiki= """There are several Buddhist universities in the United States. Some of these have exis...
[ "In fact, for current versions of Python, you do not need to add re.VERBOSE at all. If you do\nfor item in re.finditer(pattern, wiki): \n print(item.groupdict())\n\nthe program will print\n{'title': '• Naropa University ', 'city': 'Boulder', 'state'...
[ 0, 0, 0 ]
[]
[]
[ "pattern_matching", "python", "regex" ]
stackoverflow_0074670737_pattern_matching_python_regex.txt
Q: regex matched values convert to float/integers Consider this example: import re string = "1-3-a" a, b, c = re.match("(\d+)-(\d+)-(\w+)", string).groups() print(a + b) This will print: '13'. However, I want to use these values as digits (integers or floats), while keeping variable c as a string. Of course I can do...
regex matched values convert to float/integers
Consider this example: import re string = "1-3-a" a, b, c = re.match("(\d+)-(\d+)-(\w+)", string).groups() print(a + b) This will print: '13'. However, I want to use these values as digits (integers or floats), while keeping variable c as a string. Of course I can do a = int(a) etc. but I think there must be a more co...
[ "Regex will not do this natively, that's simply not its job. One way you could achieve it (if you wanted more of a \"one-line\" solution) is to use the map function to apply the int() function to every element in the groups tuple.\nimport re\nstring = \"1-3\"\na, b = map(int, re.match(\"(\\d+)-(\\d+)\", string).gro...
[ 1 ]
[]
[]
[ "match", "python", "regex" ]
stackoverflow_0074674564_match_python_regex.txt
Q: Generate a connected line with different amplitude I'm trying to make a game like Line, but with a horizontal and not vertical wave. The problem is making that the wave continues even after changing its amplitude (I will change the frequency later). So far I have reached this part of wave: import pygame import pyg...
Generate a connected line with different amplitude
I'm trying to make a game like Line, but with a horizontal and not vertical wave. The problem is making that the wave continues even after changing its amplitude (I will change the frequency later). So far I have reached this part of wave: import pygame import pygame.gfxdraw import math import time DISPLAY_W, DISPLAY_...
[ "One issue with your code is that you are using a variable called XCord to store the Y-coordinate of each point in the wave. This variable should be called YCord instead, since it represents the Y-coordinate of the point on the screen.\nAnother issue is that you are using a variable called waveFrequency to control ...
[ 0 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0074649361_pygame_python.txt
Q: How to implement third Nelson's rule with Pandas? I am trying to implement Nelson's rules using Pandas. One of them is giving me grief, specifically number 3: Using some example data: data = pd.DataFrame({"values":[1,2,3,4,5,6,7,5,6,5,3]}) values 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 5 8 6 9 5 10 3 My first ...
How to implement third Nelson's rule with Pandas?
I am trying to implement Nelson's rules using Pandas. One of them is giving me grief, specifically number 3: Using some example data: data = pd.DataFrame({"values":[1,2,3,4,5,6,7,5,6,5,3]}) values 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 5 8 6 9 5 10 3 My first approach was to use a rolling windo...
[ "With the following toy dataframe (an extended version of yours):\nimport pandas as pd\n\n\ndf = pd.DataFrame({\"values\": [1, 2, 3, 4, 5, 6, 7, 5, 6, 5, 3, 11, 12, 13, 14, 15, 16, 4, 3, 8, 9, 10, 2]})\n\nHere is one way to do it:\n# Find consecutive values\ndf[\"check\"] = (df.diff() > 0).rolling(6).sum()\ndf[\"ch...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074630430_pandas_python.txt
Q: Sending JSON to Flask, request.args vs request.form My understanding is that request.args in Flask contains the URL encoded parameters from a GET request while request.form contains POST data. What I'm having a hard time grasping is why when sending a POST request, trying to access the data with request.form retur...
Sending JSON to Flask, request.args vs request.form
My understanding is that request.args in Flask contains the URL encoded parameters from a GET request while request.form contains POST data. What I'm having a hard time grasping is why when sending a POST request, trying to access the data with request.form returns a 400 error but when I try to access it with request.a...
[ "You are POST-ing JSON, neither request.args nor request.form will work.\nrequest.form works only if you POST data with the right content types; form data is either POSTed with the application/x-www-form-urlencoded or multipart/form-data encodings.\nWhen you use application/json, you are no longer POSTing form data...
[ 63, 3, 0 ]
[]
[]
[ "flask", "json", "post", "python", "rest" ]
stackoverflow_0023326368_flask_json_post_python_rest.txt
Q: What should be the correct code in order to get the factorial of n? n=int(input("Enter a number: ")) p=1 for i in range(n): p*=i print(p) I wanted to find out the factorial of a number but I always get 0 as output. A: The factorial of a number is the product of all the numbers from 1 to that number. However...
What should be the correct code in order to get the factorial of n?
n=int(input("Enter a number: ")) p=1 for i in range(n): p*=i print(p) I wanted to find out the factorial of a number but I always get 0 as output.
[ "The factorial of a number is the product of all the numbers from 1 to that number. However, in your code, you are starting the loop from 0 and then multiplying the product by the loop variable. This means that the product will always be 0 because any number multiplied by 0 is 0.\nYou can change the starting value ...
[ 0, 0 ]
[]
[]
[ "factorial", "numbers", "python" ]
stackoverflow_0074674629_factorial_numbers_python.txt
Q: How to convert dataframe to nested dictionary with specific array and list? How can I use a dataframe to create a nested dictionary, with interleaved lists and columns, as in the example below? Create dictionary: columns = ["name","reason","cgc","limit","email","address","message","type","value"] data = [("Paulo",...
How to convert dataframe to nested dictionary with specific array and list?
How can I use a dataframe to create a nested dictionary, with interleaved lists and columns, as in the example below? Create dictionary: columns = ["name","reason","cgc","limit","email","address","message","type","value"] data = [("Paulo", "La Fava","123456","0","p@p.com.br","avenue A","msg txt 1","string","low"), ("Pe...
[ "Arrays in Spark are homogeneous i.e. the elements should have same data type. In your sample expected output, the array type of \"additional_fields\" does not match with other two map fields \"issuer\" & \"recipient\".\nYou have two ways to resolve this:\nIf you can relax \"additional_fields\" to be just the map (...
[ 0 ]
[]
[]
[ "pandas", "pyspark", "python" ]
stackoverflow_0074669493_pandas_pyspark_python.txt
Q: How do I fill a list with with tuples using a for-loop in python? I just finished implementing a working Python code for the Dijkstra-Pathfinding algorithm. I am applying this algorithm to a graph with edges, which I have written as a list of tuples: graph = Graph([ ("a", "b", 2),("a", "c", 5), ("a...
How do I fill a list with with tuples using a for-loop in python?
I just finished implementing a working Python code for the Dijkstra-Pathfinding algorithm. I am applying this algorithm to a graph with edges, which I have written as a list of tuples: graph = Graph([ ("a", "b", 2),("a", "c", 5), ("a", "d", 2),("b", "c", 3), ("b", "e", 1),("c", "e", 1), ...
[ "In this line the parenthesis are serving as a container for multiple string arguments.\ngraph.append(\"i\", \"j\", \"4\")\n\nYou need to add a layer of nested parenthesis to indicate that the argument is a single tuple.\ngraph.append((\"i\", \"j\", \"4\"))\n\n", "To add an edge to a graph, you can use the add_ed...
[ 0, 0 ]
[]
[]
[ "algorithm", "dijkstra", "graph_theory", "python", "search" ]
stackoverflow_0074674611_algorithm_dijkstra_graph_theory_python_search.txt
Q: Changing a class value of a class attribute with default 0 through instance value I am working with a certain script that calculates discount, where its default is 0, hwoever special items have varied discounts, and my challenge is that I am unable top update the discount. Here's a sample code: class Person(): ...
Changing a class value of a class attribute with default 0 through instance value
I am working with a certain script that calculates discount, where its default is 0, hwoever special items have varied discounts, and my challenge is that I am unable top update the discount. Here's a sample code: class Person(): def __init__(self, item, quantity, money,discount=0): self.discount=discount ...
[ "I think your problem here is that you are trying to define the attributes of the superclass Person by the subclass Privilage. The subclass will inherit any attributes and methods from the superclass, but not vice versa.\nA solution would be to move the if-else loop from Person to the Privilage class and then it w...
[ 0 ]
[]
[]
[ "class", "inheritance", "methods", "oop", "python" ]
stackoverflow_0074674186_class_inheritance_methods_oop_python.txt
Q: Start / Resume Generator without using next Is there a way to continue a function based on where it was last run. We want each call to do something else, e.g. (first call adds 1, second adds 2, third call adds 3), and then do something else. def a_generator(): yield lambda x: x + 1 yield lambda x: x + 2 ...
Start / Resume Generator without using next
Is there a way to continue a function based on where it was last run. We want each call to do something else, e.g. (first call adds 1, second adds 2, third call adds 3), and then do something else. def a_generator(): yield lambda x: x + 1 yield lambda x: x + 2 yield lambda x: x + 3 yield lambda x: f"Oka...
[ "Your code does that already, but consider that you have a generator that returns functions, and treat it accordingly:\ndef a_generator():\n yield lambda x: x + 1\n yield lambda x: x + 2\n yield lambda x: x + 3\n yield lambda x: f\"Okay we are almost complete {x}\"\n\nfor generator in a_generator():\n ...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074663305_python.txt
Q: RuntimeWarning: overflow encountered in exp predictions = 1 / (1 + np.exp(-predictions)) this is the code I'm trying to implement for the dataset file and as I mentioned before the result just gives a 0 and the error : RuntimeWarning: overflow encountered in exp predictions = 1 / (1 + np.exp(-predictions)) I tried...
RuntimeWarning: overflow encountered in exp predictions = 1 / (1 + np.exp(-predictions))
this is the code I'm trying to implement for the dataset file and as I mentioned before the result just gives a 0 and the error : RuntimeWarning: overflow encountered in exp predictions = 1 / (1 + np.exp(-predictions)) I tried many solutions for other codes related with this prediction but still the same `import numpy ...
[ "The RuntimeWarning: overflow encountered in exp warning indicates that the exp function in NumPy has encountered an overflow error. This means that the input value to the exp function is too large, and the function cannot compute the exponential of this value.\nThe exp function in NumPy computes the exponential of...
[ 1, 0 ]
[]
[]
[ "logistic_regression", "python" ]
stackoverflow_0074674245_logistic_regression_python.txt
Q: python: keep only unique combinations from two columns in either order of dataframe I have a problem very similar to the question here: Unique combination of two columns with mixed values however my original dataframe has an additional column of values. This value is always the same for each combination (ie A,B,5 ...
python: keep only unique combinations from two columns in either order of dataframe
I have a problem very similar to the question here: Unique combination of two columns with mixed values however my original dataframe has an additional column of values. This value is always the same for each combination (ie A,B,5 and B,A,5). My plan is to essentially ignore it when creating the key column and then dr...
[ "With the following toy dataframe:\nimport pandas as pd\n\ndf = pd.DataFrame(\n {\n \"p1\": [\"a\", \"b\", \"a\", \"a\", \"b\", \"d\", \"c\"],\n \"p2\": [\"b\", \"a\", \"c\", \"d\", \"c\", \"a\", \"b\"],\n \"value\": [1, 1, 2, 3, 5, 3, 5],\n },\n columns=[\"p1\", \"p2\", \"value\"],\n)...
[ 0 ]
[]
[]
[ "pandas", "python", "sorting" ]
stackoverflow_0074618025_pandas_python_sorting.txt
Q: Need only parent tag when i parse a html tag using beautifulsoup If i specify li in find_all() method i should only get the parent elements and not all li elements in the html. ofcourse it makes sense that find_all() takes all li into consideration but i can use child or parent in the loop to get the child list el...
Need only parent tag when i parse a html tag using beautifulsoup
If i specify li in find_all() method i should only get the parent elements and not all li elements in the html. ofcourse it makes sense that find_all() takes all li into consideration but i can use child or parent in the loop to get the child list elements. I'm trying to parse only the parent tags and print them in a s...
[ "Try to use .find_parent to filter-out unwanted <li>:\nfrom bs4 import BeautifulSoup\n\nhtml_doc = \"\"\"\\\n<html>\n<p>\nsomething\n</p>\n<li>\ntext i need\n</li>\n<li>\ntext i need \n <ol>\n <li>\n text i need but appended to parent li tag\n </li>\n <li>\n text i need but appended to parent li t...
[ 0 ]
[]
[]
[ "beautifulsoup", "html", "python", "python_3.x" ]
stackoverflow_0074674636_beautifulsoup_html_python_python_3.x.txt
Q: Recognizing matrix from image I have written algorithm that solves the pluszle game matrix. Input is numpy array. Now I want to recognize the digits of matrix from screenshot. there are different levels, this is hard one this is easy one the output of recognition should be numpy array array([[6, 2, 4, 2], [...
Recognizing matrix from image
I have written algorithm that solves the pluszle game matrix. Input is numpy array. Now I want to recognize the digits of matrix from screenshot. there are different levels, this is hard one this is easy one the output of recognition should be numpy array array([[6, 2, 4, 2], [7, 8, 9, 7], [1, 2, 4, 4], ...
[ "1- Binarize\nTesseract needs you to binarize the image first. No need for contour or any convolution here. Just a threshold should do. Especially considering that you are trying to che... I mean win intelligently to a specific game. So I guess you are open to some ad-hoc adjustments.\nFor example, (hard<240).any(a...
[ 1, 0 ]
[]
[]
[ "computer_vision", "opencv", "python", "python_tesseract", "tesseract" ]
stackoverflow_0074674268_computer_vision_opencv_python_python_tesseract_tesseract.txt
Q: Django - migrate command not using latest migrations file I have 5 migration files created. But when I run ./manage.py migrate it always tries to apply the migrations file "3". Even though the latest one is file 5. How can I fix this issue? I have tried: ./manage.py makemigrations app_name ./manage.py migrate app_...
Django - migrate command not using latest migrations file
I have 5 migration files created. But when I run ./manage.py migrate it always tries to apply the migrations file "3". Even though the latest one is file 5. How can I fix this issue? I have tried: ./manage.py makemigrations app_name ./manage.py migrate app_name ./manage.py migrate --run-syncdb Also, I checked the dbsh...
[ "Simple thing, because you didn't use migration file value while doing makemigrations. And migration file value is 0005. You must specify that value while doing makemigrations.\nUse these three commands for migrations:\npython manage.py makemigrations appname\n\npython manage.py sqlmigrate appname 0005 #specified t...
[ 0, 0 ]
[]
[]
[ "django", "django_migrations", "python" ]
stackoverflow_0074561280_django_django_migrations_python.txt
Q: Discord event on_member_join not working when a member joins the guild I have an event in my discord bot that sends an embed to welcome a member when the join the guild. No errors are produced but the event does not seem to work for me. Here is the code for the event: @bot.event async def on_member_join(member): ...
Discord event on_member_join not working when a member joins the guild
I have an event in my discord bot that sends an embed to welcome a member when the join the guild. No errors are produced but the event does not seem to work for me. Here is the code for the event: @bot.event async def on_member_join(member): """ The code in this event is executed every time a member joins the ...
[ "The reason you're getting an Error, is because the e in discord.embed is lowercase\nembed = discord.embed(title=f'Welcome to {member.guild.name}',\n description=f'{member.mention}, welcome to the server! \\nMake sure to checkout the rules first. Enjoy your stay <3',\n color=0x...
[ 0, 0 ]
[]
[]
[ "discord", "discord.py", "python" ]
stackoverflow_0074663887_discord_discord.py_python.txt
Q: Switching Values in Dataframe with Lambda expression I have a dataframe with 3 columns For each TicketID, I want to iterate through all the other rows in the dataframe, searching for the TicketID as a String somewhere within the TicketStatus. If we find a match for the ticketID within another row's TicketStatus, w...
Switching Values in Dataframe with Lambda expression
I have a dataframe with 3 columns For each TicketID, I want to iterate through all the other rows in the dataframe, searching for the TicketID as a String somewhere within the TicketStatus. If we find a match for the ticketID within another row's TicketStatus, we will switch the Odds fields for that matching pair. Ex...
[ "You can iterate through the rows of the dataframe and use the str.contains() method to check if the TicketStatus of a row contains a given TicketID. If a match is found, you can update the Odds value for both rows.\nHere is an example implementation:\nimport pandas as pd\n\n# define the function that will be appli...
[ 1 ]
[]
[]
[ "dataframe", "lambda", "python" ]
stackoverflow_0074674843_dataframe_lambda_python.txt
Q: How to solve "AttributeError: 'float' object has no attribute 'lower'" enter image description here Getting issues with my code unable to understand what to do next can anyone help me out # Importing the libraries import numpy as np import pandas as pd import tensorflow as tf from tensorflow.keras.preprocessing.te...
How to solve "AttributeError: 'float' object has no attribute 'lower'"
enter image description here Getting issues with my code unable to understand what to do next can anyone help me out # Importing the libraries import numpy as np import pandas as pd import tensorflow as tf from tensorflow.keras.preprocessing.text import Tokenizer from tensorflow.keras.preprocessing.sequence import pad_...
[ "It appears that the error is happening with data['Plot'] = data['Plot'].apply(lambda x: x.lower()) (you are calling the apply function on a column of data -> one of the values in the column is not a string so it doesn't have the lower method)!\nYou could fix this by checking if the instance is actually of type str...
[ 0, 0 ]
[]
[]
[ "artificial_intelligence", "attributeerror", "pandas", "python" ]
stackoverflow_0074674913_artificial_intelligence_attributeerror_pandas_python.txt
Q: Naive bayes with python but seperated two file as 'trainset.csv' and 'testset.csv' I need to apply the naive Bayes algorithm with these files but I search for the algorithm and every example contains '1 CSV file and manually separated train and test set'. I already have 2 CSV file for the train and test set how ca...
Naive bayes with python but seperated two file as 'trainset.csv' and 'testset.csv'
I need to apply the naive Bayes algorithm with these files but I search for the algorithm and every example contains '1 CSV file and manually separated train and test set'. I already have 2 CSV file for the train and test set how can I apply a naive Bayes algorithm? I tried to use sklearn train_test_split without(test_...
[ "It sounds like you want to use the Naive Bayes algorithm to train a model on one CSV file and then test that model using another CSV file. If that's the case, you can use the pandas library to load the two CSV files into separate dataframes, and then use the sklearn library to train a Naive Bayes model using the f...
[ 0 ]
[]
[]
[ "naivebayes", "python" ]
stackoverflow_0074674912_naivebayes_python.txt
Q: Filter Pyspark Dataframe column based on whether it contains or does not contain substring I have a pyspark dataframe message_df with millions of rows that looks like this id message ab123 Hello my name is Chris cd345 The room should be 2301 ef567 Welcome! What is your name? gh873 That way please kj893 The c...
Filter Pyspark Dataframe column based on whether it contains or does not contain substring
I have a pyspark dataframe message_df with millions of rows that looks like this id message ab123 Hello my name is Chris cd345 The room should be 2301 ef567 Welcome! What is your name? gh873 That way please kj893 The current year is 2022 and two lists wanted_words = ['name','room'] unwanted_words = ...
[ "Split text into tokens/words and use arrays_overlap function to check if wanted or unwanted token is present:\ndf = df.filter(\n (\n F.arrays_overlap(\n F.split(F.regexp_replace(F.lower(\"message\"), r\"[^a-zA-Z0-9\\s]+\", \"\"), \"\\s+\"),\n F.array([F.lit(c) for c in wanted_words])\n ...
[ 0 ]
[]
[]
[ "dataframe", "pyspark", "python" ]
stackoverflow_0074668162_dataframe_pyspark_python.txt
Q: Python Write every Nth Filename from Folder to a Text File Hello I am trying to write every odd and then even filename from a Folder to a text file. import os TXT = "C:/Users/Admin/Documents/combine.txt" # Collects Files with open(TXT, "w") as a: for path, subdirs, files in os.walk(r'C:\Users\Admin\Desktop\c...
Python Write every Nth Filename from Folder to a Text File
Hello I am trying to write every odd and then even filename from a Folder to a text file. import os TXT = "C:/Users/Admin/Documents/combine.txt" # Collects Files with open(TXT, "w") as a: for path, subdirs, files in os.walk(r'C:\Users\Admin\Desktop\combine'): for filename in files: f = os.path.joi...
[ "As suggested by Mitchell van Zuylen, and Tomerikoo, you could use slicing and listdir to produce your desired output:\nCode:\nimport os\n\nN = 2 # every 2nd filename\n\ncombine_txt = \"C:\\Users\\Admin\\Documents\\combine.txt\"\nfolder_of_interest = 'C:\\Users\\Admin\\Desktop\\combine'\n\nfiles = sorted(os.listdi...
[ 0 ]
[]
[]
[ "filenames", "iteration", "python", "subdirectory" ]
stackoverflow_0074674464_filenames_iteration_python_subdirectory.txt
Q: increment the name of the variable, ex: prdt1, prdt2, prdt3 ...etc I didn't try anything because I don't even know where to start... the program would associate every item of the list to the variables like (name)1, (name)2, (name)3, and so on to the number of items the list has. prdt = ["WD40", "001", "oleo de car...
increment the name of the variable, ex: prdt1, prdt2, prdt3 ...etc
I didn't try anything because I don't even know where to start... the program would associate every item of the list to the variables like (name)1, (name)2, (name)3, and so on to the number of items the list has. prdt = ["WD40", "001", "oleo de carro, 1L", "liquidos", "seccao 1", 5, 30] prdt1 ="WD40" prdt2 ="001" prdt...
[ "Basically with python version above 3.8 you can use eval and walrus operator in order to achieve this behaviour. You will get variables with names corresponding to your list items\nfor idx, item in enumerate(prdt):\n eval(f\"({item}{idx}:={item})\")\n\nIf you look at this weird syntax in eval it's walrus operat...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074674932_python.txt
Q: invert 2 items in a list Python I'm building a Formula1 race simulator in python and I'm trying to make a overtake function, basically, i've all the drivers stored in a list and once one of the drivers surpasses the other I need to invert their position in the list ['hamilton','vertsappen','perez','sainz'] ['hamil...
invert 2 items in a list Python
I'm building a Formula1 race simulator in python and I'm trying to make a overtake function, basically, i've all the drivers stored in a list and once one of the drivers surpasses the other I need to invert their position in the list ['hamilton','vertsappen','perez','sainz'] ['hamilton','perez','verstappen','sainz'] i...
[ "A simple overtake function:\ndef overtake_driver(drivers, overtaker, overtaken):\n # Find the indices of the overtaker and the overtaken in the list of drivers\n overtaker_index = drivers.index(overtaker)\n overtaken_index = drivers.index(overtaken)\n\n # Swap the positions of the overtaker and the overtaken i...
[ 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074674950_python.txt
Q: Box-box collision detection with PyOpenGL and Pygame at 3d I'm writing a player class that, among other things, has mesh attributes (I use the py3d library and the mesh class from it) and collider (a class that I need to implement myself). The collider is a simple cube and should have a method to determine whether...
Box-box collision detection with PyOpenGL and Pygame at 3d
I'm writing a player class that, among other things, has mesh attributes (I use the py3d library and the mesh class from it) and collider (a class that I need to implement myself). The collider is a simple cube and should have a method to determine whether it collided with another collider-cube or not. I have a class t...
[ "One way to detect box-box collisions in 3D using PyOpenGL and Pygame is to use the Bullet physics engine. Bullet is a 3D physics engine that can be used to detect collisions, apply forces, and simulate the motion of rigid bodies. To use Bullet, you would need to implement the collider class as a Bullet body, and t...
[ 0 ]
[]
[]
[ "collision_detection", "pyopengl", "python" ]
stackoverflow_0074674884_collision_detection_pyopengl_python.txt
Q: I'm creating discord bot that plays audio but i got this eror "discord.ext.commands.errors.CommandNotFound: Command "join" is not found" I'm creating discord bot that plays audio but i got this eror "discord.ext.commands.errors.CommandNotFound: Command "join" is not found" here my code music.py import discord from...
I'm creating discord bot that plays audio but i got this eror "discord.ext.commands.errors.CommandNotFound: Command "join" is not found"
I'm creating discord bot that plays audio but i got this eror "discord.ext.commands.errors.CommandNotFound: Command "join" is not found" here my code music.py import discord from discord.ext import commands import youtube_dl class music(commands.Cog): def __init__(self, client): self.client = client @...
[ "As of discord.py 2, the add_cog method has become an async function, so you need to await it. And if you're using a cog from a other file, it is suggested to use load_extension to load it. For example:\ncogs/music.py\nclass Music(commands.Cog):\n ...\n\n# as of discord.py 2, this function needs to be an async f...
[ 0 ]
[]
[]
[ "discord", "discord.py", "python" ]
stackoverflow_0074674862_discord_discord.py_python.txt
Q: Sorting Nested Lists with Various Elements I have a nested list like: [["bla","blabla","x=17"],["bla","x=13","z=13","blabla"],["x=27","blabla","bla","y=24"]] I need to have this sorted by x (from least to most) as (other strings should stay where they are): [["bla","x=13","z=13","blabla"],["bla","blabla","x=17"],...
Sorting Nested Lists with Various Elements
I have a nested list like: [["bla","blabla","x=17"],["bla","x=13","z=13","blabla"],["x=27","blabla","bla","y=24"]] I need to have this sorted by x (from least to most) as (other strings should stay where they are): [["bla","x=13","z=13","blabla"],["bla","blabla","x=17"],["x=27","blabla","bla","y=24"]] and also from m...
[ "Given your list:\nsort_this_list = [\n [\"bla\",\"blabla\",\"x=17\"],\n [\"bla\",\"x=13\",\"z=13\",\"blabla\"],\n [\"x=27\",\"blabla\",\"bla\",\"y=24\"]\n]\n\nFirst, extract the x element from the respective list!\ndef get_x(list):\n # Iterate over the items in the given list\n for item in list:\n ...
[ 1, 0 ]
[]
[]
[ "list", "nested_lists", "python", "python_3.x", "sorting" ]
stackoverflow_0074674996_list_nested_lists_python_python_3.x_sorting.txt
Q: discord.py "sub help command" I was wondering if it's possible to make a somewhat "sub help command" basically if I were to do ;help mute it would show how to use the mute command and so on for each command. Kinda like dyno how you can do ?help (command name) and it shows you the usage of the command. I have my ow...
discord.py "sub help command"
I was wondering if it's possible to make a somewhat "sub help command" basically if I were to do ;help mute it would show how to use the mute command and so on for each command. Kinda like dyno how you can do ?help (command name) and it shows you the usage of the command. I have my own help command already finished but...
[ "There are several ways you can do this.\nWhen you're using slash commands (which you are currently not,) there is a really elegant way to do this in the form of SlashCommandGroups. This would get the commands as [command name] help instead, but I don't think that is a downside.\nThis would work like this, an examp...
[ 0 ]
[]
[]
[ "discord", "discord.py", "python" ]
stackoverflow_0074661669_discord_discord.py_python.txt
Q: Can't add title to mapbox map I tried to create several maps and saved as png files. In cycle I got all mapes per year. I want to add which year on the map, and I tried title=i and fig.update_layout(title_text=i, title_x=0.5), but it does not work. import plotly.express as px import pandas as pd year = [1980,1981,...
Can't add title to mapbox map
I tried to create several maps and saved as png files. In cycle I got all mapes per year. I want to add which year on the map, and I tried title=i and fig.update_layout(title_text=i, title_x=0.5), but it does not work. import plotly.express as px import pandas as pd year = [1980,1981,1983] lat = [60.572959, 60.321403,...
[ "Use the annotations attribute of the previously created layout object in the update_layout method to add text - specified by the x and y coordinates.\nfig.update_layout(annotations=[\n dict(text=i, x=0.5, y=0.5, font_size=15, showarrow=False)\n])\n\nPlay around with the x and y coordinates to find the proper po...
[ 1, 1 ]
[]
[]
[ "mapbox", "plotly", "python" ]
stackoverflow_0074674956_mapbox_plotly_python.txt
Q: Django url change language code I am trying to change the language of the website when users click a button in Django. I have a base project and the urls are: urlpatterns += i18n_patterns( # Ecommerce is the app where I want to change the language url(r'^', include("ecommerce.urls")), ) The url inside Eco...
Django url change language code
I am trying to change the language of the website when users click a button in Django. I have a base project and the urls are: urlpatterns += i18n_patterns( # Ecommerce is the app where I want to change the language url(r'^', include("ecommerce.urls")), ) The url inside Ecommerce.urls is: urlpatterns = [ u...
[ "Actually it's not going to be a simple <a> link but a <form>.\nHave a read on how to set_language redirect view. This form will be responsible for changing languages. It's easy as a pie.\nMake sure you have set some LANGUAGES first.\n", "You can change the language of the website when users click a link (no url ...
[ 4, 4, 0 ]
[]
[]
[ "django", "django_i18n", "python" ]
stackoverflow_0042745198_django_django_i18n_python.txt
Q: decoding a Byte Array sent from arduino to TCP Server made with Python I am converting sensor data to byte and writing a byte array from an arduino to a TCP server made with Python, but somehow the sensor data which are in the array triggers variations of the UTF-8 errors displayed below when decoded. UnicodeDecod...
decoding a Byte Array sent from arduino to TCP Server made with Python
I am converting sensor data to byte and writing a byte array from an arduino to a TCP server made with Python, but somehow the sensor data which are in the array triggers variations of the UTF-8 errors displayed below when decoded. UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start by...
[ "I was able to make some progress,\nfor Arduino:\n#include <Ethernet.h>\n#include <SPI.h>\n#include \"AK09918.h\"\n#include \"ICM20600.h\"\n#include <Wire.h>\n//----------------------------------\n\n//tiltsensor\nAK09918_err_type_t err;\nint32_t x, y, z;\nAK09918 ak09918;\nICM20600 icm20600(true);\nint16_t acc_x, a...
[ 0, 0 ]
[]
[]
[ "arduino", "python", "tcpclient", "utf_8" ]
stackoverflow_0074613294_arduino_python_tcpclient_utf_8.txt
Q: Zip or create key-value pairs from two lists of lists I have the following MWE: token_uniqueness_sparse = pd.DataFrame({'token_a': [0.1, 0.0], 'token_b': [0.0, 0.2], 'token_c': [0.3, 0.0] } ...
Zip or create key-value pairs from two lists of lists
I have the following MWE: token_uniqueness_sparse = pd.DataFrame({'token_a': [0.1, 0.0], 'token_b': [0.0, 0.2], 'token_c': [0.3, 0.0] } ) sf_fake = pd.DataFrame({'...
[ "Here is a one way:\nsf_fake=sf_fake.explode('items').set_index('items').T.reset_index(drop=True)\n'''\nitems token_a token_c token_b\n0 1 1 2\n'''\n#for example, token_a takes the value in index number 1 in token_uniqueness_sparse df\n\nfinal={i:token_uniqueness_sparse[i].iloc[sf_fake[i...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074670491_python.txt
Q: Exact value of a root on Python I'm writing a programme that converts complex numbers. Right now I'm having problems with this piece of code: import numpy complexnr = 1+1j mod= numpy.absolute(complexnr) print(mod) The output of this code is: 1.4142135623730951 I would like to get √2 as the output. I have been a...
Exact value of a root on Python
I'm writing a programme that converts complex numbers. Right now I'm having problems with this piece of code: import numpy complexnr = 1+1j mod= numpy.absolute(complexnr) print(mod) The output of this code is: 1.4142135623730951 I would like to get √2 as the output. I have been advised to use the sympy module but I ...
[ "Works by using\n\nI (from sympy) rather than 1j\nbuiltin abs function which calls sympby.Abs for complex arguments\n\nCode\nfrom sympy import I\n\ncomplexnr = 1 + I # use I rather than 1j\nprint(abs(complexnr)) # also works with np.abs and np.absolute\n\nOutput\n\n", "If you want to use SymPy, you have t...
[ 1, 0 ]
[]
[]
[ "numpy", "python", "sympy" ]
stackoverflow_0074674649_numpy_python_sympy.txt
Q: Python folium - Circle not working along with popup I found some nice solutions here: How to create on click popup which includes plots using ipyleaflet, Folium or Geemap? which potentially would allow me to assign more things to the marker when it's clicked. In my situation I have a lot of circles assigned to the...
Python folium - Circle not working along with popup
I found some nice solutions here: How to create on click popup which includes plots using ipyleaflet, Folium or Geemap? which potentially would allow me to assign more things to the marker when it's clicked. In my situation I have a lot of circles assigned to the marker, but they appear all which doesn't look well. I ...
[ "To create a marker on a folium map that displays a circle when clicked, you can use the following steps:\n\nFirst, create a marker on the map using the folium.Marker class and specify the location and any popup information you want to display when the marker is clicked.\n\nfm = folium.Marker(\n location=[lat, l...
[ 0, 0 ]
[]
[]
[ "folium", "leaflet", "python" ]
stackoverflow_0074520790_folium_leaflet_python.txt
Q: Left join in (flask)sqlalchemy with getting unmatched values and filter on the right table I want to get a list of all assignments, with the progress of the user (the UserAssignments table) also in the result set. That means there should be a join between the assignments and userassignments table (where the assign...
Left join in (flask)sqlalchemy with getting unmatched values and filter on the right table
I want to get a list of all assignments, with the progress of the user (the UserAssignments table) also in the result set. That means there should be a join between the assignments and userassignments table (where the assignmentid is equal), but also a filter to check if the progress is from the current user. The diagr...
[ "try next query\nresults = db.session.query(\n Assignment, \n UserAssignments,\n).join(\n UserAssignments, \n UserAssignments.assignmentid == Assignment.assignmentid, \n isouter=True,\n).filter(\n or_(\n UserAssignments.userid == userid,\n UserAssignments.userid.is_(None),\n )\n).all()\n\n" ...
[ 0 ]
[]
[]
[ "flask_sqlalchemy", "python", "sqlalchemy" ]
stackoverflow_0074675033_flask_sqlalchemy_python_sqlalchemy.txt
Q: Sum by Factors From Codewars.com Sinopsis: my code runs well with simple lists, but when I attempt, after the 4 basic test its execution time gets timed out. Since I don't want to look for others solution, I'm asking for help and someone can show me which part of the code its messing with the time execution in ord...
Sum by Factors From Codewars.com
Sinopsis: my code runs well with simple lists, but when I attempt, after the 4 basic test its execution time gets timed out. Since I don't want to look for others solution, I'm asking for help and someone can show me which part of the code its messing with the time execution in order to focus only into modify that part...
[ "One possible cause of timeouts in your code is the use of the sorted function with the reverse = True argument. This sorts the input list in reverse order, which can be inefficient for large lists.\nInstead of sorting the list in reverse order, you can use the built-in max function to find the maximum value in the...
[ 0 ]
[]
[]
[ "performance", "python", "time" ]
stackoverflow_0074675160_performance_python_time.txt
Q: Python Selenium with Salesforce - Cannot Seem to Access Certain Form Elements Using Selenium to try and automate a bit of data entry with Salesforce. I have gotten my script to load a webpage, allow me to login, and click an "edit" button. My next step is to enter data into a field. However, I keep getting an erro...
Python Selenium with Salesforce - Cannot Seem to Access Certain Form Elements
Using Selenium to try and automate a bit of data entry with Salesforce. I have gotten my script to load a webpage, allow me to login, and click an "edit" button. My next step is to enter data into a field. However, I keep getting an error about the field not being found. I've tried to identify it by XPATH, NAME, and ID...
[ "Salesforce's Lighting Experience (the new white-blue UI) is built with web components that hide their internal implementation details. You'd need to read up a bit about \"shadow DOM\", it's not a \"happy soup\" of html and JS all chucked into top page's html. Means that CSS is limited to that one component, there'...
[ 0 ]
[]
[]
[ "frames", "html", "python", "salesforce", "selenium" ]
stackoverflow_0074674569_frames_html_python_salesforce_selenium.txt
Q: ModuleNotFoundError: No module named 'translate' , even after "pip install translate" I am having this error, even after "pip install translate" multiple times. I am running my application in a docker container. I am a beginner , so please let me know, what mistake i am doing. ` Traceback (most recent call last): ...
ModuleNotFoundError: No module named 'translate' , even after "pip install translate"
I am having this error, even after "pip install translate" multiple times. I am running my application in a docker container. I am a beginner , so please let me know, what mistake i am doing. ` Traceback (most recent call last): File "/usr/lib/python3.10/multiprocessing/process.py", line 314, in _bootstrap self.r...
[ "You need not local pip install, but install in your docker.\nAdd to Dockerfile\npython3 -m pip install translate\n\nAnd rebuild your image\n" ]
[ 0 ]
[]
[]
[ "docker", "fastapi", "pip", "python", "uvicorn" ]
stackoverflow_0074674226_docker_fastapi_pip_python_uvicorn.txt
Q: Why getting this Error selenium.common.exceptions.StaleElementReferenceException: I know already upload answer to this same question but I try them they are not working for me because there is also some some update in selenium code too. selenium.common.exceptions.StaleElementReferenceException: Message: stale elem...
Why getting this Error selenium.common.exceptions.StaleElementReferenceException:
I know already upload answer to this same question but I try them they are not working for me because there is also some some update in selenium code too. selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document (Session info: chrome=108...
[ "By clicking '//input[contains(@aria-labelledby,\"tokenizer-label\")]' element it is re-built on the page (really strange approach they built that page).\nTo make this code working I added a delay after clearing and clicking that input and then get that element again.\nThe following code worked for me:\nimport time...
[ 1 ]
[]
[]
[ "python", "selenium", "selenium_webdriver", "staleelementreferenceexception", "xpath" ]
stackoverflow_0074675192_python_selenium_selenium_webdriver_staleelementreferenceexception_xpath.txt
Q: parse list containing html-like elements into nested json using Python I'm not the best at converting certain sections of a list to nested Json and was hoping for some guidance. I have a list containing data like below: ['<h5> 1|', '<h6>Type of Care|', '<h6>SA|Substance use treatment|', '<h6>DT|Detoxification |...
parse list containing html-like elements into nested json using Python
I'm not the best at converting certain sections of a list to nested Json and was hoping for some guidance. I have a list containing data like below: ['<h5> 1|', '<h6>Type of Care|', '<h6>SA|Substance use treatment|', '<h6>DT|Detoxification |', '<h6>HH|Transitional housing, halfway house, or sober home|', '<h6>SUMH...
[ "Considering your format remains constant. Here's a flexible solution that is configurable:\nclass Separator():\n def __init__(self, data, title, sep, splitter):\n self.data = data # the data\n self.title = title # the starting in your case \"<h5>\"\n self.sep = sep # the point where you wan...
[ 0 ]
[]
[]
[ "json", "python" ]
stackoverflow_0074661204_json_python.txt
Q: Transform and fill a dataframe depending on occurence of values within the dataframe I have a dataframe such as : Names1 Gene_name Status SP1 GENE1 0 SP1 GENE1 1 SP1 GENE1 1 SP1 GENE1 2 SP1 GENE1 2 SP1 GENE2 0 SP3 GENE2 0 SP1 GENE2 1 SP2 GENE2 2 SP4 ...
Transform and fill a dataframe depending on occurence of values within the dataframe
I have a dataframe such as : Names1 Gene_name Status SP1 GENE1 0 SP1 GENE1 1 SP1 GENE1 1 SP1 GENE1 2 SP1 GENE1 2 SP1 GENE2 0 SP3 GENE2 0 SP1 GENE2 1 SP2 GENE2 2 SP4 GENE3 1 SP4 GENE3 2 SP5 GENE3 0 SP5 GENE3 0 Then I would l...
[ "Code\ng = df.groupby(['Names1', 'Gene_name'])\ng['Status'].agg(lambda x: '-'.join(x.astype('str').sort_values().unique())).unstack()\n\noutput\nGene_name GENE1 GENE2 GENE3\nNames1 \nSP1 0-1-2 0-1 NaN\nSP2 NaN 2 NaN\nSP3 NaN 0 NaN\nSP4 NaN ...
[ 3, 1, 0 ]
[]
[]
[ "pandas", "python", "python_3.x" ]
stackoverflow_0074674654_pandas_python_python_3.x.txt
Q: limiting the number of decimal places in python pandas table I was trying to rewrite a CSV file using pandas module in python. I tried to multiply the first column (excluding the title) by 60 as below, f=001.csv Urbs_Data=pd.read_csv(f,header=None) Urbs_Data=Urbs_Data.replace("Time_hrs","Time_min") Urbs_Data.l...
limiting the number of decimal places in python pandas table
I was trying to rewrite a CSV file using pandas module in python. I tried to multiply the first column (excluding the title) by 60 as below, f=001.csv Urbs_Data=pd.read_csv(f,header=None) Urbs_Data=Urbs_Data.replace("Time_hrs","Time_min") Urbs_Data.loc[1:,0]=Urbs_Data.loc[1:,0].astype(float) Urbs_Data.loc[1:,0]*=6...
[ "The DataFrame round method should work...\nimport numpy as np\nimport pandas as pd \n\nsome_numbers = np.random.ranf(5)\n\ndf = pd.DataFrame({'random_numbers':some_numbers})\n\nrounded_df = df.round(decimals=2)\n\n", "import numpy as np\nimport pandas as pd \n\n#fileName\nf=001.csv\n\n#Load File to Df\nUrbs_Data...
[ 31, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0054509060_dataframe_pandas_python.txt
Q: How to implement a smooth clamp function in python? The clamp function is clamp(x, min, max) = min if x < min, max if x > max, else x I need a function that behaves like the clamp function, but is smooth (i.e. has a continuous derivative). A: What you are looking for is something like the Smoothstep function, ...
How to implement a smooth clamp function in python?
The clamp function is clamp(x, min, max) = min if x < min, max if x > max, else x I need a function that behaves like the clamp function, but is smooth (i.e. has a continuous derivative).
[ "What you are looking for is something like the Smoothstep function, which has a free parameter N, giving the \"smoothness\", i.e. how many derivatives should be continuous. It is defined as such:\n\nThis is used in several libraries and can be implemented in numpy as\nimport numpy as np\nfrom scipy.special import ...
[ 12, 10, 1 ]
[]
[]
[ "clamp", "numpy", "pandas", "python", "smoothstep" ]
stackoverflow_0045165452_clamp_numpy_pandas_python_smoothstep.txt