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: Looking for a better way to find the most occurring letter in every position in a list of strings I have a list like words = ["test", "secondTest", "thirdTest"] and I have a function to find for every position, the most occurring element through the list, e.g. the most occurring element in first position is 't', ...
Looking for a better way to find the most occurring letter in every position in a list of strings
I have a list like words = ["test", "secondTest", "thirdTest"] and I have a function to find for every position, the most occurring element through the list, e.g. the most occurring element in first position is 't', in second is 'e' and so on. The problem is that it takes very long time, especially for very long lists...
[ "One liner\n[collections.Counter(k for k in x if k).most_common(1)[0][0] for x in itertools.zip_longest(*words)]\n\nitertools.zip_longest is like zip, except that it works even with list of different sizes, returning None for list that are overs\nSo ((k for k in x if k) for x in itertools.zip_longest(*words)) itera...
[ 0 ]
[]
[]
[ "dictionary", "find_occurrences", "list", "python" ]
stackoverflow_0074407102_dictionary_find_occurrences_list_python.txt
Q: YT-DLP How do I extract the audio file? (Python, Discord.py) I am making a Discord music bot with Python, discord.py and yt-dl. Currently I am trying to switch from yt-dl to yt-dlp because of downloading and age restriction issues. With yt-dl, I used to extract an audio files from the playlist this way: with Youtu...
YT-DLP How do I extract the audio file? (Python, Discord.py)
I am making a Discord music bot with Python, discord.py and yt-dl. Currently I am trying to switch from yt-dl to yt-dlp because of downloading and age restriction issues. With yt-dl, I used to extract an audio files from the playlist this way: with YoutubeDL(YDL_OPTIONS) as ydl: info = ydl.extract_info(link, downlo...
[ "yt-dlp has support for storyboards, which are unavailable in youtube-dl. The code takes the first item in the list of all available formats, which is the lowest quality format, as sorted by youtube-dl/yt-dlp. In youtube-dl, on YouTube videos, this is the lowest quality audio-only format. However, in yt-dlp, there ...
[ 0 ]
[]
[]
[ "discord.py", "python", "youtube_dl", "yt_dlp" ]
stackoverflow_0074262376_discord.py_python_youtube_dl_yt_dlp.txt
Q: To recognition the face I am write the code to recognition the face and mark attendence but so Error come and when i run the project the camere are open but not recogition the face the give face are stick on the camera screen. and the following error is are has follw: File "g:\Attendence System\face_recognition.py...
To recognition the face
I am write the code to recognition the face and mark attendence but so Error come and when i run the project the camere are open but not recogition the face the give face are stick on the camera screen. and the following error is are has follw: File "g:\Attendence System\face_recognition.py", line 93, in face_recog ...
[ "I guess your issue definitely is not a face recognition one:\nname=my_courser.fetchone()\nname=\"+\".join(name)\n\nYour error means that name is not iterable as it shoud be if my_courser.fetchone() returns something but None.\nYou may try:\nname=my_courser.fetchone()\nif name:\n name=\"+\".join(name)\n\nAnd do ...
[ 0 ]
[]
[]
[ "face_recognition", "pylance", "python" ]
stackoverflow_0074343177_face_recognition_pylance_python.txt
Q: Django: Retrieve a list of one model property for all distinct values of another property I’d like to use the Django ORM to give me a list values of a model property for the subset of objects that have a distinct value of another property. Consider a simple model like: class Result(models.Model): color = model...
Django: Retrieve a list of one model property for all distinct values of another property
I’d like to use the Django ORM to give me a list values of a model property for the subset of objects that have a distinct value of another property. Consider a simple model like: class Result(models.Model): color = models.CharField() score = models.IntegerField() And imagine that I have four results: results ...
[ "Unfortunatly, this will depend on you DB.\nIf you're using Postgresql you have access to ArrayAgg,\nso the following will work :\nresults.values(\"color\").annotate(scores=ArrayAgg(\"score\"))\n\nYou're using MySQL or MariaDB you can use GroupConcat.\nBut this won't yield an array, it will yield a string with valu...
[ 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0074407183_django_django_models_python.txt
Q: Find a string in a pdf file using python I want to search through a pdf file and find the page that contains a specific phrase. What I have so far is: object = PyPDF2.PdfFileReader("20220625.pdf") numpages = object.getNumPages() string = "SYSTEM WIDE OUTLET SUMMARY" for i in range(0, numpages): page = object.g...
Find a string in a pdf file using python
I want to search through a pdf file and find the page that contains a specific phrase. What I have so far is: object = PyPDF2.PdfFileReader("20220625.pdf") numpages = object.getNumPages() string = "SYSTEM WIDE OUTLET SUMMARY" for i in range(0, numpages): page = object.getPage(i) text = page.extractText() if...
[ "Take a look at this page describing the str.find method, which you are using in text.find(string). The find method returns the index of the first occurrence of the specified value unless it cannot find that value in which case it returns -1. So the statement text.find(string) returns -1 when it cannot find the str...
[ 3, 0 ]
[]
[]
[ "pdf", "python", "string" ]
stackoverflow_0074407172_pdf_python_string.txt
Q: How to use broadcast feature of numpy on a pandas dataframe with list columns of different lengths I am trying to use broadcast feature of numpy on my large data. I have list columns that can have hundreds of elements in many rows. I need to filter rows based on presence of columns value in the list column. If num...
How to use broadcast feature of numpy on a pandas dataframe with list columns of different lengths
I am trying to use broadcast feature of numpy on my large data. I have list columns that can have hundreds of elements in many rows. I need to filter rows based on presence of columns value in the list column. If number in col_a is present in col_b, I need to filter IN that row. Sample data: import pandas as pd import ...
[ "import pandas as pd\nimport numpy as np\nfrom itertools import product\n\nParse out columns based on the commas:\ndt2 = pd.DataFrame([j for i in dt.values for j in product(*i)], columns=dt.columns)\n\nFilter to where col_a equals col_b:\ndt2 = dt2[dt2['col_a'] == dt2['col_b']]\n\nResults in:\n\n", "I think you'v...
[ 2, 1 ]
[]
[]
[ "numpy", "pandas", "python" ]
stackoverflow_0074406353_numpy_pandas_python.txt
Q: Python-Train multiple files in one epoch I have a very large data images file that I divided it into smaller files and store them as pickles. Now, I need to use them to train a model for multiple epochs (10, 50, or 100)? I, first, read them before the training part, pickle_in1 = open(path + "TrainPairs1.pickle", "...
Python-Train multiple files in one epoch
I have a very large data images file that I divided it into smaller files and store them as pickles. Now, I need to use them to train a model for multiple epochs (10, 50, or 100)? I, first, read them before the training part, pickle_in1 = open(path + "TrainPairs1.pickle", "rb") trainPixel1 = pickle.load(pickle_in1) tra...
[ "\nchange the batch size ( 16 -> increase it gradually (32, 64 , 128)\nuse context managers, every time you load\n\nwith open(path + \"TrainPairs1.pickle\", \"rb\") as pickle_in1 :\n trainPixel1 = pickle.load(pickle_in1)\n\n\nif it still doesn't work , try to change the size of images before loading as np array\n...
[ 0 ]
[]
[]
[ "pickle", "python", "tensorflow" ]
stackoverflow_0074407139_pickle_python_tensorflow.txt
Q: Efficiently build a string from characters most frequent at i-th index of all the strings in a list I need to define a function that, given a list of strings, returns a string composed by the characters that are most frequent at the i-th position of every string. If multiple characters appear at the maximum freque...
Efficiently build a string from characters most frequent at i-th index of all the strings in a list
I need to define a function that, given a list of strings, returns a string composed by the characters that are most frequent at the i-th position of every string. If multiple characters appear at the maximum frequency, the one which comes first alphabetically is chosen. External libraries are not allowed. Example: ['h...
[ "Sorting is O(n*log(n)). You can modify your code to run in linear time by computing the counts during iteration and using min on the negative of the counts to get the smallest order in lexicographic order:\ndef f(words: list) -> str:\n chars = {}\n for word in words:\n for i, char in enumerate(word):\...
[ 1, 0 ]
[]
[]
[ "optimization", "python" ]
stackoverflow_0074406982_optimization_python.txt
Q: Logging out on django web app redirects to django admin logout page. What's going on? I'm following a tutorial in the Python Crash Course book on creating a simple web page using Django. I've just created an app to log a user in and out on my page, using Django's default user authentication system. When I logout, ...
Logging out on django web app redirects to django admin logout page. What's going on?
I'm following a tutorial in the Python Crash Course book on creating a simple web page using Django. I've just created an app to log a user in and out on my page, using Django's default user authentication system. When I logout, Django is not redirecting to the template I've created to show that the user is logged out....
[ "in settings.py you can sett logout redirect url\nGive this a try\nLOGOUT_REDIRECT_URL = '/path_to_the_page'\nLOGIN_URL = '/path_to_the_page'\n\n", "in your settings you can do that easily how suppose you have function based view\ndef hello(request):\n return render (request, 'logout_redirect.html')\nand in ur...
[ 3, 0, 0, 0 ]
[]
[]
[ "django", "html", "python" ]
stackoverflow_0069008290_django_html_python.txt
Q: How to stop the execution of an imported python script without exiting the python altogether? In the example below, when I run y_file.py, I need 5 printed and Hello not printed. How to stop the execution of an imported python script x_file.py without exiting the python altogether? sys.exit() seems to exit python a...
How to stop the execution of an imported python script without exiting the python altogether?
In the example below, when I run y_file.py, I need 5 printed and Hello not printed. How to stop the execution of an imported python script x_file.py without exiting the python altogether? sys.exit() seems to exit python altogether. x_file.py import sys x = 5 if __name__ != '__main__': pass # stop executing x.py, bu...
[ "As jvx8ss suggested, you can fix this by putting the print inside a if __name__ == \"__main__\": conditional. Note the equality \"==\" instead of inequality \"!=\".\nFinal code:\nimport sys\nx = 5\nif __name__ == \"__main__\":\n # stop executing x.py, but do not exit python\n # sys.exit() # this line exits p...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074407002_python.txt
Q: How to add play again option for a hangman in python? I have done these steps of the hangman: Write a function hangman() which allows you to play hangman and returns the word ‘victory’ or ‘defeat’ depending on the result. In this function: randomly draw a word then called mystery_word define word_found as a list ...
How to add play again option for a hangman in python?
I have done these steps of the hangman: Write a function hangman() which allows you to play hangman and returns the word ‘victory’ or ‘defeat’ depending on the result. In this function: randomly draw a word then called mystery_word define word_found as a list of characters (and not as a character string) of the length...
[ "so you are able to make a while loop just after the end.\n# Your code here\nwhile True:\n hangman()\n\nFurther if you want to keep track of wins and losses, make 2 variables, win and loss with each time if you won inside the while loop do win++ or loss++ to add 1 to their value. You are also able to print them i...
[ 0 ]
[]
[]
[ "function", "python" ]
stackoverflow_0074407266_function_python.txt
Q: how to remove a column in dataframe if the specified column values are NaN This is my dataframe. I need to delete the row with all the values in d1,d2,d3,c1,c2,c3 are Nan. no d1 d2 d3 c1 c2 c3 0 59890 28.4 32.2 31.3 40.7 40.0 39.6 1 55679 NaN 32.8 31....
how to remove a column in dataframe if the specified column values are NaN
This is my dataframe. I need to delete the row with all the values in d1,d2,d3,c1,c2,c3 are Nan. no d1 d2 d3 c1 c2 c3 0 59890 28.4 32.2 31.3 40.7 40.0 39.6 1 55679 NaN 32.8 31.5 37.3 39.2 39.4 2 58900 NaN NaN NaN NaN NaN Na...
[ "You can use dropna() parameters:\ndf = df.dropna(subset=['d1','d2','d3','c1','c2','c3'], how='all')\n\nAlternatively, if it's the first column you don't want to include:\ndf = df.dropna(subset=df.columns[1:], how='all')\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "nan", "pandas", "python" ]
stackoverflow_0074407349_dataframe_nan_pandas_python.txt
Q: Cannot import name 'get_cloud_client' from 'gretel_client' I keep getting the error Cannot import name 'get_cloud_client' from 'gretel_client' when I import using from gretel_client import get_cloud_client client = get_cloud_client(prefix="api", api_key="prompt") client.install_packages() I have followed all do...
Cannot import name 'get_cloud_client' from 'gretel_client'
I keep getting the error Cannot import name 'get_cloud_client' from 'gretel_client' when I import using from gretel_client import get_cloud_client client = get_cloud_client(prefix="api", api_key="prompt") client.install_packages() I have followed all documentation and tutorials which say to just install using !pip i...
[ "It seems like this is the older way of using gretel_client.\nYou have two options, either to install and use an older version of the library:\npip install gretel-client==0.7.13\nOr learn how to use the latest version of the library, the docs might be helpful:\nhttps://python.docs.gretel.ai/en/latest/index.html\n" ...
[ 0 ]
[]
[]
[ "importerror", "python", "syntax_error" ]
stackoverflow_0074407190_importerror_python_syntax_error.txt
Q: ModuleNotFoundError when trying to install and import the aux library I wanyt to do the feature extraction of the images and as part of it want to use the aux library. I have pip installed the aux library and getting an error. I am trying to find a solution for the following error. WARNING: Discarding https://file...
ModuleNotFoundError when trying to install and import the aux library
I wanyt to do the feature extraction of the images and as part of it want to use the aux library. I have pip installed the aux library and getting an error. I am trying to find a solution for the following error. WARNING: Discarding https://files.pythonhosted.org/packages/0e/d8/1ca6b67fee40d3fba147853cdce37bae241a0f0b6...
[ "You must put no spaces between the package name, the ==, and the version.\npip install aux==0.0.2\n\n" ]
[ 0 ]
[]
[]
[ "pip", "python" ]
stackoverflow_0074402408_pip_python.txt
Q: Everytime i try to install Django using "pip install django" on my command prompt why does this come up? pip install Django 'pip' is not recognized as an internal or external command, operable program or batch file. A: Well, this is an error you'll have to face multiple times in the future. It's pretty self-expl...
Everytime i try to install Django using "pip install django" on my command prompt why does this come up?
pip install Django 'pip' is not recognized as an internal or external command, operable program or batch file.
[ "Well, this is an error you'll have to face multiple times in the future. It's pretty self-explanatory. It means that 'pip' does not exist in your system. To fix this either: 1. Reinstall python (using the installer) and make sure that you've checked the 'pip' checkbox OR 2. Download 'pip.exe' manually and then add...
[ 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074407242_django_python.txt
Q: Click button but multiple classes I can click the "AKZEPTIEREN" button using XPATH like this: WebDriverWait(driver, 15).until(expected_conditions.element_to_be_clickable((By.XPATH, '/html/body/div[4]/div/button[2]'))).click() To make it more dynamic I want to use a class, so this would be: WebDriverWait(driver, 1...
Click button but multiple classes
I can click the "AKZEPTIEREN" button using XPATH like this: WebDriverWait(driver, 15).until(expected_conditions.element_to_be_clickable((By.XPATH, '/html/body/div[4]/div/button[2]'))).click() To make it more dynamic I want to use a class, so this would be: WebDriverWait(driver, 15).until(expected_conditions.element_to...
[ "You can try the below code using xpath expression that will select a single element and click on it because click() method requires a single selection:\nWebDriverWait(driver, 15).until(expected_conditions.element_to_be_clickable((By.XPATH, '//*[@class=\"primary accept no-pop-execute\" and contains(., \"Akzeptiere...
[ 1 ]
[]
[]
[ "python", "selenium" ]
stackoverflow_0074407355_python_selenium.txt
Q: How can I mock requests and the response? I am trying to use Pythons mock package to mock Pythons requests module. What are the basic calls to get me working in below scenario? In my views.py, I have a function that makes variety of requests.get() calls with different response each time def myview(request): res1...
How can I mock requests and the response?
I am trying to use Pythons mock package to mock Pythons requests module. What are the basic calls to get me working in below scenario? In my views.py, I have a function that makes variety of requests.get() calls with different response each time def myview(request): res1 = requests.get('aurl') res2 = request.get('b...
[ "This is how you can do it (you can run this file as-is):\nimport requests\nimport unittest\nfrom unittest import mock\n\n# This is the class we want to test\nclass MyGreatClass:\n def fetch_json(self, url):\n response = requests.get(url)\n return response.json()\n\n# This method will be used by th...
[ 418, 246, 72, 47, 32, 30, 8, 7, 5, 4, 3, 2, 2, 2, 1, 1, 0, 0, 0, 0 ]
[]
[]
[ "mocking", "python", "request" ]
stackoverflow_0015753390_mocking_python_request.txt
Q: Changing datetime format ready for sql database in pandas I have this datetime format 2016-01-31T20:13:48.000+02:00 as an object in pandas. What would be the best way for changing it, for transfering to sql database. For sql, iam using mysql. I need to store all this format, including time zone. A: Up to you how...
Changing datetime format ready for sql database in pandas
I have this datetime format 2016-01-31T20:13:48.000+02:00 as an object in pandas. What would be the best way for changing it, for transfering to sql database. For sql, iam using mysql. I need to store all this format, including time zone.
[ "Up to you how to store this into a SQL database, answering your main question though, here's how you could convert this into a datetime class type.\nimport pandas as pd\nfrom datetime import datetime\n\n\ndef convert_to_datetime(input):\n # function that reformats input string to datetime type\n return datet...
[ 1 ]
[]
[]
[ "datetime", "pandas", "python", "sql" ]
stackoverflow_0074406476_datetime_pandas_python_sql.txt
Q: multikey value sorting in dictionary in python a=[{"name":"sri",rank":5},{"name":"harish","rank":1},{"name":"adhya",rank":5},{"name":"mathi","rank":"NUL"}] print(sorted(a,key=lambda i: (i['rank'], i['name'])) ) TypeError: '<' not supported between instances of 'str' and 'int' want ouptput like: a=[{"name":"hari...
multikey value sorting in dictionary in python
a=[{"name":"sri",rank":5},{"name":"harish","rank":1},{"name":"adhya",rank":5},{"name":"mathi","rank":"NUL"}] print(sorted(a,key=lambda i: (i['rank'], i['name'])) ) TypeError: '<' not supported between instances of 'str' and 'int' want ouptput like: a=[{"name":"harish","rank":1},{"name":"adhya",rank":5},{"name":"sri...
[ "Cast i['rank'] to str():\nprint(sorted(a, key=lambda i: (str(i['rank']), i['name'])))\n\n# [{'name': 'harish', 'rank': 1}, {'name': 'adhya', 'rank': 5}, {'name': 'sri', 'rank': 5}, {'name': 'mathi', 'rank': 'NUL'}]\n\n" ]
[ 0 ]
[]
[]
[ "multikey", "python" ]
stackoverflow_0074405654_multikey_python.txt
Q: How to concatenate columns in a Dataframe based on the date? In a data frame similar to the one below how can I create the Concatenation column based on the date of each activity? Activity A Activity B Activity C Concatenation 1/1/2022 1/15/2022 2/3/2022 Activity A --> Activity B --> Activity C 1/15/2022 2/3/20...
How to concatenate columns in a Dataframe based on the date?
In a data frame similar to the one below how can I create the Concatenation column based on the date of each activity? Activity A Activity B Activity C Concatenation 1/1/2022 1/15/2022 2/3/2022 Activity A --> Activity B --> Activity C 1/15/2022 2/3/2022 1/1/2022 Activity C --> Activity A --> Activity B
[ "You can use numpy's argsort:\ndf2 = df.filter(like='Activity').apply(pd.to_datetime, dayfirst=False)\n\ndf['Concatenation'] = list(map(' -> '.join, df2.columns.to_numpy()[np.argsort(df2.to_numpy())]))\n\nOr with pandas only (less efficient):\ndf['Concatenation'] = (df\n .filter(like='Activity')\n .apply(pd.to_date...
[ 1, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074405291_dataframe_pandas_python.txt
Q: Download csv file which has javascript on-click download with requests I'm trying to download a csv file from here: Link after clicking on "Acesse todos os negócios realizados até o momento", which is in blue next to an image of a cloud with an arrow. I do know how to solve the problem with selenium, but it's such...
Download csv file which has javascript on-click download with requests
I'm trying to download a csv file from here: Link after clicking on "Acesse todos os negócios realizados até o momento", which is in blue next to an image of a cloud with an arrow. I do know how to solve the problem with selenium, but it's such a heavy library that I'd like to learn another solutions (specially faster ...
[ "Try to decode the base64-encoded response from the server:\nimport base64\nimport requests\n\nurl = \"https://bvmf.bmfbovespa.com.br/NegociosRealizados/Registro/DownloadArquivoDiretorio?data=\"\n\nt = base64.b64decode(requests.get(url).text)\nprint(t.decode(\"utf-8\"))\n\nPrints:\nData/Hora da ultima atualizacao: ...
[ 0 ]
[]
[]
[ "ajax", "python", "python_requests" ]
stackoverflow_0074407406_ajax_python_python_requests.txt
Q: Normalizing a color map for plotting a Confusion Matrix with ConfusionMatrixDisplay from Sklearn I am trying to create a color map for my 10x10 confusion matrix that is provided by sklearn. I would like to be able to customize the color map to be normalized between [0,1] but I have had no success. I am trying to u...
Normalizing a color map for plotting a Confusion Matrix with ConfusionMatrixDisplay from Sklearn
I am trying to create a color map for my 10x10 confusion matrix that is provided by sklearn. I would like to be able to customize the color map to be normalized between [0,1] but I have had no success. I am trying to use ax_ and matplotlib.colors.Normalize but am struggling to get something to work since ConfusionMatri...
[ "Let's try imshow and annotate manually:\naccuracies = conf_mat/conf_mat.sum(1)\nfig, ax = plt.subplots(figsize=(10,8))\ncb = ax.imshow(accuracies, cmap='Greens')\nplt.xticks(range(len(classes)), classes,rotation=90)\nplt.yticks(range(len(classes)), classes)\n\nfor i in range(len(classes)):\n for j in range(len(...
[ 1, 0 ]
[]
[]
[ "colormap", "matplotlib", "python", "scikit_learn" ]
stackoverflow_0064559225_colormap_matplotlib_python_scikit_learn.txt
Q: How to preserve column order after applying sklearn.compose.ColumnTransformer on numpy array I want to use Pipeline and ColumnTransformer modules from sklearn library to apply scaling on numpy array. Scaler is applied on some of the columns. And, I want to have the output with same column order of input. Example: ...
How to preserve column order after applying sklearn.compose.ColumnTransformer on numpy array
I want to use Pipeline and ColumnTransformer modules from sklearn library to apply scaling on numpy array. Scaler is applied on some of the columns. And, I want to have the output with same column order of input. Example: import numpy as np from sklearn.compose import ColumnTransformer from sklearn.preprocessing impor...
[ "Here is a solution by adding a transformer which will apply the inverse column permutation after the column transform:\nfrom sklearn.base import BaseEstimator, TransformerMixin\nimport re\n\n\nclass ReorderColumnTransformer(BaseEstimator, TransformerMixin):\n index_pattern = re.compile(r'\\d+$')\n \n def ...
[ 1, 0 ]
[]
[]
[ "numpy_ndarray", "python", "scaling", "scikit_learn", "transformer_model" ]
stackoverflow_0072572232_numpy_ndarray_python_scaling_scikit_learn_transformer_model.txt
Q: Constantly getting TabError: inconsistent use of tabs and spaces in indentation I'm getting these TabErrors constantly and it's really slowing down my work flow. I can't figure out how to make them go away. I get them to disappear by completely retyping my script, and then I add a new function and suddenly every...
Constantly getting TabError: inconsistent use of tabs and spaces in indentation
I'm getting these TabErrors constantly and it's really slowing down my work flow. I can't figure out how to make them go away. I get them to disappear by completely retyping my script, and then I add a new function and suddenly everything is messed up again. I have not changed the way I indent my code. I am not add...
[ "Add this to your settings.json file\n\"[python]\": {\n \"editor.insertSpaces\": true, // if you want to use spaces, false for tabs\n \"editor.tabSize\": 4,\n} // you may need a trailing comma here - you've been warned!\n\n" ]
[ 2 ]
[]
[]
[ "python", "visual_studio_code" ]
stackoverflow_0074407416_python_visual_studio_code.txt
Q: Questions regarding transactions on psycopg2 If I have a transaction that saves data in the database, but this transaction is part of another transaction that needs the id(fk) of that data to create a new data, but an error occurs at that moment, all transactions are rolled back or just the last transaction? A: ...
Questions regarding transactions on psycopg2
If I have a transaction that saves data in the database, but this transaction is part of another transaction that needs the id(fk) of that data to create a new data, but an error occurs at that moment, all transactions are rolled back or just the last transaction?
[ "They will both rollback unless you set up savepoints. A transaction \"within transaction\" is actually the same transaction. A plain ROLLBACK will revert everything, even if there are savepoints set up. A ROLLBACK TO savepoint will only undo operations that occured from that point onwards, keeping everything that ...
[ 1 ]
[]
[]
[ "postgresql", "psycopg2", "python", "transactions" ]
stackoverflow_0074406606_postgresql_psycopg2_python_transactions.txt
Q: unzip nested dictionary in function to calculate dictionary values I have different nested dictionaries, want to calculate discount wise score A = {'tr_1': {'hos': 100.0, 'dy': 100.0}, 'tr_2': {'hos': 100.0, 'dy': 50.0}, 'tr_3': {'hos': 100.0, 'dy': 50.0}} B = {'tr_1': {'cor': 160, 'ner': 0}, 'tr_2': {'cor': 6...
unzip nested dictionary in function to calculate dictionary values
I have different nested dictionaries, want to calculate discount wise score A = {'tr_1': {'hos': 100.0, 'dy': 100.0}, 'tr_2': {'hos': 100.0, 'dy': 50.0}, 'tr_3': {'hos': 100.0, 'dy': 50.0}} B = {'tr_1': {'cor': 160, 'ner': 0}, 'tr_2': {'cor': 69, 'ner': 36.14}, 'tr_3': {'cor': 63, 'ner': 41.69}} c = {'tr_1': {'st...
[ "IIUC, you can try:\nimport math\n\ndicts = [A, B, C]\nkeys = ['dy', 'ner', 'st_c']\n\nout = {k: {'eff': round(0.2*math.prod(d[k][k2] for k2,d in zip(keys, dicts)), 2)}\n for k in A}\n\nprint(out)\n\nOutput:\n{'tr_1': {'eff': 9.0},\n 'tr_2': {'eff': 54.0},\n 'tr_3': {'eff': 44.8}}\n\nUsed input:\nA = {'tr_1':...
[ 1 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0074407279_dictionary_python.txt
Q: How can I get more than 20 youtube search results using urllib? I am trying to make a python script that fetches youtube channel URLs with a keyword input. I'm using urlib to request the html of the search result page and then filtering out the channel IDs using RE. I can't seem to find a way to get the script to ...
How can I get more than 20 youtube search results using urllib?
I am trying to make a python script that fetches youtube channel URLs with a keyword input. I'm using urlib to request the html of the search result page and then filtering out the channel IDs using RE. I can't seem to find a way to get the script to fetch more than 20 results. Can anyone help me out here? Here's the c...
[ "For more results you need to implement in some way pagination, as you are working with the YouTube UI, as I did in my open-source API.\nNote that you are anyway limited to 500 results, if you use YouTube Data API v3 Search: list endpoint or the YouTube UI.\n" ]
[ 1 ]
[]
[]
[ "python", "urllib", "web_scraping", "youtube", "youtube_data_api" ]
stackoverflow_0074406773_python_urllib_web_scraping_youtube_youtube_data_api.txt
Q: Double 2d array in Numpy I am trying to recreate the attached array in numpy two different ways: using operator broadcasting and for loops. For some reason I am struggling with both ways to recreate the array, any ideas? I have tried iterating with a list and other just operator (np.square()), but the 2D is trick...
Double 2d array in Numpy
I am trying to recreate the attached array in numpy two different ways: using operator broadcasting and for loops. For some reason I am struggling with both ways to recreate the array, any ideas? I have tried iterating with a list and other just operator (np.square()), but the 2D is tricking me up. Any help would be a...
[ "With a for loop:\nimport numpy\n\narray = numpy.zeros((6,6), dtype=int)\nfor i in range(6):\n for j in range(6):\n array[i,j] = (6-i)*(j+1)\n\n" ]
[ 0 ]
[]
[]
[ "arrays", "numpy", "python", "python_3.x", "square" ]
stackoverflow_0074406305_arrays_numpy_python_python_3.x_square.txt
Q: File "", line 1 syntax error python on linux I'm trying to install an astro programm, PAHFits, the problem is that when I run it in the pyhton shell, it appears File "", line 1, as in the image I know it's not a problem with PAHFit but I don't know how to solve it! Help :( I tried to install from the bash and sti...
File "", line 1 syntax error python on linux
I'm trying to install an astro programm, PAHFits, the problem is that when I run it in the pyhton shell, it appears File "", line 1, as in the image I know it's not a problem with PAHFit but I don't know how to solve it! Help :( I tried to install from the bash and still have problems
[]
[]
[ "You can install libraries either like this:\npip install git+https://github.com/gretelai/gretel-python-client@main\nor like this:\npython -m pip install git+https://github.com/gretelai/gretel-python-client@main\n" ]
[ -1 ]
[ "astropy", "python" ]
stackoverflow_0074407550_astropy_python.txt
Q: Problems with pip install numpy - RuntimeError: Broken toolchain: cannot link a simple C program I'm trying to install numpy (and scipy and matplotlib) into a virturalenv. I keep getting these errors though: RuntimeError: Broken toolchain: cannot link a simple C program ---------------------------------------- Cl...
Problems with pip install numpy - RuntimeError: Broken toolchain: cannot link a simple C program
I'm trying to install numpy (and scipy and matplotlib) into a virturalenv. I keep getting these errors though: RuntimeError: Broken toolchain: cannot link a simple C program ---------------------------------------- Cleaning up... Command python setup.py egg_info failed with error code 1 I have the command line tools ...
[ "For Docker (Alpine) and Python 3.x this worked for me:\nRUN apk update\nRUN apk add make automake gcc g++ subversion python3-dev\n\n", "While it's ugly, it appears to work\nsudo ARCHFLAGS=-Wno-error=unused-command-line-argument-hard-error-in-future pip install --upgrade numpy\n\nNote that if you are getting this...
[ 150, 84, 17, 9, 7, 5, 5, 5, 4, 3, 0, 0, 0 ]
[ "Old thread, by my problem was that I didn't have Xcode installed. The following solved it.\nxcode-select --install\n\n" ]
[ -1 ]
[ "numpy", "pip", "python", "virtualenv" ]
stackoverflow_0022388519_numpy_pip_python_virtualenv.txt
Q: How to get vertices of rotated rectangle? I try smth like this: def main_rec(): width = random.randint(150, 250) height = random.randint(150, 250) angle = rand_angle() c, s = np.cos(angle), np.sin(angle) R = np.array(((c, -s), (s, c))) center = (random.randint(0, 640), random.randint(0, 48...
How to get vertices of rotated rectangle?
I try smth like this: def main_rec(): width = random.randint(150, 250) height = random.randint(150, 250) angle = rand_angle() c, s = np.cos(angle), np.sin(angle) R = np.array(((c, -s), (s, c))) center = (random.randint(0, 640), random.randint(0, 480)) x1y10 = (center[0] - width / 2, center[...
[ "using numpy and rotation matrix code would be:\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef create_rect(width,height,center):\n x,y = center\n w,h = width,height\n return np.array([[x-w/2,y-h/2],\n [x+w/2,y-h/2],\n [x+w/2,y+h/2],\n ...
[ 0 ]
[]
[]
[ "numpy", "python", "python_imaging_library" ]
stackoverflow_0074407514_numpy_python_python_imaging_library.txt
Q: I'm facing issues in sql fetch data in django ? It returns None This is test.py from django.http import HttpResponse import mysql.connector MySQLdb = mysql.connector host = 'xxxxxx' username = 'xxxx' db = 'xxxx' port = '3306' password = 'xxxxxx' class sql: def __int__(self): pass def mysql_conn...
I'm facing issues in sql fetch data in django ? It returns None
This is test.py from django.http import HttpResponse import mysql.connector MySQLdb = mysql.connector host = 'xxxxxx' username = 'xxxx' db = 'xxxx' port = '3306' password = 'xxxxxx' class sql: def __int__(self): pass def mysql_connection(self): try: mysql_conn = mysql.connector...
[ "Use form.cleaned_data[\"git_Id\"] after calling form.is_valid() so:\ndef index(request):\n if request.method == \"POST\":\n form = InputForm(request.POST)\n\n if form.is_valid():\n obj = sql()\n # git_id = 5666\n ids = form.cleaned_data[\"git_Id\"]\n print(i...
[ 1 ]
[]
[]
[ "django", "django_forms", "django_models", "django_views", "python" ]
stackoverflow_0074407257_django_django_forms_django_models_django_views_python.txt
Q: Creating a column with random values between 5 distinct floats or strings Good morning I need to create two dataframe columns. First one shall have random values that are either 0,05 0.10, 0.15 0.20 or 0.25. I have tried using: np.random.uniform but this returns me unwanted values such as 0.07 or 0.12. I also hav...
Creating a column with random values between 5 distinct floats or strings
Good morning I need to create two dataframe columns. First one shall have random values that are either 0,05 0.10, 0.15 0.20 or 0.25. I have tried using: np.random.uniform but this returns me unwanted values such as 0.07 or 0.12. I also have another column for which I want to do the same("Assigning random values") but...
[ "You can use numpy.random.choice:\nn = 20\n\ndf = pd.DataFrame({'Hg': np.random.choice([0.05, 0.10, 0.15, 0.20, 0.25], size=n),\n 'Outcome': np.random.choice(['Positive', 'Negative'], size=n)\n })\n\nprint(df)\n\nExample output:\n Hg Outcome\n0 0.25 Negative\n1 0.20 ...
[ 3 ]
[]
[]
[ "numpy", "pandas", "python" ]
stackoverflow_0074406245_numpy_pandas_python.txt
Q: Python: How to execute only one async function call when the function is called multiple times in a short timeframe? Context: I'm currently coding a bot on Discord. The bot has a server class within it (with none of the fancy websockets and http requests) and a client class that serves as a bridge between the user...
Python: How to execute only one async function call when the function is called multiple times in a short timeframe?
Context: I'm currently coding a bot on Discord. The bot has a server class within it (with none of the fancy websockets and http requests) and a client class that serves as a bridge between the user and the server. The instance of the client class manages sending log messages to its corresponding user, updating its GUI...
[ "Here is a class, \"Regulator\", which can be used to wrap any Callable in a way that meets your requirements. The function will never be called more than once in a given time interval. Excess calls will be discarded.\nThe main function is almost the same as your foo_caller but I added some time delays so that it...
[ 1, 0 ]
[]
[]
[ "python", "python_asyncio" ]
stackoverflow_0074402780_python_python_asyncio.txt
Q: parameter 'int1' is missing a type annotation in callback 'custdice' in discord.py I'm updating my bot to have slash commands and I encountered an issue, whenever there are parameters given in the command it refuses to even start the bot even though the parameters themselves are referenced in the command, the comm...
parameter 'int1' is missing a type annotation in callback 'custdice' in discord.py
I'm updating my bot to have slash commands and I encountered an issue, whenever there are parameters given in the command it refuses to even start the bot even though the parameters themselves are referenced in the command, the command in question is this one @bot.tree.command() async def custdice(ctx, int1, int2): ...
[ "For application commands, the type of the parameters has to be known because Discord treats them differently (eg. showing a list of members, roles, channels, checking for valid numbers, etc).\nYou haven't provided a type annotation for any of them, and the error is telling you to do so. It quite literally says wha...
[ 1 ]
[]
[]
[ "discord", "discord.py", "python" ]
stackoverflow_0074407531_discord_discord.py_python.txt
Q: Lookup based on row and column header Pandas How do I use the QuantityFormula column to iterate over the column headers. For example to find where count (from QuantityFormula) == count (from headers. Take the value of that row To produce a new column called Quantity, with that value. Do the same for all Count, Ar...
Lookup based on row and column header Pandas
How do I use the QuantityFormula column to iterate over the column headers. For example to find where count (from QuantityFormula) == count (from headers. Take the value of that row To produce a new column called Quantity, with that value. Do the same for all Count, Area, Volume It needs to work if new rows are adde...
[ "With your current data, you have nan in the columns that aren't the one you want, and only have a real value in the one you do.\nSo, I say you just add up those three columns, which will effectively be the_number_you_want + 0 + 0. You can use np.nansum() to properly add the nan as zero.\n...\nimport numpy as np\n....
[ 1, 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074405739_pandas_python.txt
Q: change json structure of column data frame pandas with nested json sorry i want to ask i want to change json structure of pandas data frame column with nested json but after trying to search in several sources have not found a solution. Maybe someone here can help, please help! thanks for the code like this: impor...
change json structure of column data frame pandas with nested json
sorry i want to ask i want to change json structure of pandas data frame column with nested json but after trying to search in several sources have not found a solution. Maybe someone here can help, please help! thanks for the code like this: import pandas as pd import json d = {'id': ['xxx'], 'user': ['asdam']} df = p...
[ "you can use a lambda function (a little strange but it works):\nimport pandas as pd\nimport json\nd = {'id': ['xxx'], 'user': ['asdam']}\ndf = pd.DataFrame(data=d)\ndf['user']=df['user'].apply(lambda x: {'display_name':x}) # create a dictionary with row value\nresult = df.to_json(orient=\"records\")\nparsed = json...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074383215_dataframe_pandas_python.txt
Q: tkinter get widget that event got called by Minimal reproducable Example from tkinter import * def test(event): print(event.widget) window = Tk() window.geometry("600x600") window.bind("<Motion>", test) frame = Frame(window, bg="red", width=200, height=200) frame.pack() frame.bind("<Motion>", test) window....
tkinter get widget that event got called by
Minimal reproducable Example from tkinter import * def test(event): print(event.widget) window = Tk() window.geometry("600x600") window.bind("<Motion>", test) frame = Frame(window, bg="red", width=200, height=200) frame.pack() frame.bind("<Motion>", test) window.mainloop() I want to call the function "test" fr...
[ "I think your confusion is in the moment of interpreting when the mouse pointer entered the widget or left the widget. Instead of Motion let's use for example Leave and Enter events to better understand what happens.\nI have taken the liberty of including some labels that show which widget we enter and left at each...
[ 1, 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074406293_python_tkinter.txt
Q: Object Method Reference Variable is not the Object method After initializing an object attribute to point to an object method, the variable will not be evaluated as being the same (using 'is') as the object method. It will still be evaluated as having equality (==) with the method. class SomeClass: def __init_...
Object Method Reference Variable is not the Object method
After initializing an object attribute to point to an object method, the variable will not be evaluated as being the same (using 'is') as the object method. It will still be evaluated as having equality (==) with the method. class SomeClass: def __init__(self): self.command = self.do_something def do_s...
[ "Each time you access a method via an instance, you get back a new instance of method that wraps both the instance and the underlying function. Two method instances compare as equal if they wrap the same instance and the same function. (This is not documented anywhere as far as I know—it's not mentioned in the docu...
[ 1 ]
[]
[]
[ "class", "function", "python" ]
stackoverflow_0074407492_class_function_python.txt
Q: Why mutable default parameter behaves this way? I'm aware of mutable parameter behavior. Why the list is not set up to None when I send and unpack **dictionary as argument? The common_header.png repeads, it means is stored in list. That is weird to me and I couldn't find answer for the question... I'm learning, ha...
Why mutable default parameter behaves this way?
I'm aware of mutable parameter behavior. Why the list is not set up to None when I send and unpack **dictionary as argument? The common_header.png repeads, it means is stored in list. That is weird to me and I couldn't find answer for the question... I'm learning, happy to hear any other suggestions to code, thank you ...
[ "In your code, when you pass the list explicitly to each call, you create a new instance of the list.\nWhen you pass as a dictionary, you are calling with a single instance of that list three times.\nWe could change your code to use the same list six times, and you'll see the same behavior with both calling convent...
[ 2, 1 ]
[]
[]
[ "default", "keyword_argument", "parameters", "python" ]
stackoverflow_0074407681_default_keyword_argument_parameters_python.txt
Q: Can't execute external script from zabbix I'm trying to execute script from zabbix ui. I put my script to '/usr/lib/zabbix/externalscripts' folder. The script's name is "check_ssl.py". When I connect to server and go to that folder and execute the script manually - it works, but when I try to execute it from zabb...
Can't execute external script from zabbix
I'm trying to execute script from zabbix ui. I put my script to '/usr/lib/zabbix/externalscripts' folder. The script's name is "check_ssl.py". When I connect to server and go to that folder and execute the script manually - it works, but when I try to execute it from zabbix's ui - it throws an error : "Traceback (most...
[ "The service environment is different from other users' env, see https://serverfault.com/questions/413397/how-to-set-environment-variable-in-systemd-service\nEdit the service with systemctl edit zabbix-server and add Environment=\"ACCESS_KEY=your_access_key\" in the [Service] section.\n", "\nCreate the script wit...
[ 0, 0 ]
[]
[]
[ "python", "zabbix" ]
stackoverflow_0072168478_python_zabbix.txt
Q: Pandas to_sql avoid duplicate rows I am using pandas' to_sql method to insert data into a mysql table. The mysql table already exists and I'd like to avoid inserting duplicate rows. https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_sql.html Is there a way to do this in python? # mysql connection imp...
Pandas to_sql avoid duplicate rows
I am using pandas' to_sql method to insert data into a mysql table. The mysql table already exists and I'd like to avoid inserting duplicate rows. https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_sql.html Is there a way to do this in python? # mysql connection import pandas as pd import pymysql from sql...
[ "It sounds like you want to do an \"upsert\" (insert or update). Pangres is a useful package that will allow you to do an upsert using a pandas df. If you don't want to update the row if it exists, that is also an option by setting if_row_exists to 'ignore'\n", "I have never heard of 'upsert' before today, but it...
[ 1, 0 ]
[]
[]
[ "mysql", "pandas", "python" ]
stackoverflow_0072960356_mysql_pandas_python.txt
Q: why my second app doesn't want import to first app Django File "C:\python mini\PyCharm Community Edition 2021.1.1\MyBlog\mysite\mysite\urls.py", line 3, in <module> from mysite.register import views ModuleNotFoundError: No module named 'mysite.register' Why do you think this error might occur? Why doesn't dja...
why my second app doesn't want import to first app Django
File "C:\python mini\PyCharm Community Edition 2021.1.1\MyBlog\mysite\mysite\urls.py", line 3, in <module> from mysite.register import views ModuleNotFoundError: No module named 'mysite.register' Why do you think this error might occur? Why doesn't django see the app being imported? maybe I should try setting up m...
[ "I'm Found the problem.I just swapped 2 lines... path('', include('blog.urls')), with path(\"register/\", views.register, name=\"register\"), . At the same time import from register import views are underlined red\n" ]
[ 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0074406381_django_django_models_python.txt
Q: Comparing an item in a list to an integer gives TypeError Python I have an array in my python program called ageArray. It contains the same attribute from each object in a group. Here's the intitialisation code: ageArray = [[amoeba.age] for amoeba in amoebas] Because the I want the attribute to change, I intitial...
Comparing an item in a list to an integer gives TypeError Python
I have an array in my python program called ageArray. It contains the same attribute from each object in a group. Here's the intitialisation code: ageArray = [[amoeba.age] for amoeba in amoebas] Because the I want the attribute to change, I intitialise it at the start of a while statement. After this I have the follow...
[ "You create a list with List Comprehensions, where each element is a list with one element ([amoeba.age] is a list with a single element):\n\nageArray = [[amoeba.age] for amoeba in amoebas]\n\n\nJust leave out the inner square brackets to create a list:\nageArray = [amoeba.age for amoeba in amoebas]\n\n", "Initia...
[ 2, 1 ]
[]
[]
[ "arrays", "python", "typeerror" ]
stackoverflow_0074407755_arrays_python_typeerror.txt
Q: Dot product of two vectors in tensorflow I was wondering if there is an easy way to calculate the dot product of two vectors (i.e. 1-d tensors) and return a scalar value in tensorflow. Given two vectors X=(x1,...,xn) and Y=(y1,...,yn), the dot product is dot(X,Y) = x1 * y1 + ... + xn * yn I know that it is possib...
Dot product of two vectors in tensorflow
I was wondering if there is an easy way to calculate the dot product of two vectors (i.e. 1-d tensors) and return a scalar value in tensorflow. Given two vectors X=(x1,...,xn) and Y=(y1,...,yn), the dot product is dot(X,Y) = x1 * y1 + ... + xn * yn I know that it is possible to achieve this by first broadcasting the v...
[ "One of the easiest way to calculate dot product between two tensors (vector is 1D tensor) is using tf.tensordot\na = tf.placeholder(tf.float32, shape=(5))\nb = tf.placeholder(tf.float32, shape=(5))\n\ndot_a_b = tf.tensordot(a, b, 1)\n\nwith tf.Session() as sess:\n print(dot_a_b.eval(feed_dict={a: [1, 2, 3, 4, 5...
[ 31, 27, 18, 4, 3, 2, 1, 1, 1, 0 ]
[]
[]
[ "dot_product", "python", "tensorflow" ]
stackoverflow_0040670370_dot_product_python_tensorflow.txt
Q: Behavior of multiprocessing.Pool on exception? Suppose I have a program that looks like this: jobs = [list_of_values_to_consume_and_act] with multiprocessing.Pool(8) as pool: results = pool.map(func, jobs) And whatever is done in func can raise an exception due to external circumstances, so I can't prevent an...
Behavior of multiprocessing.Pool on exception?
Suppose I have a program that looks like this: jobs = [list_of_values_to_consume_and_act] with multiprocessing.Pool(8) as pool: results = pool.map(func, jobs) And whatever is done in func can raise an exception due to external circumstances, so I can't prevent an exception from happening. How will the pool behave ...
[ "\nNo processes will be terminated at all. All calls to the target\nfunctions from within the pool's processes are wrapped in a\ntry...except block. Incase an exception is caught, the process\ninforms the appropriate handler thread in the main process which\npasses the exception forward so it can be re-rasied. Whet...
[ 1 ]
[]
[]
[ "python", "python_multiprocessing" ]
stackoverflow_0074382683_python_python_multiprocessing.txt
Q: AttributeError: module 'camelot' has no attribute 'read_pdf' I am trying to extract tables from pdf using camelot and I get this attribute error. Could you please help? import camelot import pandas as pd pdf = camelot.read_pdf("Gordian.pdf") AttributeError Traceback (most recent call l...
AttributeError: module 'camelot' has no attribute 'read_pdf'
I am trying to extract tables from pdf using camelot and I get this attribute error. Could you please help? import camelot import pandas as pd pdf = camelot.read_pdf("Gordian.pdf") AttributeError Traceback (most recent call last) in ----> 1 pdf = camelot.read_pdf("Gordian.pdf") Attri...
[ "NOTE : If you are using virtual environment activate environment before do this things. \nI have already faced this error.There is a no bug in your code.The problem is with camelot installation.\n1 remove installed camelot version\n2 install again using this command. There is a multiple ways to install camelot. Pl...
[ 16, 4, 4, 2, 1, 0 ]
[ "When downloading the library please pay attention to where it is downloaded. Because the library you downloaded may have been saved in another Python version\n" ]
[ -1 ]
[ "python", "python_camelot" ]
stackoverflow_0058376583_python_python_camelot.txt
Q: Analysis of categorical variables based on three dependent dropdowns in pandas I have a dataframe which looks something like this: df = pd.DataFrame ({'id': {0: 84, 1: 84, 2: 84, 3: 84, 4: 124}, 'Version': { 0: 'SemVer4', 1: 'Timestamps', 2: 'Snapshots', 3: 'Names', 4: 'Numbered Versions'}, ...
Analysis of categorical variables based on three dependent dropdowns in pandas
I have a dataframe which looks something like this: df = pd.DataFrame ({'id': {0: 84, 1: 84, 2: 84, 3: 84, 4: 124}, 'Version': { 0: 'SemVer4', 1: 'Timestamps', 2: 'Snapshots', 3: 'Names', 4: 'Numbered Versions'}, 'server_Version': {0: 'v1', 1: 'v2', 2: 'api/v1', 3: '1.1.0', 4: 'v4'}, ...
[ "Since you mentioned that you want the dropdowns to be dependent, the dropdowns have to be aware of the state of the other dropdowns – this isn't possible in plotly, but this is possible in plotly-dash since callbacks are supported.\nTo do this, we can write an update function that takes all possible selections for...
[ 1 ]
[]
[]
[ "pandas", "plotly", "plotly_dash", "plotly_python", "python" ]
stackoverflow_0074380944_pandas_plotly_plotly_dash_plotly_python_python.txt
Q: Expanding an alphanumeric range given a list I have a list of alphanumeric items: values=['1111X0-1111X3', 'A111X0-A111X3',...., ] I would like to expand the last digit of every item in this list such that: values_output = ['111X0', '111X1', '111X2', '111X3', 'A111X0', 'A111X1', 'A111X2', 'A111X3',...' ',...] I ...
Expanding an alphanumeric range given a list
I have a list of alphanumeric items: values=['1111X0-1111X3', 'A111X0-A111X3',...., ] I would like to expand the last digit of every item in this list such that: values_output = ['111X0', '111X1', '111X2', '111X3', 'A111X0', 'A111X1', 'A111X2', 'A111X3',...' ',...] I found this answer on a similar post that uses rege...
[ "You can use\nre.search(r'^(\\w+?)(\\d+)-\\1(\\d+)$', l)\n\nSee the Python demo.\nDetails:\n\n^ - start of string\n(\\w+?) - Group 1: any one or more word chars as few as possible\n(\\d+) - Group 2: one or more digits\n- - a hyphen\n\\1 - Group 1 value\n(\\d+) - Group 3: one or more digits\n$ - end of string.\n\n" ...
[ 4 ]
[]
[]
[ "list", "python", "regex" ]
stackoverflow_0074407932_list_python_regex.txt
Q: How to get rid of the rest of the text after getting the results I want? import urllib.request import json from collections import Counter def count_coauthors(author_id): coauthors_dict = {} url_str = ('https://api.semanticscholar.org/graph/v1/author/47490276?fields=name,papers.authors') respons = ur...
How to get rid of the rest of the text after getting the results I want?
import urllib.request import json from collections import Counter def count_coauthors(author_id): coauthors_dict = {} url_str = ('https://api.semanticscholar.org/graph/v1/author/47490276?fields=name,papers.authors') respons = urllib.request.urlopen(url_str) text = respons.read().decode() for line...
[ "From what I understand you are not quite sure where your successful output originates from. It is not the 5 lines at the end.\nYour result is printed by the print(top) on line 39. This top variable is what you want to return from the function, as the coauthors_dict you are currently returning never actually gets a...
[ 0, 0 ]
[]
[]
[ "json", "python", "urllib" ]
stackoverflow_0074407782_json_python_urllib.txt
Q: Can't get total size of a bucket with Boto3 I'm trying to get the total size of a bucket. However total_size returns 0. Of course there are a couple of files in the bucket. If I have five files in my bucket the following function prints five zeros. What am I doing wrong? bucket = boto3.resource('s3', config=Config...
Can't get total size of a bucket with Boto3
I'm trying to get the total size of a bucket. However total_size returns 0. Of course there are a couple of files in the bucket. If I have five files in my bucket the following function prints five zeros. What am I doing wrong? bucket = boto3.resource('s3', config=Config(signature_version="s3", s3={'addressing_style': ...
[ "I see few issues:\n\nNot sure about your call to boto3.resource(). Is that correct?\ntotal_size not initialized\n\nTry this:\ntotal_size = 0\nbucket = boto3.resource('s3').Bucket('mybucket')\nfor object in bucket.objects.all():\n total_size += object.size\n print(object.size)\nprint(total_size)\n\nOr a one liner...
[ 10, 2, 1, 1, 0, 0, 0 ]
[]
[]
[ "amazon_s3", "amazon_web_services", "boto", "boto3", "python" ]
stackoverflow_0046512945_amazon_s3_amazon_web_services_boto_boto3_python.txt
Q: Trying graph a piecewise function with Python Sympy, but don't know why all y-values are squeezed into a line I am trying to graph the following piecewise function: f(x)=1 for 4<x<6 f(x)=0 otherwise The following is my code: import sympy as sym import sympy.plotting as sym_plot sym.init_printing() x= sym.symbols('...
Trying graph a piecewise function with Python Sympy, but don't know why all y-values are squeezed into a line
I am trying to graph the following piecewise function: f(x)=1 for 4<x<6 f(x)=0 otherwise The following is my code: import sympy as sym import sympy.plotting as sym_plot sym.init_printing() x= sym.symbols('x') f_2 = sym.Piecewise((1, (4<x)),(1,(x<6)),(0,True)) sym_plot.plot(f_2, (x,-10,10)) My plot displays the followi...
[ "I think it has to do with the order in which you supply the conditionals. From sympy.Piecewise doc, \"the conditions are evaluated in turn, returning the first that is True.:\n | Piecewise( (expr,cond), (expr,cond), ... )\n | - Each argument is a 2-tuple defining an expression and condition\n | - The ...
[ 0 ]
[]
[]
[ "plot", "python", "sympy" ]
stackoverflow_0074407883_plot_python_sympy.txt
Q: how can i make this script reset if an incorrect password is used? import getpass p = getpass.getpass(prompt='What is the code you were given?? ') if p.lower() == 'breakout': print('Welcome..!!!') else: print('The answer entered by you is incorrect..!!!') I tried a few things, all of them gave errors. ...
how can i make this script reset if an incorrect password is used?
import getpass p = getpass.getpass(prompt='What is the code you were given?? ') if p.lower() == 'breakout': print('Welcome..!!!') else: print('The answer entered by you is incorrect..!!!') I tried a few things, all of them gave errors.
[ "Reset?. You mean you need to ask again if password is wrong?..if so Use while True until password is Correct\nimport getpass\n\nwhile 1:\n \n \n p = getpass.getpass(prompt='What is the code you were given?? ')\n \n if p.lower() == 'breakout':\n print('Welcome..!!!')\n break\n else...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074407941_python.txt
Q: Python - display loading animation while preforming a (long) task I'm trying to implement a program that is able to run functions (which take long time to complete). My understanding of threads and code-flow in python is quite limited, and I'm having a difficult time understanding how some methods, that can have n...
Python - display loading animation while preforming a (long) task
I'm trying to implement a program that is able to run functions (which take long time to complete). My understanding of threads and code-flow in python is quite limited, and I'm having a difficult time understanding how some methods, that can have no explicit async-await keywords (e.g. the PyGithub library, which makes...
[ "Change one line in your function execWhileLoading to run the loading function in an Executor. The default executor (a ThreadPoolExecutor) runs the function in another thread, but you may want to use a ProcessPoolExecutor instead. The method returns an awaitable, so it needs to be used in an await expression.\nSe...
[ 1 ]
[]
[]
[ "async_await", "python", "python_asyncio" ]
stackoverflow_0074399077_async_await_python_python_asyncio.txt
Q: Python: get correct link with dynamic URLs in Flask with url_for() I have html template, and python function(driver_links), my functional work but I have the wrong link html template (driver_id.html): <a href="{{ url_for('driver_links', driver_id=key[0]) }}">{{key[0]}}</a> function: @app.route("/report/drivers/<d...
Python: get correct link with dynamic URLs in Flask with url_for()
I have html template, and python function(driver_links), my functional work but I have the wrong link html template (driver_id.html): <a href="{{ url_for('driver_links', driver_id=key[0]) }}">{{key[0]}}</a> function: @app.route("/report/drivers/<driver_id>") def driver_links(driver_id): context = { "repo...
[ "Choose between variable rules or url parameters.\nIf you use the former, the required, extracted parameter is passed as a variable to the function.\n@app.route(\"/report/drivers/<driver_id>\")\ndef driver_links(driver_id):\n # ...\n\nWith the latter, you have to ask for the optional parameter from the dictionar...
[ 1 ]
[]
[]
[ "flask", "html", "jinja2", "python", "url" ]
stackoverflow_0074407866_flask_html_jinja2_python_url.txt
Q: Formatting of table for Telegram bot (python) I am developing simple telegram bot that should send dataframe to the chat. The problem is that the dataframe gets distorted (it has 5 columns). I was thinking about 2 solutions: Make a picture and then send it to the chat. The problem is that you have to save picture...
Formatting of table for Telegram bot (python)
I am developing simple telegram bot that should send dataframe to the chat. The problem is that the dataframe gets distorted (it has 5 columns). I was thinking about 2 solutions: Make a picture and then send it to the chat. The problem is that you have to save picture locally (i need the chat bot to work instantly). D...
[ "Take a look at this question (converting dataframe to png). Showing dataframe in the message is not a very good idea. I think the best solution here is to generate .txt or .csv file and send it to user. Users on the phones should be able to open these files with ease (by tapping on them).\n" ]
[ 1 ]
[]
[]
[ "aiogram", "chatbot", "python", "telegram" ]
stackoverflow_0074408027_aiogram_chatbot_python_telegram.txt
Q: Draw specific edges in graph in NetworkX I have a graph looking like this: By default, drawing the graph will include all nodes and edges, but I need to draw some specific edges using an array of connected nodes like this: [ ['A', 'C', 'B', 'A'], ['A', 'E', 'D', 'F', 'A'], ['A', 'H', 'G', 'I', 'A'] ] ...
Draw specific edges in graph in NetworkX
I have a graph looking like this: By default, drawing the graph will include all nodes and edges, but I need to draw some specific edges using an array of connected nodes like this: [ ['A', 'C', 'B', 'A'], ['A', 'E', 'D', 'F', 'A'], ['A', 'H', 'G', 'I', 'A'] ] Here is my code: G = nx.DiGraph(edge_list) nx...
[ "If I've understood correctly, you can do something like this:\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport networkx as nx\n\nG = nx.complete_graph(10).to_directed()\n\nfor edge in G.edges:\n G.add_edge(*edge[::-1])\n\ncycles = [[0, 1, 2, 0], [0, 3, 4, 5, 6, 0], [0, 7, 8, 0]]\n\nH = nx.DiGraph()\...
[ 2 ]
[]
[]
[ "networkx", "python" ]
stackoverflow_0074406226_networkx_python.txt
Q: How to transpose unique entries in a column and print values from another column I have a file input.txt with two columns, I want to split the second column by ";" and transpose the unique entries then count and list how many matches are in column 1. This is my tab-delimited input.txt file Gene Biological_Proc...
How to transpose unique entries in a column and print values from another column
I have a file input.txt with two columns, I want to split the second column by ";" and transpose the unique entries then count and list how many matches are in column 1. This is my tab-delimited input.txt file Gene Biological_Process BALF2 metabolic process CHD4 cell organization and biogenesis;metabolic proce...
[ "$ cat script.awk \n#! /usr/bin/awk -f \n\nBEGIN {\n FS = \"[\\t;]\"; # sep can be a regex\n OFS = \"\\t\"\n}\n\nNR>1 && /^[A-Z]/{ # skip header & blank lines \n for(i=NF; i>1; i--)\n if($i) # skip empty bio-proc\n a[$i] = a[$i] OFS $1 \n}\nEND{\n print \"Biological_Process\",\"Gene...
[ 2, 1 ]
[]
[]
[ "awk", "python" ]
stackoverflow_0074369833_awk_python.txt
Q: AttributeError: __enter__ while passing .xml via HTTP Post to pd.read_xml() I'm using python pandas and flask for some postprocessing tasks (anlaysis and visualization). Until now I uploaded/read *.csv *.xlsx and *.xls via pd.read_csv, pd.read_xlsx. Everything worked quiet fine. Now I have a *.xml file as datasour...
AttributeError: __enter__ while passing .xml via HTTP Post to pd.read_xml()
I'm using python pandas and flask for some postprocessing tasks (anlaysis and visualization). Until now I uploaded/read *.csv *.xlsx and *.xls via pd.read_csv, pd.read_xlsx. Everything worked quiet fine. Now I have a *.xml file as datasource and tried according my habit pattern. So i tried: <form action="/input" method...
[ "I just solved my issue even though I'm not quite sure why pd.read_xml() behaves different compared to pd.read_csv() or pd.read_xlsx().\npd.read_xml is not able to read a FileStorage object. The variable passed by request.file[] is a instance of the class: werkzeug.datastructures.FileStorage(stream=None, filename=N...
[ 1 ]
[]
[]
[ "attributeerror", "flask", "pandas", "python", "xml" ]
stackoverflow_0074379738_attributeerror_flask_pandas_python_xml.txt
Q: multi thread is not closing though terminated For some reason, when the timeout is reached and the except is therefore executed, thread 2 is still "working", still expecting to get values from the user. Even though the closing_threads function is entered. Why can't I terminate the thread? Why is it still waiting ...
multi thread is not closing though terminated
For some reason, when the timeout is reached and the except is therefore executed, thread 2 is still "working", still expecting to get values from the user. Even though the closing_threads function is entered. Why can't I terminate the thread? Why is it still waiting for keyboard entry? If I add t2.join() then executi...
[ "the second thread is technically not working, nor terminated, it is in a suspended state by the operating system, it will be terminated when it returns from this suspended state.\nwhen you call input the operating system suspends the thread, and waits for input, then when input is available it wakes the thread and...
[ 0 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0074407832_multithreading_python.txt
Q: I'm trying to test my code using pytest but i get 'command not found' in my terminal I tried uninstalling and reinstalling it and nothing gives. Im using vscode by the way. Any help will be appreciated. This is the error message i get: I'm hoping to get some guidance on how to locate the package on my computer an...
I'm trying to test my code using pytest but i get 'command not found' in my terminal
I tried uninstalling and reinstalling it and nothing gives. Im using vscode by the way. Any help will be appreciated. This is the error message i get: I'm hoping to get some guidance on how to locate the package on my computer and place it in the correct path, as suggested by the error message, but im very new to pyth...
[ "Try this:\nC:/Users/reham/AppData/Local/Microsoft/WindowsApps/python3.10.exe -m pytest\nThis is temporary solution. You should be able to run python -m pytest, but I guess this will fail if Python is not in PATH. You might want to add Python to PATH if commands like python or python -m ... fail.\n" ]
[ 2 ]
[]
[]
[ "pytest", "python", "visual_studio_code" ]
stackoverflow_0074407972_pytest_python_visual_studio_code.txt
Q: Drag & Drop files to Pygame and save them I wonder if someone know anyway to make function to drag and drop image to pygame screen and after that save it to files in computer. For example like in Photoshop. or at least browse button like here: I would like to use that image after that as well. A: Pygame seems t...
Drag & Drop files to Pygame and save them
I wonder if someone know anyway to make function to drag and drop image to pygame screen and after that save it to files in computer. For example like in Photoshop. or at least browse button like here: I would like to use that image after that as well.
[ "Pygame seems to have limited support for dragging and dropping event, but it is possible to acomplish certain tasks.\nIt turns out that dropping a file on an active Pygame window will generate an event of type pygame.DROPFILE with a single file attribute which contains the absolute path to the file as a string.\n...
[ 1 ]
[]
[]
[ "file", "pygame", "python" ]
stackoverflow_0074407954_file_pygame_python.txt
Q: chocolatey says it has successfully force reinstalled python 3.11 - but I can't find it Windows 11. I am not great at virtual environments, and I have bumped around between a half dozen different "solutions." I thought I had it solved with chocolatey, but I am trying to install python3.11, and not having success....
chocolatey says it has successfully force reinstalled python 3.11 - but I can't find it
Windows 11. I am not great at virtual environments, and I have bumped around between a half dozen different "solutions." I thought I had it solved with chocolatey, but I am trying to install python3.11, and not having success. Basically, choco says it is installed, but I can't find it anywhere. C:\Windows\System32>ch...
[ "From PowerShell, run get-command python.exe\nAnd you will get something like this:\nCommandType Name Version Source\n----------- ---- ------- ------\nApplication python.exe ...
[ 1, 1 ]
[]
[]
[ "choco", "chocolatey", "python" ]
stackoverflow_0074340427_choco_chocolatey_python.txt
Q: How to highlight the 3 highest values and 3 lowest values in on dataframe Currently, I only know how to create a dataframe that highlights highest values or a dataframe that highlights lowest values. I want one dataframe with highlight lowest and highest. The code I currently use to do this (for highest values) is...
How to highlight the 3 highest values and 3 lowest values in on dataframe
Currently, I only know how to create a dataframe that highlights highest values or a dataframe that highlights lowest values. I want one dataframe with highlight lowest and highest. The code I currently use to do this (for highest values) is: def highlight_top3(s): # Get 3 largest values of the column is_large = s.nla...
[ "You can try the following:\nimport pandas as pd\n\ndf = pd.DataFrame({'a': [1,2,3,5,6,7,0.5,9,4,5.5]})\n\ndef highlight_top3(s):\n \n result = []\n is_large = s.nlargest(3).values\n is_small = s.nsmallest(3).values\n\n for i in s:\n if i in is_large:\n result.append('background-col...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074406711_dataframe_pandas_python.txt
Q: Comparing lines in two files and print only missing line I have two files 1.0.txt and Master.txt and I need the list that has all the commits in 1.0.txt but missing in Master.txt Commit example: 19175c1 Correct the logic by Jacob · 2 days ago 8.4.0.109 I need to compare only the message Correct the logic and i...
Comparing lines in two files and print only missing line
I have two files 1.0.txt and Master.txt and I need the list that has all the commits in 1.0.txt but missing in Master.txt Commit example: 19175c1 Correct the logic by Jacob · 2 days ago 8.4.0.109 I need to compare only the message Correct the logic and if this message is NOT in the master.txt then print it import j...
[ "You can use .rfind() to find the last instance of a substring in a string, so you can change your splitting_line assignment to this: splitting_line = message[8:message.rfind(\" by \")], this'll make your program a little better at saving memory and accounts for if you use the word \"by\" in your commit.\nI struggl...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074407901_python.txt
Q: Issues with PySerial: Port must be configured before it can be used I am writing code (in python) to use serial communication with an Arduino, using the pySerial library, on Windows 7. However, I am having issues using the ports correctly. Here is my code: import serial #sets the connection parameters, relook a...
Issues with PySerial: Port must be configured before it can be used
I am writing code (in python) to use serial communication with an Arduino, using the pySerial library, on Windows 7. However, I am having issues using the ports correctly. Here is my code: import serial #sets the connection parameters, relook at when know more ser = serial.Serial( port ='COM4', baudrate = 9600, pa...
[ "I guess that with the second ser = serial.Serial(), you are overwriting the serial port object that you created in the first few lines. You are replacing it with a new serial port object, which was created without giving it any parameters. Try commenting out that line.\n", "If you want to use serial.Serial(), no...
[ 1, 0 ]
[]
[]
[ "pyserial", "python", "usb" ]
stackoverflow_0030246659_pyserial_python_usb.txt
Q: Pandas : How to flatten/split multiple nested dictionary, inside a JSONresponse I am getting a json response like this : { "id": 7, "status": "Public", "Options": [ { "id": 8, "pId": 7 }, ...
Pandas : How to flatten/split multiple nested dictionary, inside a JSONresponse
I am getting a json response like this : { "id": 7, "status": "Public", "Options": [ { "id": 8, "pId": 7 }, { "id": 9, "pId": 10 ...
[ "Let's get the id and pId values ​​into a list using the group by function.\ndf = pd.DataFrame(response_data)\ndf=df.rename(columns={'id':'id_main'})\ndf=df.join(pd.json_normalize(df.pop('Options')))\ndf=df.groupby('id_main').agg({'status':'first','id':list,'pId':list})\nprint(df)\n'''\n status id ...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074382327_dataframe_pandas_python.txt
Q: Does Pandas release the last chunk from memory after loading the next one? Take the code below for example. Assuming the chunk iterator renders 10 chunks, the for loop will load all of them into memory (one after another) or Python will work efficiently releasing one after the oter? df_iter = pd.read_csv(file, chu...
Does Pandas release the last chunk from memory after loading the next one?
Take the code below for example. Assuming the chunk iterator renders 10 chunks, the for loop will load all of them into memory (one after another) or Python will work efficiently releasing one after the oter? df_iter = pd.read_csv(file, chunksize=100) for chunk in df_iter: chunk.to_sql(table, engine) I've made some...
[ "I think I'm seeing what you're seeing, where more and more memory gets used in the program as the loop iterates. I wasn't expecting this to be the case. I tried keeping track of current memory using the tracemalloc library and the memory usage does increase.\nI tried to pre-allocate all the memory I'd need outside...
[ 1, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0072408709_dataframe_pandas_python.txt
Q: Append values to list within a pandas column As simple as this sounds I cannot figure it out... Here's what I want to do df = pd.DataFrame( [ {'first names' : ['trey', 'tagg']}, {'first names' : ['teague', 'tanner']}, ] ) df first names 0 [trey, tagg] 1 ['teague', 'tanner'] I would like to do something such...
Append values to list within a pandas column
As simple as this sounds I cannot figure it out... Here's what I want to do df = pd.DataFrame( [ {'first names' : ['trey', 'tagg']}, {'first names' : ['teague', 'tanner']}, ] ) df first names 0 [trey, tagg] 1 ['teague', 'tanner'] I would like to do something such as df['first names'].append('joe') and...
[ "Try:\ndf[\"first names\"].apply(lambda lst: lst.append(\"joe\"))\nprint(df)\n\nPrints:\n first names\n0 [trey, tagg, joe]\n1 [teague, tanner, joe]\n\n", "You can try\nfor val in df['first names']:\n val.append('jeo')\nprint(df)\n\noutput\n first names\n0 [trey, tagg, jeo]\n1...
[ 1, 1 ]
[]
[]
[ "list", "pandas", "python" ]
stackoverflow_0074408219_list_pandas_python.txt
Q: Python: sum column for every dataframe in a list I have a list of identical dataframes and I am trying to sum one column in each dataframe in the list. My thought is something like total = [df['A'].sum for df in dfs] but this returns a list of length dfs containing only the value method. My desired output is a lis...
Python: sum column for every dataframe in a list
I have a list of identical dataframes and I am trying to sum one column in each dataframe in the list. My thought is something like total = [df['A'].sum for df in dfs] but this returns a list of length dfs containing only the value method. My desired output is a list of the column sum for each dataframe. What is the fa...
[ "Perhaps, you are missing () after sum\n total = [df['A'].sum() for df in dfs]\n\nYou want to call the method sum not just reference it.\nPython sum is pretty quick: Python built-in sum function vs. for loop performance and\nI assume that pandas sum should be comparable.\nDifference between sum, 'sum' and np.sum *u...
[ 0 ]
[]
[]
[ "dataframe", "list", "pandas", "python", "sum" ]
stackoverflow_0074408254_dataframe_list_pandas_python_sum.txt
Q: How to get full html when requesting page I am working on scrapping web page which requires authentication and need full page html to scrap the data. I am using cookies to authenticate request. I am not in favor of using selenium driver as it makes me open browser. I want this process to be running in backend. I h...
How to get full html when requesting page
I am working on scrapping web page which requires authentication and need full page html to scrap the data. I am using cookies to authenticate request. I am not in favor of using selenium driver as it makes me open browser. I want this process to be running in backend. I have tried it using requests and urllib.requests...
[ "\nUsing the requests library:\n\nimport requests\n\nr = requests.get('http://www.google.com')\n\nprint(r.text)\n\n\nUsing the urllib library:\n\nimport urllib.request\n\nwith urllib.request.urlopen('http://www.google.com') as response:\n html = response.read()\n\nprint(html)\n\n\nUsing the selenium library:\n\nf...
[ 0 ]
[]
[]
[ "python", "request", "urllib" ]
stackoverflow_0074408332_python_request_urllib.txt
Q: Compare dataframe previous and current row in Python I have a dataframe with the following column. CUI C13874 C13874 C47687 I have written a function that calls a certain API endpoint. I would like to only call the API endpoint when the value of 'CUI' column changes, else write the previous output. umls_cui = ope...
Compare dataframe previous and current row in Python
I have a dataframe with the following column. CUI C13874 C13874 C47687 I have written a function that calls a certain API endpoint. I would like to only call the API endpoint when the value of 'CUI' column changes, else write the previous output. umls_cui = open('umls_cui_names.txt', 'w') def get_cui(CUI): #i...
[ "You can try assigning the used value to a variable and check if that value is repeating in each iteration (I made a dummy function to show how it works):\nimport pandas as pd\n\ndef get_cui(CUI):\n print('calling:', CUI)\n return CUI\n\ndata = ['C13874', 'C13874', 'C47687']\ndf = pd.DataFrame(data, columns=[...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074408272_python.txt
Q: How can I save a new array in iteration in a loop Let me preface this by saying that I am new to programming. I would like to create a new array for each iteration, not add elements to the same array. How can I create a new array? If I use E=np.array[(...)] in my loop, I will be rewriting the array every single ti...
How can I save a new array in iteration in a loop
Let me preface this by saying that I am new to programming. I would like to create a new array for each iteration, not add elements to the same array. How can I create a new array? If I use E=np.array[(...)] in my loop, I will be rewriting the array every single time. I want to have a series of arrays saved so that I c...
[ "Based on your statement \"I want to have a series of arrays saved so that I can Add them to a data frame later\"\nI suggest that you initiate an empty dataframe and then append each loop's resulting array to the dataframe with an appropriate unique ID identifying the loop it came from.\ndf=pd.DataFrame() \nE=0\nn=...
[ 0, 0 ]
[]
[]
[ "arrays", "dataframe", "loops", "python" ]
stackoverflow_0074408174_arrays_dataframe_loops_python.txt
Q: Odoo 13:- HTTP controller type ="http" request type application/json not accepted I write a odoo program in python, this way request type text/plain is working. And application/json request work in any other odoo version(Odoo 15,Odoo 16) .But odoo 13 application/json request not working. My odoo python controlle...
Odoo 13:- HTTP controller type ="http" request type application/json not accepted
I write a odoo program in python, this way request type text/plain is working. And application/json request work in any other odoo version(Odoo 15,Odoo 16) .But odoo 13 application/json request not working. My odoo python controller code here:- class CamsAttendance(http.Controller): @http.route('/sample/sample_js...
[ "Have you tried to change the type of the controller route to json?\nAlso see the official documentation\n\nodoo.http.route(route=None, **kw)\nDecorator marking the\ndecorated method as being a handler for requests. The method must be\npart of a subclass of Controller.\nParameters\nroute – string or array. The rout...
[ 0, 0 ]
[]
[]
[ "http_post", "json", "odoo", "odoo_13", "python" ]
stackoverflow_0074398335_http_post_json_odoo_odoo_13_python.txt
Q: Print non-unicode subscript to Python console I'm using Python 3.10 to implement a classical mechanics problem, and I want to print a message to the console asking the user to input the initial velocities. I am using x, y, and z as coordinates so ideally I want to denote the velocity components as vx, vy, and vz. ...
Print non-unicode subscript to Python console
I'm using Python 3.10 to implement a classical mechanics problem, and I want to print a message to the console asking the user to input the initial velocities. I am using x, y, and z as coordinates so ideally I want to denote the velocity components as vx, vy, and vz. Originally I thought of using unicode subscirpts, b...
[ "No -\nThe terminal emulator (or command line) can only display characters, and does not allow for unlimited character transformations, as it is possible with text on a web browser or in a graphic interface.\nALthough there are special character sequences that can trigger special features such as foreground and bac...
[ 0 ]
[]
[]
[ "python", "subscript", "unicode", "user_input", "user_interface" ]
stackoverflow_0074396230_python_subscript_unicode_user_input_user_interface.txt
Q: DynamoDB : The provided key element does not match the schema Is there a way to get an item depending on a field that is not the hashkey? Example My Table Users: id (HashKey), name, email And I want to retrieve the user having email as 'test@mail.com' How this can be done? I try this with boto: user = users.get_it...
DynamoDB : The provided key element does not match the schema
Is there a way to get an item depending on a field that is not the hashkey? Example My Table Users: id (HashKey), name, email And I want to retrieve the user having email as 'test@mail.com' How this can be done? I try this with boto: user = users.get_item(email='john.doe@gmail.com') I get the following error: 'The pr...
[ "The following applies to the Node.js AWS SDK in the AWS Lambda environment:\nThis was a rough one for me. I ran into this problem when trying to use the getItem method. No matter what I tried I would continue to receive this error. I finally found a solution on the AWS forum: https://forums.aws.amazon.com/thread.j...
[ 53, 24, 14, 8, 2, 1, 1, 0, 0 ]
[]
[]
[ "amazon_dynamodb", "amazon_web_services", "boto", "python" ]
stackoverflow_0025886403_amazon_dynamodb_amazon_web_services_boto_python.txt
Q: How to count frequency of first letters of strings? I have a list of strings in my program, for example: [ 'home', 'dog', 'park', 'house', 'hotel', 'fire' ] and I want to know which is the most first frequent letter . for example in that string is the letter H because it is in hotel, house and home. I tried just ...
How to count frequency of first letters of strings?
I have a list of strings in my program, for example: [ 'home', 'dog', 'park', 'house', 'hotel', 'fire' ] and I want to know which is the most first frequent letter . for example in that string is the letter H because it is in hotel, house and home. I tried just 2 for cycles but I didn't get the result
[ "You could create a list of the first letters and then use the max() function to get the highest number of occurrences in it.\nlst = ['home', 'dog', 'park', 'house', 'hotel', 'fire']\nmax([item[0] for item in lst], key=lst.count)\n\noutput\n'h'\n\n", "Extracting first elemnt from list item & Using collections\nfr...
[ 3, 1, 1, 1, 0 ]
[]
[]
[ "frequency", "python" ]
stackoverflow_0074408312_frequency_python.txt
Q: Flattening JSON objects using Python I have a json object sample_json ={ "workspaces": [ { "wsid": "1", "wsname": "firstworkspace", "report":[{"reportname":"r1ws1"},{"reportname":"r2ws1"},{"reportname":"r1ws1"}] }, { "wsid": "2", "wsname": "secondworkspace", ...
Flattening JSON objects using Python
I have a json object sample_json ={ "workspaces": [ { "wsid": "1", "wsname": "firstworkspace", "report":[{"reportname":"r1ws1"},{"reportname":"r2ws1"},{"reportname":"r1ws1"}] }, { "wsid": "2", "wsname": "secondworkspace", "report":[{"reportname":"r1ws2"},{"rep...
[ "The package jertl can be used for this.\nIn [1]: import jertl\n\nIn [2]: import pandas as pd\n\nIn [3]: sample_json = ... #removed for brevity\n\nIn [4]: pattern = '''\n ...: {\n ...: \"workspaces\": [*_,\n ...: {\n ...: \"wsid\": wsid,\n ...: \"wsname\": wsname,\n ...: \"...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074407074_python.txt
Q: Google AdManager getCurrentNetwork() error I have set up ad manager credentials. I'm trying to access the Admanager API, im getting the following error. from googleads import ad_manager client = ad_manager.AdManagerClient.LoadFromStorage() network_service = client.GetService('NetworkService', version='v201902') cu...
Google AdManager getCurrentNetwork() error
I have set up ad manager credentials. I'm trying to access the Admanager API, im getting the following error. from googleads import ad_manager client = ad_manager.AdManagerClient.LoadFromStorage() network_service = client.GetService('NetworkService', version='v201902') current_network = network_service.getCurrentNetwor...
[ "You are probably missing permissions with your configured service account. Make sure the account has access to ad-manager and scopes are configured properly.\n", "I suggest to do it this way:\nclass Adx:\n def __init__(self):\n self.GOOGLEADS_YAML = 'googleads.yaml'\n self.GOOGLEADS_VERSION = 'v...
[ 0, 0 ]
[]
[]
[ "google_ad_manager", "python", "soap" ]
stackoverflow_0054710091_google_ad_manager_python_soap.txt
Q: How to edit header in Odoo I'm in Odoo15 and i want to modify the header in Odoo view I have Quotations / S00156 like in the image, but the client want only the first 3 numbers, should look something like this Quotations / S156 How can I modify this in Odoo? I only have to modify the way it looks like in this view...
How to edit header in Odoo
I'm in Odoo15 and i want to modify the header in Odoo view I have Quotations / S00156 like in the image, but the client want only the first 3 numbers, should look something like this Quotations / S156 How can I modify this in Odoo? I only have to modify the way it looks like in this view. Thanks! :)
[ "if you use custom module then you are go to the folder in custom module view/view.xml add the file in\n<menuitem id=\"sample_id\" name=\"DISPLAY_NAME\"\n parent=\"SALES.SALES\" sequence=\"20\"\n groups=\"SALES.GROUP_SALES\" action=\"SALES\"/>\n\nI write caps_leter words change you...
[ 0, 0 ]
[]
[]
[ "odoo", "odoo_15", "python" ]
stackoverflow_0074398276_odoo_odoo_15_python.txt
Q: Sending a pointer to glVertexAttributePointer in Pyrthon I need to pass an offset pointer to glVertexAttribPointer in Python. Currently I have coming out of pythons console window when an instance of Box class is created: C:\Users\phill\PycharmProjects\texturebox\venv\Scripts\python.exe C:\Users\phill\PycharmProje...
Sending a pointer to glVertexAttributePointer in Pyrthon
I need to pass an offset pointer to glVertexAttribPointer in Python. Currently I have coming out of pythons console window when an instance of Box class is created: C:\Users\phill\PycharmProjects\texturebox\venv\Scripts\python.exe C:\Users\phill\PycharmProjects\texturebox\main.py Traceback (most recent call last): Fil...
[ "(GL.GLfloat * 6)(*vertices_list) does not do what you expect. It creates an array with 6 elements.\nSee pyopengl, glVertexAttribPointer. The argument must be a void pointer. You can use the ctypes.c_void_p to create a void pointer, e.g.:\nGL.glVertexAttribPointer(1,\n 3,\n ...
[ 2 ]
[]
[]
[ "glfw", "opengl", "pyopengl", "python", "texturing" ]
stackoverflow_0074408404_glfw_opengl_pyopengl_python_texturing.txt
Q: OBS crashes when set_current_scene function called within a timer callback (Python scripting) scenes = obs.obs_frontend_get_scenes() def script_load(settings): obs.obs_frontend_add_event_callback(onevent) def script_update(settings): global trigger, s_minutes, s_seconds, ending, e_minutes, e_seconds t...
OBS crashes when set_current_scene function called within a timer callback (Python scripting)
scenes = obs.obs_frontend_get_scenes() def script_load(settings): obs.obs_frontend_add_event_callback(onevent) def script_update(settings): global trigger, s_minutes, s_seconds, ending, e_minutes, e_seconds trigger = obs.obs_data_get_string(settings, "e_trigger scene") s_minutes = obs.obs_data_get_int(...
[ "This might be a bit late, and I'm relatively new to programming to OBS, but I noticed that your code uses \"obs_frontend_get_current_scene()\". There are some calls, including this one, that create pointers whenever they are called. These pointers have to be released or they continue consuming more and more resour...
[ 0 ]
[]
[]
[ "obs", "obs_studio", "python", "scripting" ]
stackoverflow_0073142444_obs_obs_studio_python_scripting.txt
Q: GIF not getting saved while using ImageIO/PIL I am trying to use both ImageIo and PIL to save a sequence of my images as GIF. The images do get saved in a .gif file. But, they are getting saved as a sequence of images and not as a "video" GIF. gif_images[0].save('path/test.gif', save_all=True, append_images=gif_im...
GIF not getting saved while using ImageIO/PIL
I am trying to use both ImageIo and PIL to save a sequence of my images as GIF. The images do get saved in a .gif file. But, they are getting saved as a sequence of images and not as a "video" GIF. gif_images[0].save('path/test.gif', save_all=True, append_images=gif_images[1:], optimize=False, duration=40, loop=0) #usi...
[ "I would recommend that you switch to using ImageIO's v3 API. The syntax is a little cleaner:\nimport imageio.v3 as iio\n\niio.imwrite(\"path/test.gif\", gif_images, duration=100, loop=0)\n# duration is the time to display each frame in ms\n\n\nThat said, the reason you are seeing a \"sequence of images\" instead o...
[ 0 ]
[]
[]
[ "gif", "python", "python_imageio", "python_imaging_library" ]
stackoverflow_0074398682_gif_python_python_imageio_python_imaging_library.txt
Q: why is the inscription displayed and not the number? I don't understand what i am doing wrong, why "s" outputs like a title print('* xa=',xa,' * s=,{:9.f}', '*'. format('s')) I expected that i will see s=(there would be number of s) A: You put .format in the wrong place, it should...
why is the inscription displayed and not the number?
I don't understand what i am doing wrong, why "s" outputs like a title print('* xa=',xa,' * s=,{:9.f}', '*'. format('s')) I expected that i will see s=(there would be number of s)
[ "You put .format in the wrong place, it should be after ' * s=,{:9.f}'. And the argument should be the variable that should be formatted, so you shouldn't put s in quotes.\nIn modern Python it's easier to put everything together into an f-string instead of using .format().\nprint(f'* xa={xa...
[ 0 ]
[]
[]
[ "format", "python" ]
stackoverflow_0074408552_format_python.txt
Q: Set default page when installed new module i want to know how to set default page when installing new module. Like example, My main module is about restaurant ERP, by it's default when i open my module the default page is Restaurant Overview and then i installed reporting sub module with Report Dashboard on it. Ho...
Set default page when installed new module
i want to know how to set default page when installing new module. Like example, My main module is about restaurant ERP, by it's default when i open my module the default page is Restaurant Overview and then i installed reporting sub module with Report Dashboard on it. How to set default page from Restaurant Overview t...
[ "Odoo permits to set an initial action for every user.\nFrom Settings -> Users and Companies -> Users pick one user.\nMove to Preferences tab, and pick desired action in Initial page action field.\nRepeat this for every user.\n" ]
[ 0 ]
[]
[]
[ "odoo", "odoo_14", "python", "xml" ]
stackoverflow_0074329894_odoo_odoo_14_python_xml.txt
Q: Python Tkinter import all I keep getting a warning in my code editor "Wildcard import from a library not allowed" does anyone know how to fix this error? from tkinter import * this is the warning I get (Wildcard import from a library not allowed) A: When you use a wildcard import, every function and variable fr...
Python Tkinter import all
I keep getting a warning in my code editor "Wildcard import from a library not allowed" does anyone know how to fix this error? from tkinter import * this is the warning I get (Wildcard import from a library not allowed)
[ "When you use a wildcard import, every function and variable from the library is \"put\" into your code. This can cause unexpected issues, like accidentally writing a variable from tkinter.\nInstead, you should import tkinter as tk and put tk.<widget name> for anything you want to put in a window.\n" ]
[ 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074399724_python_tkinter.txt
Q: How to shift a pandas column based on date column from previous month I have a df called df_actual that looks like this: BondSecurity TradeCoupon IssuanceYear AsOfDate Cpr1 0 FNCL 4.0 2017 2022-06-30 17.888957 1 FNCL 4.0 2018 2022-04-30 26.383609...
How to shift a pandas column based on date column from previous month
I have a df called df_actual that looks like this: BondSecurity TradeCoupon IssuanceYear AsOfDate Cpr1 0 FNCL 4.0 2017 2022-06-30 17.888957 1 FNCL 4.0 2018 2022-04-30 26.383609 2 FNCL 4.0 2018 2022-05-31 20.834899 3 F...
[ "Clustering method:\ndf_actual['cohort'] = df_actual.BondSecurity + ' ' + df_actual.IssuanceYear.astype(str) + ' ' + df_actual.TradeCoupon.astype(str)\ncohort_list = [df_actual[df_actual.cohort == x] for x in df_actual.cohort.unique()]\n\nThen run each clustered dataframe through the following for loop to generate ...
[ 1 ]
[]
[]
[ "conditional_statements", "datetime", "indexing", "pandas", "python" ]
stackoverflow_0074408331_conditional_statements_datetime_indexing_pandas_python.txt
Q: create a list of categories from a dictionary in Python ` import csv record={} with open( 'subject-info.csv') as f: reader = csv.DictReader(f) for row in reader: record[row['ID']]=row['Age_group'] ` now the dictionary has ID number as keys and the value of each key has one number between 1 and 13...
create a list of categories from a dictionary in Python
` import csv record={} with open( 'subject-info.csv') as f: reader = csv.DictReader(f) for row in reader: record[row['ID']]=row['Age_group'] ` now the dictionary has ID number as keys and the value of each key has one number between 1 and 13. each number represents an age group. I need to put together...
[ "import csv\n\nrecord_list=[]\nwith open( 'subject-info.csv') as f:\n reader = csv.DictReader(f)\n for row in reader:\n record_dict={}\n record_dict[row['ID']]=row['Age_group']\n record_list.append(record_dict)\n\nI hope this might help you. Good day!\n", "I finally found the answer and...
[ 0, 0 ]
[]
[]
[ "categories", "csv", "dictionary", "list", "python" ]
stackoverflow_0074383187_categories_csv_dictionary_list_python.txt
Q: Add variable value in payload string in Python I have payload string that i want to modify in a loop but i can not figure out how to convert this '41.86464600000019' and this '-87.80732699999984' in variables to replace them in a loop. inserting f{} did not help here is the full string payload = "{\"showPrice\":...
Add variable value in payload string in Python
I have payload string that i want to modify in a loop but i can not figure out how to convert this '41.86464600000019' and this '-87.80732699999984' in variables to replace them in a loop. inserting f{} did not help here is the full string payload = "{\"showPrice\":\"DISCOUNT\",\"searchRange\":80.467,\"points\":[{\"l...
[ "Quite difficult with strings.\nYou can switch payload to dict.\npayload = {'showPrice': 'DISCOUNT',\n 'searchRange': 80.467,\n 'points': [{'latitude': 41.86464600000019, 'longitude': -87.80732699999984}],\n 'cardNumber': 'blablabla',\n '_mt926720371': '3796524828557652229'}\n\n# a set of two (lat, lon) tuples just...
[ 0 ]
[]
[]
[ "python", "string", "variables" ]
stackoverflow_0074408604_python_string_variables.txt
Q: Parse XML to CSV when XML tag has child attributes I've written a small python app to print some XML tags and select child attributes. The XML are for electronic invoicing here in Mexico, here is an example of the XML: <?xml version="1.0" encoding="UTF-8"?><cfdi:Comprobante xmlns:cfdi="http://www.sat.gob.mx/cfd/4"...
Parse XML to CSV when XML tag has child attributes
I've written a small python app to print some XML tags and select child attributes. The XML are for electronic invoicing here in Mexico, here is an example of the XML: <?xml version="1.0" encoding="UTF-8"?><cfdi:Comprobante xmlns:cfdi="http://www.sat.gob.mx/cfd/4" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" V...
[ "It looks like your code is way more complicated than necessary.\nTry it this way:\nfrom lxml import etree\n\ncols = [\"Monto\",\"Fecha\",\"Descripcion\",\"RFC_Emisor\",\"Emisor\",\"UUID\",\"RFC_Receptor\",\"Receptor\"]\nrows = []\nrow =[]\nfor t in root.xpath('//*[@Total]'):\n row.extend((t.attrib.get(\"Total\"...
[ 0 ]
[]
[]
[ "pandas", "python", "xml", "xml_parsing" ]
stackoverflow_0074396442_pandas_python_xml_xml_parsing.txt
Q: aws sam deployment failed due to pip executable not found - python I am attempting to perform a sam deployment and upon running the command: sam build --template template.yaml --build-dir ./build --use-container I see that the image "amazon/aws-sam-cli-build-image-python3.6" is successfully pulled but then I obtai...
aws sam deployment failed due to pip executable not found - python
I am attempting to perform a sam deployment and upon running the command: sam build --template template.yaml --build-dir ./build --use-container I see that the image "amazon/aws-sam-cli-build-image-python3.6" is successfully pulled but then I obtain the following error: Build Failed Error: PythonPipBuilder:ResolveDepen...
[ "You need to install the pip for your python distribution\nlike this:\nsudo apt-get install python3-pip\n\nMore in this link: Python 3.6 No module named pip\n", "Ran into this same problem as well. The issue was that I needed to upgrade the version of Pip installed by Homebrew to 20.3, which uses Python's new scr...
[ 1, 0, 0, 0 ]
[]
[]
[ "amazon_web_services", "aws_lambda", "docker", "python" ]
stackoverflow_0064189929_amazon_web_services_aws_lambda_docker_python.txt
Q: Read multiple files and store filename as key and value as the contents of the file in python dictonary I currently have a list with the following filenames [file1, file2] I want to read each files by iterating through the list and read the contents of the file into dictionary So I am trying to create dictionary w...
Read multiple files and store filename as key and value as the contents of the file in python dictonary
I currently have a list with the following filenames [file1, file2] I want to read each files by iterating through the list and read the contents of the file into dictionary So I am trying to create dictionary with key and value as : thisisdict={ "file1" : "abcdefgh", "file2" :" defssfifj"} I am able to read and store ...
[ "This should be fairly easy, if I understand your requirement right.\nmy_dict = {}\nfor filename in ['file1.txt', 'file2.txt']:\n with open(filename, 'r') as f:\n _t = f.read()\n my_dict.update({filename: _t})\n\nOf course, this is a simple solution for small files, this can be done better if you h...
[ 0, 0 ]
[]
[]
[ "file_handling", "python" ]
stackoverflow_0074408699_file_handling_python.txt
Q: nx.set_node_attributes not adding the two attributes from either datafram or dict I need to create a graph object, with two attributes for each node. When I create this and add node attributes, I cannot correctly retrieve the values when I call specific nodes. The code I am using to create the graph object is as f...
nx.set_node_attributes not adding the two attributes from either datafram or dict
I need to create a graph object, with two attributes for each node. When I create this and add node attributes, I cannot correctly retrieve the values when I call specific nodes. The code I am using to create the graph object is as follows: nodes = pd.DataFrame(data=N) E = {'from': ['1','2', '1','5','D','D','D','03','...
[ "To answer my question, for those in the future. The following code added the attributes required:\nG = nx.from_pandas_edgelist(df, 'from', 'to', True, nx.DiGraph())\nnx.set_node_attributes(G, all_stations.set_index('node').to_dict('index'))\nG.nodes[\"Z\"]\n\nA slight change but successful result\n" ]
[ 0 ]
[]
[]
[ "networkx", "python" ]
stackoverflow_0074395704_networkx_python.txt
Q: i can't add select options to an existing selection field odoo 15 i have declared two selection fields x = fields.Selection([('x A','x A'),('x B','x B')],string='X') y = fields.Selection([('0','0')],string='Y') then i tried to add selection options to y field on onchange @api.onchange('x') def onchange_x(s...
i can't add select options to an existing selection field odoo 15
i have declared two selection fields x = fields.Selection([('x A','x A'),('x B','x B')],string='X') y = fields.Selection([('0','0')],string='Y') then i tried to add selection options to y field on onchange @api.onchange('x') def onchange_x(self): self.y = fields.Selection(selection_add = [('y A', 'y A')...
[ "You should never change selection array in run-time.\nSelection array for Selection fields should always be static.\nThis because odoo in background runs some migrations after installing the module, creating a support postgresql table where selection options are stored.\nYou can increase (using selection_add) it's...
[ 0 ]
[]
[]
[ "odoo", "odoo_15", "python", "xml" ]
stackoverflow_0074262627_odoo_odoo_15_python_xml.txt
Q: Correcting python code for using functions So huge disclaimer first: I am very new to python and programing in general, and this is my first time using functions. I would be very glad for any help, but the end goal here is not to have the prettiest or the most efficient code. I just want it to somehow work. I have...
Correcting python code for using functions
So huge disclaimer first: I am very new to python and programing in general, and this is my first time using functions. I would be very glad for any help, but the end goal here is not to have the prettiest or the most efficient code. I just want it to somehow work. I have written the program below but I can't get it to...
[ "In my first answer, I tried not to change too much code, but I think it will be easier to re-think the logic, and rewrite the code. Here's what I came up with, I think this does what you need?\nimport sys, re\n\n\ndef normalize(name):\n name = name.lower()\n name = re.sub('ä', 'ae', name)\n name = re.sub(...
[ 2 ]
[]
[]
[ "function", "list", "python", "regex", "regex_group" ]
stackoverflow_0074408248_function_list_python_regex_regex_group.txt
Q: Using Pysheds on non-square Raster I am using Pysheds for watershed delineation and displaying potential flow networks. Everything works well (like in the GitHub Readme) as long as the raster (TIFF) is square: But if I try to use a raster clipped to my desired extents, the code does not work anymore: The occurin...
Using Pysheds on non-square Raster
I am using Pysheds for watershed delineation and displaying potential flow networks. Everything works well (like in the GitHub Readme) as long as the raster (TIFF) is square: But if I try to use a raster clipped to my desired extents, the code does not work anymore: The occuring error is: File "...\Anaconda3\envs\g...
[ "I suspect it might have to do with the indexes pysheds creates in the background or maybe there are no points in the clipped raster that accumuluate over 1000 (have you checked the values for x_snap and y_snap?)\nCould you try to define x_snap and y_snap with the following (This should work, it does on a non recta...
[ 0 ]
[]
[]
[ "python", "raster", "watershed" ]
stackoverflow_0073335818_python_raster_watershed.txt
Q: How to implement a function through scikit FunctionTransformer() that refers to two columns of a data frame ('kw_args' argument?) while working on my submission for the famous Kaggle Titanic dataset (890 rows/11 columns) I would like to execute all of my 'Feature Engineering' steps within one scikit pipeline. Howe...
How to implement a function through scikit FunctionTransformer() that refers to two columns of a data frame ('kw_args' argument?)
while working on my submission for the famous Kaggle Titanic dataset (890 rows/11 columns) I would like to execute all of my 'Feature Engineering' steps within one scikit pipeline. However, I could barely find any online examples that demonstrate how to use the scikit FunctionTransformer() in order to execute slightly ...
[ "That warning is very common, and worth reading up on. But it's also not great to be looping over the rows of a dataframe. You can use pandas's own fillna for this:\ndef impute_age_class(df, fillme, groupby):\n df = df.copy()\n df.loc[:, fillme] = df[fillme].fillna(\n value=df[groupby].map(\n ...
[ 0 ]
[]
[]
[ "python", "scikit_learn" ]
stackoverflow_0073937751_python_scikit_learn.txt
Q: how to group by trade and not by time open high low close Volume ctime 2022-11-07 01:00:00.012000+01:00 20900.0 20900.0 20900.0 20900.0 209.00 2022-11-07 01:00:00.019000+01:00 20900.1 20900.1 20900.1 ...
how to group by trade and not by time
open high low close Volume ctime 2022-11-07 01:00:00.012000+01:00 20900.0 20900.0 20900.0 20900.0 209.00 2022-11-07 01:00:00.019000+01:00 20900.1 20900.1 20900.1 20900.1 1254.00 2022-11-07 01:00:00.1110...
[ "Define a new series that put the trades into groups of 5, then aggregate per group:\ntrade_group = np.arange(len(df)) // 5\n\n# The `open` of the group is the `open` of the first trade in the group\n# `high` is max of the `high` in the group\n# and so on...\ndf.groupby(trade_group).agg({\n \"open\": \"first\",\...
[ 0 ]
[]
[]
[ "pandas", "python", "trading" ]
stackoverflow_0074408676_pandas_python_trading.txt
Q: Groupby in Groupby and random Sampling import pandas as pd data = pd.DataFrame(data={'ID':[1, 1, 2, 2, 3, 3], 'prod':['A', 'B', 'C','D', 'E', 'F'], 'category':['cat1', 'cat1', 'cat1', 'cat1', 'cat2', 'cat2']}) How to randomly sample 1 ID per category to get for example:
Groupby in Groupby and random Sampling
import pandas as pd data = pd.DataFrame(data={'ID':[1, 1, 2, 2, 3, 3], 'prod':['A', 'B', 'C','D', 'E', 'F'], 'category':['cat1', 'cat1', 'cat1', 'cat1', 'cat2', 'cat2']}) How to randomly sample 1 ID per category to get for example:
[]
[]
[ "One solution is to loop over each group of category:\nimport random\ngroups_df = []\ngrouped = data.groupby(['category'])\n\nlist_of_groups = list(grouped.groups.keys())\n\nfor k in list_of_groups:\n group = grouped.get_group(k)\n l = group.ID.unique().tolist()\n group.reset_index(drop=True, inplace=True)...
[ -1 ]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074408492_dataframe_pandas_python.txt
Q: can't open file 'manager.py': [Errno 2] No such file or directory I'm trying to create an application using python and django, but this error keeps happening. What I've already tried: put python path and script in environment variables reinstall python reinstall django close and open vscode (I thought it was ...
can't open file 'manager.py': [Errno 2] No such file or directory
I'm trying to create an application using python and django, but this error keeps happening. What I've already tried: put python path and script in environment variables reinstall python reinstall django close and open vscode (I thought it was an update issue) run the server inside setup - the application folder ...
[ "You should run the right command which is:\npython manage.py runserver\n\n" ]
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074408888_django_python.txt