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: TypeError: string indices must be integers JSON with backslash I'm try to scraping JSON data from script tags. And I was able to extract data from it. My Code. import requests, json from bs4 import BeautifulSoup head = { "Accept": 'application/json, text/plain, */*', "Accept-Encoding": "gzip, deflate, br",...
TypeError: string indices must be integers JSON with backslash
I'm try to scraping JSON data from script tags. And I was able to extract data from it. My Code. import requests, json from bs4 import BeautifulSoup head = { "Accept": 'application/json, text/plain, */*', "Accept-Encoding": "gzip, deflate, br", "Accept-Language": "en-GB,en-US;q=0.9,en;q=0.8,km;q=0.7", "...
[ "script is JavaScript code, not JSON. Notice the window._SSR_HYDRATED_DATA= before the {. Everything after that can be treated as JSON (even though technically it isn't.) You have to deal with the variable assignment first. One way is to use split():\n_, my_json = script.split('=', maxsplit=1)\n\nNow you can use js...
[ 0 ]
[]
[]
[ "json", "python", "request", "web_scraping" ]
stackoverflow_0074549794_json_python_request_web_scraping.txt
Q: Python or math: How to count all possible combinations of a list's elements? Say there is a list [1,2,3,4,5], I would need to get the count of all possible combinations of the elements (or 'sub-lists'), e.g. 1, 2, 3, 4, 5, 12, 13, 14, ..., 123, 124, ..., 12345. I know how to get nCr, the count of combinations of r...
Python or math: How to count all possible combinations of a list's elements?
Say there is a list [1,2,3,4,5], I would need to get the count of all possible combinations of the elements (or 'sub-lists'), e.g. 1, 2, 3, 4, 5, 12, 13, 14, ..., 123, 124, ..., 12345. I know how to get nCr, the count of combinations of r elements of a list with total n elements. Python 3.8 or above: from math import c...
[ "This concept is called a power set in mathematics, and it refers to all subsets of a given set. Your question refers to the size of the power set which is 2^n where n is the size of your original set. This total includes the empty set, so as C4stor said, your total would be 2^n - 1.\nThe above answer works if the ...
[ 3, 0 ]
[]
[]
[ "math", "python" ]
stackoverflow_0074549925_math_python.txt
Q: Converting Intersystems cache objectscript into a python function I am accessing an Intersystems cache 2017.1.xx instance through a python process to get various attributes about the database in able to monitor the database. One of the items I want to monitor is license usage. I wrote a objectscript script in a Te...
Converting Intersystems cache objectscript into a python function
I am accessing an Intersystems cache 2017.1.xx instance through a python process to get various attributes about the database in able to monitor the database. One of the items I want to monitor is license usage. I wrote a objectscript script in a Terminal window to access license usage by user: s Rset=##class(%Resul...
[ "Following should work (based on the documentation):\nquery = intersys.pythonbind.query(database)\nquery.prepare_class(\"%SYSTEM.License\",\"UserListAll\")\nquery.execute();\n\n# Fetch each row in the result set, and print the\n# name and value of each column in a row: \nwhile 1:\n cols = query.fetch([None])\n ...
[ 0, 0, 0 ]
[]
[]
[ "caching", "intersystems", "python" ]
stackoverflow_0071573937_caching_intersystems_python.txt
Q: Why is the apple not spawning? My Problem As a new programmer, I tried to make Snake in Python, the most straightforward programming language (besides Scratch) using Pygame. I didn't understand the problem until now, and the Food (And the snake's death point) are going out of bounds from the game's display. What s...
Why is the apple not spawning?
My Problem As a new programmer, I tried to make Snake in Python, the most straightforward programming language (besides Scratch) using Pygame. I didn't understand the problem until now, and the Food (And the snake's death point) are going out of bounds from the game's display. What should I do? My code # Importing libr...
[]
[]
[ "As commented, the game works ok for me, however, I would swap the following lines:\n if x1 >= dis_width or x1 < 0 or y1 >= dis_height or y1 < 0:\n game_close = True\n x1 += x1_change\n y1 += y1_change\n\nIt makes more sense like this:\n x1 += x1_change\n y1 += y1_chang...
[ -1 ]
[ "pygame", "python" ]
stackoverflow_0074549810_pygame_python.txt
Q: Python folium - failed with extending functionality I would like to extend the functionality of my folium map I found a nice thread here: Python: How to extend Folium functionality (such as measuring distance) by using JS Leaflet inside python code? but it doesn't work when apply to my code export_js = [ ( ...
Python folium - failed with extending functionality
I would like to extend the functionality of my folium map I found a nice thread here: Python: How to extend Folium functionality (such as measuring distance) by using JS Leaflet inside python code? but it doesn't work when apply to my code export_js = [ ( "leaflet_bigimage_js", "js/Leaflet.BigImag...
[ "If you have the css and js files on the computer, you can use the branca library, that gets installed with folium to include the js and css elements.\nimport folium\nfrom branca.element import CssLink, JavascriptLink\nfrom pathlib import Path\n\njs_file = Path(\"/path/to/script.js\")\njs_link = JavascriptLink(js_f...
[ 0 ]
[]
[]
[ "folium", "python" ]
stackoverflow_0074545694_folium_python.txt
Q: create a python script in another python script and run it I have an python application which reads the python scripts and runs it and returns the values: main.py def Exec(id): try: connection = mysql.connector.connect(host='localhost', user='ro...
create a python script in another python script and run it
I have an python application which reads the python scripts and runs it and returns the values: main.py def Exec(id): try: connection = mysql.connector.connect(host='localhost', user='root', password='', ...
[ "create another file name fetchscript.py and in this file create the connection and fetch the script from your table , call fetchscript.py from main.py and then import pythonscript and call the desired function from pythonscript.py\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074545730_python.txt
Q: Matplotlib animate fill_between shape I am trying to animate a fill_between shape inside matplotlib and I don't know how to update the data of the PolyCollection. Take this simple example: I have two lines and I am always filling between them. Of course, the lines change and are animated. Here is a dummy example: ...
Matplotlib animate fill_between shape
I am trying to animate a fill_between shape inside matplotlib and I don't know how to update the data of the PolyCollection. Take this simple example: I have two lines and I am always filling between them. Of course, the lines change and are animated. Here is a dummy example: import matplotlib.pyplot as plt # Init plo...
[ "Ok, as someone pointed out, we are dealing with a collection here, so we will have to delete and redraw. So somewhere in the update_data function, delete all collections associated with it:\naxes_dummy.collections.clear()\n\nand draw the new \"fill_between\" PolyCollection:\naxes_dummy.fill_between(x, y-sigma, y+s...
[ 12, 5, 3, 0, 0, 0 ]
[]
[]
[ "animation", "matplotlib", "plot", "python" ]
stackoverflow_0016120801_animation_matplotlib_plot_python.txt
Q: ERROR: Could not build wheels for frozenlist, multidict, yarl, which is required to install pyproject.toml-based projects I'm trying to install discord.py , but I get this error out. pip updated immediately I say. I reinstalled python, pip and so on, I installed in pycharm both from PythonInterpreter and through t...
ERROR: Could not build wheels for frozenlist, multidict, yarl, which is required to install pyproject.toml-based projects
I'm trying to install discord.py , but I get this error out. pip updated immediately I say. I reinstalled python, pip and so on, I installed in pycharm both from PythonInterpreter and through the terminal please helpp \dfggfdgfdgfdgdf \fdggfddgfdgfgfd \fdgfdggfdgfdgfd \dfgdfgfdgdfg \fdgdfgfdgdfg \fdgfdgfdgfdg \dfgdfgdf...
[ "You probably have to investigate the error message in your log:\nMicrosoft Visual C++ 14.0 or greater is required. Get it with \"Microsoft C++ Build Tools\"\nHere is related question: Microsoft Visual C++ 14.0 is required. Get it with \"Microsoft Visual C++ Build Tools\"\n\nAlso the following may be helpful. I had...
[ 1 ]
[]
[]
[ "discord", "discord.py", "python" ]
stackoverflow_0074255709_discord_discord.py_python.txt
Q: Pandas Separate categorical and numeric features from multiple data frames and store in a new data frame I have a situation where I want to separate categorical and numeric features from multiple data frames as mentioned below (df1,df2,df3, and df4) and I want to store these in two different data frames with names...
Pandas Separate categorical and numeric features from multiple data frames and store in a new data frame
I have a situation where I want to separate categorical and numeric features from multiple data frames as mentioned below (df1,df2,df3, and df4) and I want to store these in two different data frames with names "Cont" and "Cat". I am looking for a process that loops into these multiple data frames and gives the output ...
[ "You can use pandas.DataFrame.select_dtypes to create the two dataframes.\nTry this:\nout = pd.concat([df1, df2, df3, df4], axis=1)\n​\ncat= out.select_dtypes(include=\"object\") #or include=\"category\"\ncont= out.select_dtypes(include=np.number)\n\n# Output :\nprint(cat)\n Name1 Name2 Name3 Name4\n0 ABC ABCD ...
[ 1 ]
[]
[]
[ "data_wrangling", "dataframe", "dtype", "pandas", "python" ]
stackoverflow_0074550006_data_wrangling_dataframe_dtype_pandas_python.txt
Q: Pasting .bin image files into excel using openpyxl I've been trying to write a script to fetch images and paste them all together into one file. For this I use ZipFile from zipfile to extract .bin image files from a collection of .xlsx files and I planned to use openpyxl to paste them all into one new .xlsx file. ...
Pasting .bin image files into excel using openpyxl
I've been trying to write a script to fetch images and paste them all together into one file. For this I use ZipFile from zipfile to extract .bin image files from a collection of .xlsx files and I planned to use openpyxl to paste them all into one new .xlsx file. When I run this, I end up getting a KeyError: '.wmf'. I ...
[ "I actually found a way to do it without openpyxl. Python has a build-in library xlsxwriter which can handle .wmf files and allows it to paste the .bin files as well.\nimport xlsxwriter as xw\n\nwb = xw.Workbook('imgsave/combined images.xlsx')\nws = wb.add_worksheet()\n\nimagelist = [img for img in os.listdir('xl/m...
[ 0 ]
[]
[]
[ "bin", "excel", "openpyxl", "python" ]
stackoverflow_0074547563_bin_excel_openpyxl_python.txt
Q: Kill all "workers" on "listener" error (multiprocessing, manager and queue set-up) I'm using multiprocessing to run workers on different files in parallel. Worker's results are put into queue. A listener gets the results from the queue and writes them to the file. Sometimes listener might run into errors (of vario...
Kill all "workers" on "listener" error (multiprocessing, manager and queue set-up)
I'm using multiprocessing to run workers on different files in parallel. Worker's results are put into queue. A listener gets the results from the queue and writes them to the file. Sometimes listener might run into errors (of various origins). In this case, the listener silently dies, but all other processes continue ...
[ "As always there are many ways to accomplish what you're after, but I would probably suggest using an Event to signal that the processes should quit. I also would not use a Pool in this instance, as it only really simplifies things for simple cases where you need something like map. More complicated use cases quick...
[ 1 ]
[]
[]
[ "error_handling", "multiprocessing", "python", "python_3.x", "queue" ]
stackoverflow_0074548611_error_handling_multiprocessing_python_python_3.x_queue.txt
Q: How to globally override a pythonPackage in nix I'm trying to override a python package (uvloop) globally, in nix, such that black sees the override. uvloop (python package) tests fail for me because I'm working behind a firewall. I can build things that use uvloop by editing the nixpkgs derivation directly (ugh)...
How to globally override a pythonPackage in nix
I'm trying to override a python package (uvloop) globally, in nix, such that black sees the override. uvloop (python package) tests fail for me because I'm working behind a firewall. I can build things that use uvloop by editing the nixpkgs derivation directly (ugh) to set doCheck = false. I'm trying to encode this in...
[ "The following worked for me. It applies a patch to twitch-chat-downloader (Python app) and a patch to twitch-python (Python library used by twitch-chat-downloader). nix-env -iA nixpkgs.twitch-chat-downloader installed a patch copy of twitch-chat-downloader which uses a patched copy of twitch-python.\n{\n packageO...
[ 0, 0 ]
[]
[]
[ "nix", "python" ]
stackoverflow_0070395839_nix_python.txt
Q: Can someone help me with this simple calculator program in python? I am having problem in finding error Program got a Syntax error as follow: elif choice == "3": ^^^^ SyntaxError: invalid syntax print("1 Addition\n2 Subtraction\n3 Multiplication\n4 Division ") choice= input ("WHat is you choice? : ") num1 = float ...
Can someone help me with this simple calculator program in python? I am having problem in finding error
Program got a Syntax error as follow: elif choice == "3": ^^^^ SyntaxError: invalid syntax print("1 Addition\n2 Subtraction\n3 Multiplication\n4 Division ") choice= input ("WHat is you choice? : ") num1 = float (input("Please enter a number: ")) num2 = float( input("please enter another number: ")) if choice == "1": ...
[ "Variable names are case sensitive (\"num1\" cannot be referenced as \"Num1\")\nIndentation on elif should be inline with the original \"if\"\nMissing colon on if statement on line 13.\nHere is an altered version that worked for me:\nprint(\"1 Addition\\n2 Subtraction\\n3 Multiplication\\n4 Division \")\nchoice= in...
[ -1 ]
[ "You need to unindent the elif statements like:\nprint(\"1 Addition\\n2 Subtraction\\n3 Multiplication\\n4 Division \")\nchoice= input(\"What is you choice? : \")\nnum1 = float(input(\"Please enter a number: \"))\nnum2 = float(input(\"please enter another number: \"))\n\nif choice == \"1\":\n print(f\"{Num1}+{Nu...
[ -2 ]
[ "python", "syntax_error" ]
stackoverflow_0074549960_python_syntax_error.txt
Q: When to utilize pandas .filter() over other subsetting methods? I've been studying the different ways to filter and subset pandas DataFrames and came across the pandas.DataFrame.filter() method. However, I can't figure out why one would use this over another method of filtering (loc, iloc, logical operators, str.c...
When to utilize pandas .filter() over other subsetting methods?
I've been studying the different ways to filter and subset pandas DataFrames and came across the pandas.DataFrame.filter() method. However, I can't figure out why one would use this over another method of filtering (loc, iloc, logical operators, str.contains(), .query(), etc). Can anyone provide an example of when it m...
[ "filter is applied to index or column labels, not the values.\nIn contrast to query, contains etc. which are used to filter a DataFrame based on its contents.\nIf you for example would like to only keep columns ending with 'address', you could use df.filter(regex='address$')\n", "\nEach function is used in partic...
[ 0, 0 ]
[]
[]
[ "dataframe", "filter", "pandas", "python" ]
stackoverflow_0069182663_dataframe_filter_pandas_python.txt
Q: Pygame not importing, tried all techniques I have read some of the Stack Overflow posts here about pygame not importing. I have tried moving pygame in the scripts folder of Python, making sure it is the right type, and installing it using anaconda prompt. Do you know why none of these are working? By the way, her...
Pygame not importing, tried all techniques
I have read some of the Stack Overflow posts here about pygame not importing. I have tried moving pygame in the scripts folder of Python, making sure it is the right type, and installing it using anaconda prompt. Do you know why none of these are working? By the way, here's my code and error. I have Windows 10, 64 bit...
[ "make sure you installed the library in same python version where you are coding. if you don't know how to do that type this in python code and run it\nimport pip\npip.main([\"install\",\"pygame\"])\n\nif it does not work too you should probably upgrade python to 3.10\n" ]
[ 0 ]
[ "some users arent run pygame command.after showing requirement message.if you download pygame copy that 2 folder named as\"pygame\"and\"pygame-1.9.4.dist-info\"socopy this folder to your\"C:\\Program Files (x86)\\Python37-32\\Lib\" seriously after that u r DONE!!!!!!!!\n" ]
[ -2 ]
[ "import", "pygame", "python", "python_2.7", "python_import" ]
stackoverflow_0045224990_import_pygame_python_python_2.7_python_import.txt
Q: pyqt5: This application failed to start because no Qt platform plugin could be initialized - installation problem? I am working on Ubuntu 18.04 (as a Windows 10 subsystem for linux). When I try running code that uses pyqt5 it throws the error: " qt.qta.xcb: could not connect to display qt.qpa.plugin: Could not loa...
pyqt5: This application failed to start because no Qt platform plugin could be initialized - installation problem?
I am working on Ubuntu 18.04 (as a Windows 10 subsystem for linux). When I try running code that uses pyqt5 it throws the error: " qt.qta.xcb: could not connect to display qt.qpa.plugin: Could not load the Qt platform plugin "xcb" in "" even though it was found. This application failed to start because no Qt platform p...
[ "Someone suggested to run \"xhost +local:\" first.\n", "The error relates to a missing requirement for one or multiple XCB-related libraries, which needs to be fulfilled on X11 for Qt to function properly. For a full list of XCB libraries check here.\nI would suggest that, instead of copying files left and right,...
[ 2, 1, 0, 0, 0 ]
[]
[]
[ "pyqt", "pyqt5", "python", "qt", "user_interface" ]
stackoverflow_0072378976_pyqt_pyqt5_python_qt_user_interface.txt
Q: Using the same hotkey for two different purposes in Python Using pythons keyboard library, I have two function definitions: def start_tracking(): *code to start tracking time* def end_tracking(): *code to stop tracking time* I then want to use the same hotkey (e.g. F1) to invoke function 1 (start tracking time...
Using the same hotkey for two different purposes in Python
Using pythons keyboard library, I have two function definitions: def start_tracking(): *code to start tracking time* def end_tracking(): *code to stop tracking time* I then want to use the same hotkey (e.g. F1) to invoke function 1 (start tracking time) on the first press and then function 2 (end tracking time) on ...
[ "Consider using a class variable or global variable as a flag. Such that:\nclass tracker():\n\n def __init__(self):\n self.start_flag = True <- Init class variable\n\n def tracking(self):\n\n if self.start_flag:\n start_tracking()\n self.start_flag = False #<- class va...
[ 0, 0 ]
[]
[]
[ "keyboard", "python" ]
stackoverflow_0074549843_keyboard_python.txt
Q: The program should display ‘Out of range’ if credits entered are not in the range 0, 20, 40, 60, 80, 100 and 120 To try to solve the question above I tried by creating a list with the range and then a list with the variables in it. Then to check if the variables are in the list i used an if loop however it is not...
The program should display ‘Out of range’ if credits entered are not in the range 0, 20, 40, 60, 80, 100 and 120
To try to solve the question above I tried by creating a list with the range and then a list with the variables in it. Then to check if the variables are in the list i used an if loop however it is not working and only printing out "out of range...". I have also tried a while loop and it would just repeat the total 7 ...
[ "Testing whether one set of numbers is in another is a set operation. So use set and subtract all of the valid values from your input. If any values remain, they are not valid.\na = set([0, 20, 40, 60, 80, 100, 120])\nif set([userPass, userFail, userDefer]) - a:\n print(\"Out of range. Try again\")\n \n\nInte...
[ 0, 0 ]
[]
[]
[ "for_loop", "loops", "python" ]
stackoverflow_0074550104_for_loop_loops_python.txt
Q: How to solve TypeError: 'int' object is not iterable in Python while calculating sum of two numbers? I am trying to take two values as parameters and return True if its value is equal to 10 and false if it isn't. The values are strictly int. Here is the code class Solution: def twomakes10(self, no1, no2): ...
How to solve TypeError: 'int' object is not iterable in Python while calculating sum of two numbers?
I am trying to take two values as parameters and return True if its value is equal to 10 and false if it isn't. The values are strictly int. Here is the code class Solution: def twomakes10(self, no1, no2): if sum(no1, no2) == 10: return True else: return False if __nam...
[ "sum function, gets an iterable value as input, you can try:\nsum([no1,no2])\n\n", "sum is expecting iterable .. so make it happy. See below\nclass Solution:\n\n def twomakes10(self, no1, no2):\n return sum([no1, no2])\n\n\nif __name__ == \"__main__\":\n p = Solution()\n n1 = 9\n n2 = 1\n pr...
[ 1, 0 ]
[]
[]
[ "list", "python", "tuples" ]
stackoverflow_0074550268_list_python_tuples.txt
Q: Add comma between text I have a list of addresses in a text document and I want to add a comma after address line 1, and then save it all to a new text document. example my list of addresses are Address 1404 756 48 Stockholm Address 9 756 52 Stockholm Address 53 B lgh 1001 619 34 Stockholm Address 72 B lgh 1101 61...
Add comma between text
I have a list of addresses in a text document and I want to add a comma after address line 1, and then save it all to a new text document. example my list of addresses are Address 1404 756 48 Stockholm Address 9 756 52 Stockholm Address 53 B lgh 1001 619 34 Stockholm Address 72 B lgh 1101 619 30 Stockholm Address 52 A ...
[ "With regexp\nimport re\nre.sub(r'\\s(\\d{3}\\s\\d{2}\\s.*)$', ', \\\\1', 'Address 53 B lgh 1001 619 34 Stockholm')\n# 'Address 53 B lgh 1001, 619 34\\xa0Stockholm'\n\n(the \\xa0 is part of your strings. It will print as a space)\n", "You can use str.rstrip() to separate city and index from the first line:\nfile_...
[ 2, 0, 0, 0, -1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074548921_python_python_3.x.txt
Q: How to check if key exists inside JSON file, if the key is inside an Array in JSON (ROBOT FRAMEWORK) So I am facing this problem, where I need to check if the key exists in my JSON file, and continue my actions based on that. So I am doing Add Item To JSON [Documentation] This keyword is designed to add an...
How to check if key exists inside JSON file, if the key is inside an Array in JSON (ROBOT FRAMEWORK)
So I am facing this problem, where I need to check if the key exists in my JSON file, and continue my actions based on that. So I am doing Add Item To JSON [Documentation] This keyword is designed to add an Item to JSON file [Arguments] ${json_file} ${item_ref} ${item_details} Create ...
[ "@The Leviathan, I am not so familiar with robotframework but consider the following python recursion:\ndef check_keys(search_key,data):\n return_value = False\n for key,value in data.items():\n if search_key == key:\n return_value = True\n else: \n dict_test = check_lis...
[ 0 ]
[]
[]
[ "arrays", "collections", "json", "python", "robotframework" ]
stackoverflow_0074478356_arrays_collections_json_python_robotframework.txt
Q: Creating nested list with different shapes with numpy I want to create a list of lists of random numbers, h[i,j,k], with axes of different lenghts. For that I have tried import numpy as np import random as rng NBR1 = 2 NBR2 = [2,3,1] list = np.array([np.array([np.array([rng.uniform(-1,1) for k in range(NBR2[...
Creating nested list with different shapes with numpy
I want to create a list of lists of random numbers, h[i,j,k], with axes of different lenghts. For that I have tried import numpy as np import random as rng NBR1 = 2 NBR2 = [2,3,1] list = np.array([np.array([np.array([rng.uniform(-1,1) for k in range(NBR2[i+1])]) for j in range(NBR2[i])]) for i in range(NBR1)]) W...
[ "Is the following what you are looking for (a list of np.arrays)?\nnp.random.seed(0) # for reproducible example --remove when using\nlst = [np.random.uniform(-1, 1, size) for size in zip(NBR2, NBR2[1:])]\n\n>>> lst\n[array([[ 0.09762701, 0.43037873, 0.20552675],\n [ 0.08976637, -0.1526904 , 0.29178823]])...
[ 0 ]
[]
[]
[ "numpy_ndarray", "numpy_slicing", "python" ]
stackoverflow_0074548489_numpy_ndarray_numpy_slicing_python.txt
Q: Why does my Heroku app say my app is using Postgresql? Since Heroku is removing its free tier, I'm currently in the process of upgrading. However it says that my web app will be turned into an eco dyno, and my postgresql will be switched to "mini". I do not use any database in my app, and am not sure why it shows ...
Why does my Heroku app say my app is using Postgresql?
Since Heroku is removing its free tier, I'm currently in the process of upgrading. However it says that my web app will be turned into an eco dyno, and my postgresql will be switched to "mini". I do not use any database in my app, and am not sure why it shows up. Will Heroku shut down my app if I don't pay an additiona...
[ "You may have a Postgres instance that was automatically provisioned:\n\nBefore you provision Heroku Postgres, confirm that it isn't already provisioned for your app. Heroku automatically provisions Postgres for apps that include certain libraries, such as the pg Ruby gem.\n\nI believe the psycopg2 Python module al...
[ 0 ]
[]
[]
[ "django", "dyno", "heroku", "heroku_postgres", "python" ]
stackoverflow_0074549830_django_dyno_heroku_heroku_postgres_python.txt
Q: How to check if string of group in pandas is contained in another string of the same group in pandas I have this sample of dataframe | identifier | span | matched_string | | -------- | -------------- | ------ | | occupation | [0,12] | general manager| | occupation | [0,7] ...
How to check if string of group in pandas is contained in another string of the same group in pandas
I have this sample of dataframe | identifier | span | matched_string | | -------- | -------------- | ------ | | occupation | [0,12] | general manager| | occupation | [0,7] | manager | | time schedule | [13,14] | "0-5" | | occupation | [0,12]. ...
[ "I solved the problem by subdividing the for loops into functions and let them return True. Then I dropped those rows by index where both functions returned True.\nThis is my solution:\ntesta = df.groupby([\"job_title_index\", \"identifier\"])\n\n#check if string matches are contained in the same span\ndef same_spa...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074546016_dataframe_pandas_python.txt
Q: Xarray find lat/lon coordinates for maximum/minimum values for each timestep As the title says, supposing I have a ds with coords: [time lat lon], how can I obtain for each timestep in time the pair of ['lat','lon'] in which the maximum(or minimum) value for a given variable is located. A: Use xr.Dataset.idxmax ...
Xarray find lat/lon coordinates for maximum/minimum values for each timestep
As the title says, supposing I have a ds with coords: [time lat lon], how can I obtain for each timestep in time the pair of ['lat','lon'] in which the maximum(or minimum) value for a given variable is located.
[ "Use xr.Dataset.idxmax to find the index label of the maximum along a dimension (one at a time). Same for xr.Dataset.idxmin.\nmax_lons = ds.max(dim=\"lat\").idxmax(dim=\"lon\")\nmax_lats = ds.max(dim=\"lon\").idxmax(dim=\"lat\")\n\nThe results will be datasets, with each variable giving the lon or lat coresponding ...
[ 2 ]
[]
[]
[ "python", "python_xarray" ]
stackoverflow_0074547978_python_python_xarray.txt
Q: Create new columns using unique values in other columns in Python I'd like to create new columns in my dataframe using unique values from another column, for example Column 1 has the following values: Apple Apple Banana Strawberry Strawberry Strawberry When I check unique values in Column 1, the output would be :...
Create new columns using unique values in other columns in Python
I'd like to create new columns in my dataframe using unique values from another column, for example Column 1 has the following values: Apple Apple Banana Strawberry Strawberry Strawberry When I check unique values in Column 1, the output would be : Apple Banana Strawberry Now I want to use these three values to creat...
[ "extract unique values, iterate on them to create columns and fill in data.\nHere I inly put boolean values based on matching with the col1 value ...\ndf = pd.DataFrame({\"col1\": [\"apple\", \"apple\", \"banana\", \"pineapple\", \"banana\", \"apple\"]})\n\ndata=\n col1\n0 apple\n1 apple\n2 ban...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074550091_dataframe_pandas_python.txt
Q: can't fix weird characters when saving to .json file from python I'm trying to save a text from python but it generates strange characters "\u00f1" and I don't know how to eliminate this This is the code I'm using: with open("NoticiasHabboHotel.json", "w") as f: json.dump(test_versions, f, indent=0, sepa...
can't fix weird characters when saving to .json file from python
I'm trying to save a text from python but it generates strange characters "\u00f1" and I don't know how to eliminate this This is the code I'm using: with open("NoticiasHabboHotel.json", "w") as f: json.dump(test_versions, f, indent=0, separators=(',', ': ')) This is the text that generates me: Dise\u00f1ad...
[ "See: https://docs.python.org/3/library/json.html#basic-usage\nYou need to add ensure_ascii=False because ñ is a non-ASCII character\nwith open(\"NoticiasHabboHotel.json\", \"w\") as f:\n json.dump(test_versions, f, indent=0, separators=(',', ': '), ensure_ascii=False)\n\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074549987_python.txt
Q: use OpenMaya to give particles specific translate and rotate values I'm struggling with OpenMaya here. I want to be able to take transform information from a list of locators and plug these values to particles shapes. The goal is to use this over 25000 locators, so I can't create a particle system for each instanc...
use OpenMaya to give particles specific translate and rotate values
I'm struggling with OpenMaya here. I want to be able to take transform information from a list of locators and plug these values to particles shapes. The goal is to use this over 25000 locators, so I can't create a particle system for each instance. I really need to store position and rotation values to the particles t...
[ "I've made a couple of changes to make it work. I didn't check the particle setup though. In fact, the main problem is mixing two different APIs. Either stick to OpenMaya (or even OpenMaya v2.0) or PyMEL.\nimport pymel.core as pm\nimport maya.OpenMaya as om\nimport maya.OpenMayaFX as omfx\n\nimport random\n\n### A ...
[ 0, 0 ]
[]
[]
[ "maya", "maya_api", "python" ]
stackoverflow_0074539366_maya_maya_api_python.txt
Q: cimpl.KafkaException: KafkaError{code=_INVALID_ARG,val=-186,str="No such configuration property: "bootstrap_servers""} I am trying to produce AVRO data to Kafka topic through python producer script, I already installed python dependencies avro-python3 and confluent_kafka, however when running this script i got bel...
cimpl.KafkaException: KafkaError{code=_INVALID_ARG,val=-186,str="No such configuration property: "bootstrap_servers""}
I am trying to produce AVRO data to Kafka topic through python producer script, I already installed python dependencies avro-python3 and confluent_kafka, however when running this script i got below error: File "./kafka_producer_avro.py", line 24, in <module> kafka_producer_obj = Producer(kafka_config_obj) cimpl...
[ "Your shown error has nothing to do with OS packages.\nIt's bootstrap.servers, not with an underscore. Also, the Kafka module is with hyphen, not underscore.\nDocs - https://docs.confluent.io/kafka-clients/python/current/overview.html\nYou can additionally install fastavro with pip.\n" ]
[ 0 ]
[]
[]
[ "apache_kafka", "confluent_kafka_python", "python" ]
stackoverflow_0074547844_apache_kafka_confluent_kafka_python_python.txt
Q: Pandas interpolate within a groupby for one column Similar to this question Pandas interpolate within a groupby but the answer to that question does the interpolate() for all columns. If I only want to limit the interpolate() to one column how do I do that? Input filename val1 val2 t 1...
Pandas interpolate within a groupby for one column
Similar to this question Pandas interpolate within a groupby but the answer to that question does the interpolate() for all columns. If I only want to limit the interpolate() to one column how do I do that? Input filename val1 val2 t 1 file1.csv 5 10 2 file1.csv NaN NaN 3 ...
[ "A direct approach:\ndf = pd.read_clipboard() # clipboard contains OP sample data\n# interpolate only on col \"val2\"\ndf[\"val2_interpolated\"] = df[[\"filename\",\"val2\"]].groupby('filename')\n.apply(lambda x:x) # WTF\n.interpolate(method='linear')[\"val2\"]\n\nreturns:\n filename val1 val2 val2_interpolat...
[ 0 ]
[]
[]
[ "dataframe", "group_by", "interpolation", "pandas", "python" ]
stackoverflow_0074550482_dataframe_group_by_interpolation_pandas_python.txt
Q: How to retain attributes of inherited Spark DataFrame Class following a Spark operation on that class I create a new class called NewDataFrame with attribute a_string: import numpy as np import pandas as pd from pyspark.sql import DataFrame class NewDataFrame(DataFrame): def __init__(self, df): super...
How to retain attributes of inherited Spark DataFrame Class following a Spark operation on that class
I create a new class called NewDataFrame with attribute a_string: import numpy as np import pandas as pd from pyspark.sql import DataFrame class NewDataFrame(DataFrame): def __init__(self, df): super().__init__(df._jdf,df.sql_ctx) self.a_string = "Hello, World." I use the class on some data and a...
[ "I have tried the same inheritance in Python with no success. The PySpark dataframe has been implemented in a such way to return the Dataframe object after performing the operations. You can look at the source code and see how it has been done:\nhttps://github.com/apache/spark/blob/master/python/pyspark/sql/datafra...
[ 0 ]
[]
[]
[ "class", "dataframe", "inheritance", "pyspark", "python" ]
stackoverflow_0071376315_class_dataframe_inheritance_pyspark_python.txt
Q: Python IPython Turning variables to strings I have a function that creates new Jupyter Notebook cells and I'm trying to use a loop to show value counts for each column and the specific difficulty I have is having them return with the column names in quotes. Here's what I have: def create_new_cell(contents): sh...
Python IPython Turning variables to strings
I have a function that creates new Jupyter Notebook cells and I'm trying to use a loop to show value counts for each column and the specific difficulty I have is having them return with the column names in quotes. Here's what I have: def create_new_cell(contents): shell = get_ipython() payload = dict( s...
[ "You forgot curly brackets.\nYou need to use them to replace the field with the variable.\ncol = f'{col}'\nTest code\ncol = 'column'\ncol = f'{col}'\nprint(col)\n\n", "So I just found the answer. I had to use Pretty Print.\ndef show_vc(col):\n col = pformat(col)\n #col = f'({col})'\n content = \"df[{col_...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074549942_python.txt
Q: How to return the sum for each string value in excel sheet? I try to return the sum for every fruit item. So I have a excel sheet with column E(5) and then for every row there is a value. So the row:ananas(6,7,8) has the values: 1596, 1309,1057 = total: 3962 So I have it like this: import openpyxl import tabula e...
How to return the sum for each string value in excel sheet?
I try to return the sum for every fruit item. So I have a excel sheet with column E(5) and then for every row there is a value. So the row:ananas(6,7,8) has the values: 1596, 1309,1057 = total: 3962 So I have it like this: import openpyxl import tabula excelWorkbook = openpyxl.load_workbook(path, data_only=True) def c...
[ "You could use a dictionary to keep a running tally of sums while you iterate through the values.\nfruit_sums = {\n 'ananas': 0,\n 'apple': 0,\n 'waspeen': 0,\n}\n\nI would recommend converting all excel values to a python array.\narray = [row for row in sheet_factuur.values]\n\nIterate through values and ...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074549977_python.txt
Q: How to remove numbers from a string column that starts with 4 zeros? I have a column of names and informations of products, i need to remove the codes from the names and every code starts with four or more zeros, some names have four zeros or more in the weight and some are joined with the name as the example belo...
How to remove numbers from a string column that starts with 4 zeros?
I have a column of names and informations of products, i need to remove the codes from the names and every code starts with four or more zeros, some names have four zeros or more in the weight and some are joined with the name as the example below: data = { 'Name' : ['ANOA 250g 00004689', 'ANOA 10000g 00000059884',...
[ "Use a regex with str.replace:\ntestdf['Name'] = testdf['Name'].str.replace(r'(?:(?<=\\D)|\\s*\\b)0{4}\\d*',\n '', regex=True)\n\nOr, similar to @HaleemurAli, with a negative match\ntestdf['Name'] = testdf['Name'].str.replace(r'(?<!\\d)0{4,}0{4}\\d*',\n ...
[ 3, 3 ]
[ "try splitting it at each space and checking if the each item has 0000 in it like:\nanswer=[]\nfor i in results[\"Name\"]:\n answer.append(\"\".join([j for j in i.split() if \"0000\" not in j]))\n\n" ]
[ -1 ]
[ "pandas", "python" ]
stackoverflow_0074550291_pandas_python.txt
Q: Django CountryField, query by country I have a class similar to this: class Person(models.Model): name = CharField(max_length=255) citizenship = CountryField(multiple=True) In this example a Person can have more than one citizenship. Person.objects.create(name="Fred Flinstone", citizenship="US...
Django CountryField, query by country
I have a class similar to this: class Person(models.Model): name = CharField(max_length=255) citizenship = CountryField(multiple=True) In this example a Person can have more than one citizenship. Person.objects.create(name="Fred Flinstone", citizenship="US, CA") I want to query for everyone who ha...
[ "Try this out:\n Person.objects.filter(citizenship__contains=\"US\")\n\nAlso check out the django-countries code, especially tests, if my suggestion is not exactly what you are searching for, I am sure you will find answer there:\nLink to tests\n" ]
[ 1 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0074550230_django_django_models_python.txt
Q: Divide click commands into sections in cli documentation This code: #!/usr/bin env python3 import click def f(*a, **kw): print(a, kw) commands = [click.Command("cmd1", callback=f), click.Command("cmd2", callback=f)] cli = click.Group(commands={c.name: c for c in commands}) if __name__ == "__main__": c...
Divide click commands into sections in cli documentation
This code: #!/usr/bin env python3 import click def f(*a, **kw): print(a, kw) commands = [click.Command("cmd1", callback=f), click.Command("cmd2", callback=f)] cli = click.Group(commands={c.name: c for c in commands}) if __name__ == "__main__": cli() generates this help: # Usage: cli.py [OPTIONS] COMMAN...
[ "If you define your own group class you can overide the help generation like:\nCustom Class:\nclass SectionedHelpGroup(click.Group):\n \"\"\"Sections commands into help groups\"\"\"\n\n def __init__(self, *args, **kwargs):\n self.grouped_commands = kwargs.pop('grouped_commands', {})\n commands =...
[ 3, 0 ]
[]
[]
[ "command_line_interface", "python", "python_click" ]
stackoverflow_0057066951_command_line_interface_python_python_click.txt
Q: Test Google Cloud Function Im asked to test a Google Cloud Function triggered by http through cloud shell using the "curl -m 60 -X GET [url_of_your_function]" commnand. Does anyone know where to find the url of my function? Ive tried the main url of it and many other ideas but get not solution. I cannot find any d...
Test Google Cloud Function
Im asked to test a Google Cloud Function triggered by http through cloud shell using the "curl -m 60 -X GET [url_of_your_function]" commnand. Does anyone know where to find the url of my function? Ive tried the main url of it and many other ideas but get not solution. I cannot find any documentation on Google Cloud as ...
[ "See Function URL on the documentation for Cloud Functions.\nThe way to parse the describe result depends on whether you're using 1st or 2nd gen.\nOnce you have the URL, assuming it requires auth, you can:\nENDPOINT=\"$(gcloud functions describe ... )\"\nTOKEN=\"$(gcloud auth print-identity-token)\"\n\ncurl \\\n--g...
[ 2 ]
[]
[]
[ "google_cloud_functions", "google_cloud_platform", "google_cloud_shell", "python" ]
stackoverflow_0074549234_google_cloud_functions_google_cloud_platform_google_cloud_shell_python.txt
Q: Popen from python to Cpp process I am trying to create a python script that will send lines into a cpp file running on a while loop and printing the lines received into the console. test.py #test.py import subprocess p = subprocess.Popen('./stdin.out',bufsize=1,stdin=subprocess.PIPE,stdout=subprocess.DEVNULL, std...
Popen from python to Cpp process
I am trying to create a python script that will send lines into a cpp file running on a while loop and printing the lines received into the console. test.py #test.py import subprocess p = subprocess.Popen('./stdin.out',bufsize=1,stdin=subprocess.PIPE,stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, universal_newl...
[ "You have two problems. The first is that the python script terminates the subprocess before it has a chance to run. The second is that you pipe stdout and err to DEVNULL, so even if it did run, you wouldn't see anything. Normally, when you are done communicating with a subprocess, you close stdin. The subprocess c...
[ 1 ]
[]
[]
[ "c++", "python", "subprocess" ]
stackoverflow_0074549489_c++_python_subprocess.txt
Q: ERROR: Could not build wheels for aiohttp, which is required to install pyproject.toml-based projects Python version: 3.11 Installing dependencies for an application by pip install -r requirements.txt gives the following error: socket.c -o build/temp.linux-armv8l-cpython-311/aiohttp/_websocket.o aiohttp/_websocket...
ERROR: Could not build wheels for aiohttp, which is required to install pyproject.toml-based projects
Python version: 3.11 Installing dependencies for an application by pip install -r requirements.txt gives the following error: socket.c -o build/temp.linux-armv8l-cpython-311/aiohttp/_websocket.o aiohttp/_websocket.c:198:12: fatal error: 'longintrepr.h' file not found #include "longintrepr.h" ...
[ "Solution for this error: need to update requirements.txt.\nNot working versions of modules with Python 3.11:\naiohttp==3.8.1\nyarl==1.4.2\nfrozenlist==1.3.0\n\nWorking versions:\naiohttp==3.8.2\nyarl==1.8.1\nfrozenlist==1.3.1\n\nLinks to the corresponding issues with fixes:\n\nhttps://github.com/aio-libs/aiohttp/i...
[ 0 ]
[]
[]
[ "aiohttp", "linux", "pip", "python", "termux" ]
stackoverflow_0074550830_aiohttp_linux_pip_python_termux.txt
Q: Django user is_authenticated vs. is_active: when should I use one or the other? After reading the documentation, I still don't fully grasp the difference between these two User methods: is_active and is_authenticated. Both are returning a boolean. While is_authenticated is read-only (and you get an error if you tr...
Django user is_authenticated vs. is_active: when should I use one or the other?
After reading the documentation, I still don't fully grasp the difference between these two User methods: is_active and is_authenticated. Both are returning a boolean. While is_authenticated is read-only (and you get an error if you try to set it), is_active can be modified and for instance you can set it to False inst...
[ "is_active is an attribute on user accounts which can be flipped on and off. You can do that in the admin interface, or programmatically. Only active users are allowed to log in. I.e. you can use the is_active flag to prevent a user from logging in without needing to change their password, delete their account, or ...
[ 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074550184_django_python.txt
Q: pygame surface isn't visible I'm currently trying to follow the Introduction to Pygame tutorial and I'm stuck on one step where the speaker makes the surface. His surface is bright red while my surface isn't visible at all. Here's the code: import pygame from sys import exit pygame.init() screen = pygame.display....
pygame surface isn't visible
I'm currently trying to follow the Introduction to Pygame tutorial and I'm stuck on one step where the speaker makes the surface. His surface is bright red while my surface isn't visible at all. Here's the code: import pygame from sys import exit pygame.init() screen = pygame.display.set_mode((800, 400)) pygame.displa...
[ "It is a matter of indentation. You have draw the scene and update the display in the application loop:\nimport pygame\nfrom sys import exit\n\npygame.init()\nscreen = pygame.display.set_mode((800, 400))\npygame.display.set_caption('Runner')\nclock = pygame.time.Clock()\n\ntest_surface = pygame.Surface((100, 200))\...
[ 0 ]
[]
[]
[ "pygame", "pygame_surface", "python" ]
stackoverflow_0074550877_pygame_pygame_surface_python.txt
Q: Not able to split the string properly using Regular Expression in python I'm using a regex pattern to split some strings based on pipe as the delimiter. Most of the strings were able to split correctly as per my requirement, but one type of string is not splitting correctly. Delimiter I'm considering is pipe and t...
Not able to split the string properly using Regular Expression in python
I'm using a regex pattern to split some strings based on pipe as the delimiter. Most of the strings were able to split correctly as per my requirement, but one type of string is not splitting correctly. Delimiter I'm considering is pipe and the rule is that if a pipe or other special character such as \ or " is present...
[ "You can use an extracting approach using\n\"\\|\"?(.*?)\"(?=\\|)|([^\"|]+)\n\nSee the regex demo. Details:\n\n\"\\|\"? - a \"| or \"|\" substring\n(.*?) - Group 1: any zero or more chars other than line break chars as few as possible\n\" - a \" char\n(?=\\|) - a positive lookahead that requires a | char immediatel...
[ 0 ]
[]
[]
[ "list", "python", "regex", "split", "string" ]
stackoverflow_0074550840_list_python_regex_split_string.txt
Q: turn function add(1, 4) into (add, 1, 4) I have been experimenting with using functions to make a mini programming language, but can't find out how to turn the function add(1, 4) into (add, 1, 4) So far I have this: mem = {} def inp(text): return(input(text)) def store(name, value): mem[str(name)] = va...
turn function add(1, 4) into (add, 1, 4)
I have been experimenting with using functions to make a mini programming language, but can't find out how to turn the function add(1, 4) into (add, 1, 4) So far I have this: mem = {} def inp(text): return(input(text)) def store(name, value): mem[str(name)] = value def get(name): return(mem[str(name)])...
[ "You're either making a fairly basic mistake or attempting something very nuanced and difficult. :)\nAssuming the former: You need to be clear about the difference between python syntax and your syntax. Functions in your syntax are generally not going to be python functions (there's some nuance there) - they'll be ...
[ 0 ]
[]
[]
[ "for_loop", "function", "math", "notation", "python" ]
stackoverflow_0074550781_for_loop_function_math_notation_python.txt
Q: How can I mock patch a class used in an isinstance test? I want to test the function is_myclass. Please help me understand how to write a successful test. def is_myclass(obj): """This absurd stub is a simplified version of the production code.""" isinstance(obj, MyClass) MyClass() Docs The Python Docs...
How can I mock patch a class used in an isinstance test?
I want to test the function is_myclass. Please help me understand how to write a successful test. def is_myclass(obj): """This absurd stub is a simplified version of the production code.""" isinstance(obj, MyClass) MyClass() Docs The Python Docs for unittest.mock illustrate three ways of addressing the isi...
[ "You can't mock the second argument of isinstance(), no. The documentation you found concerns making a mock as the first argument pass the test. If you want to produce something that is acceptable as the second argument to isinstance(), you actually have to have a type, not an instance (and mocks are always instanc...
[ 6, 0, 0 ]
[]
[]
[ "mocking", "python", "python_unittest", "unit_testing" ]
stackoverflow_0049718428_mocking_python_python_unittest_unit_testing.txt
Q: Why url_for generates URL with localhost as the hostname instead of the domain name? I have a FastAPI web application using Jinja2 templates, which is working fine on localhost, but not in production. The problem is that is not generating URLs for JavaScript and other static files correctly. I have deployed it on ...
Why url_for generates URL with localhost as the hostname instead of the domain name?
I have a FastAPI web application using Jinja2 templates, which is working fine on localhost, but not in production. The problem is that is not generating URLs for JavaScript and other static files correctly. I have deployed it on EC2 instance using gunicorn and nginx. I have this line of code in my HTML file: <script s...
[ "Serve on 0.0.0.0 instead of 127.0.0.1. If you're using uvicorn which is the default web server for FastAPI, you need to pass --host 0.0.0.0 when starting the server. For other servers, look up the equivalent flag.\n", "Since you mentioned that you are using gunicorn, you need to make sure you are binding gunicor...
[ 0, 0 ]
[]
[]
[ "fastapi", "jinja2", "python", "starlette", "templating" ]
stackoverflow_0074549045_fastapi_jinja2_python_starlette_templating.txt
Q: Else or elif condition executed every time in python code in the nested dictionary I am trying to execute below code wherein I want to insert a key in the dictionary with a particular value on a condition where tos is greater than or less than the value of position key in the dictionary. But in the output I see th...
Else or elif condition executed every time in python code in the nested dictionary
I am trying to execute below code wherein I want to insert a key in the dictionary with a particular value on a condition where tos is greater than or less than the value of position key in the dictionary. But in the output I see the else or elif condition executed every time. def convert_csv_to_dataframe_and_then_conv...
[ "Your code is working fine:\nif int(recs[i]['POSITION'])>tos:\n recs[i]['is_valid']=True \nelif int(recs[i]['POSITION'])<tos:\n recs[i]['is_valid'] = False\n\nIn both the cases int(recs[i]['POSITION'])<tos, thus\nrecs[i]['is_valid'] = False\nYou might want to change the positions of True and False to get desi...
[ 1, 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074550814_pandas_python.txt
Q: Replacing character in a list with keys from a dictionary of lists I have a dictionary containing lists like char_code = {'1':['b','f','v','p'],'2':['c','g','j','k','q','s','x','z'], '3':['d','t'], '4':['l'],'5':['m','n'], '6':['r']} I have another list containing characters word_list = ['r', 'v', 'p', 'c'] I wa...
Replacing character in a list with keys from a dictionary of lists
I have a dictionary containing lists like char_code = {'1':['b','f','v','p'],'2':['c','g','j','k','q','s','x','z'], '3':['d','t'], '4':['l'],'5':['m','n'], '6':['r']} I have another list containing characters word_list = ['r', 'v', 'p', 'c'] I want to replace the letters in word_list with keys in the dictionary so th...
[ "First, invert the dictionary, so that you can easily look up the digit symbol for a given letter:\nnum_code = {\n letter: digit\n for digit, letters in char_code.items()\n for letter in letters\n}\n\nThen simply use that lookup to do the mapping:\nword_list[:] = [num_code[letter] for letter in word_list]\...
[ 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074550763_python.txt
Q: Python: Incorrect UTC Offset The following code prints: -1 day, 19:00:00 when New York is actually 5 hours behind UTC. What is wrong and how to fix it? import pytz from datetime import datetime date = datetime(2022, 11, 23, 22, 30) tz = pytz.timezone('America/New_York') print(tz.utcoffset(date)) A: tz.utcoffset...
Python: Incorrect UTC Offset
The following code prints: -1 day, 19:00:00 when New York is actually 5 hours behind UTC. What is wrong and how to fix it? import pytz from datetime import datetime date = datetime(2022, 11, 23, 22, 30) tz = pytz.timezone('America/New_York') print(tz.utcoffset(date))
[ "tz.utcoffset(date) returns a datetime.timedelta that should be added to a UTC datetime to get local time. Its a negative number for negative UTC offsets so that the addition works.\n>>> import pytz\n>>> from datetime import datetime\n>>> \n>>> date = datetime(2022, 11, 23, 22, 30)\n>>> tz = pytz.timezone('America/...
[ 0, 0 ]
[]
[]
[ "datetime", "python", "python_3.x", "pytz", "timezone_offset" ]
stackoverflow_0074550378_datetime_python_python_3.x_pytz_timezone_offset.txt
Q: Python Sequential parallel loop gets stuck in the middle I'm making a sequential parallel loop. It runs for the first time, but ends without running the loop. I don't know which part is wrong. Running the code the value is [2, 3, 3] [2, 2, 3] [2, 2, 2] If I replace it with while statement, I can't get the value ...
Python Sequential parallel loop gets stuck in the middle
I'm making a sequential parallel loop. It runs for the first time, but ends without running the loop. I don't know which part is wrong. Running the code the value is [2, 3, 3] [2, 2, 3] [2, 2, 2] If I replace it with while statement, I can't get the value I want. [2, 3, 3] [1, 3, 3] [0, 3, 3] [0, 2, 3] [0, 1, 3] [0,...
[ "Your loop is only executing 3 times because list_b only has 3 elements in it.\nIf you want the whole loop to run 3 times, you could wrap it in another for loop, like so:\nfor x in range(3):\n for i, symbol in enumerate(list_b):\n if retry_cnt[i] > 0:\n dd = 'state'\n time.sleep(0.2)...
[ 0 ]
[]
[]
[ "enumerate", "for_loop", "python" ]
stackoverflow_0074550883_enumerate_for_loop_python.txt
Q: How to calculate my encoding sha256 maximum int lenght? I use this little code in a function to generate immutable hash of strings and store it. My problem is i don't know how to find the max possible value with sha256 :7 'little' ??? int.from_bytes(hashlib.sha256(value.encode('utf-8')).digest()[:7], 'little') A:...
How to calculate my encoding sha256 maximum int lenght?
I use this little code in a function to generate immutable hash of strings and store it. My problem is i don't know how to find the max possible value with sha256 :7 'little' ??? int.from_bytes(hashlib.sha256(value.encode('utf-8')).digest()[:7], 'little')
[ "Well, if you have seven bytes, and you turn that into an integer, the maximum value is the same as the maximum value of a (7*8) bit integer, because there are 8 bits in a byte. The largest value of a 56-bit unsigned integer is 2**56 - 1, and the smallest value is 0.\n>>> 2**56 - 1\n72057594037927935\n\nWhat about ...
[ 1 ]
[]
[]
[ "calculation", "python" ]
stackoverflow_0074550960_calculation_python.txt
Q: Keras call model.fit where x is two-tuple of np.ndarray I have a regression tf.keras.Model that takes in: x: tuple[np.ndarray, np.ndarray], where the two items have different shapes Shapes are (128, 1152) and (1, 256) y: float I have my model and training codified like so: class MyModel(tf.keras.Model): d...
Keras call model.fit where x is two-tuple of np.ndarray
I have a regression tf.keras.Model that takes in: x: tuple[np.ndarray, np.ndarray], where the two items have different shapes Shapes are (128, 1152) and (1, 256) y: float I have my model and training codified like so: class MyModel(tf.keras.Model): def __init__(self): ... # Omitted for brevity d...
[ "The answer is Model.fit is iterating over the x's and y's, so I had to add a batch dimension up-front to my x[0] and y.\nThis could be easily done using np.newaxis or np.expand_dims.\nimport numpy as np\n\n# NOTE: item 0's shape is (128, 1152), item 1's shape is (1, 256)\ndatapoint_x: tuple[np.ndarray, np.ndarray]...
[ 0 ]
[]
[]
[ "keras", "python", "tensorflow", "tf.keras" ]
stackoverflow_0074542125_keras_python_tensorflow_tf.keras.txt
Q: How do you plot on a premade matplotlib plot with IPyWidgets? I have a scenario where I would like to initialize the plot and plot a bunch of stuff on it before I run a widget on it. However, the jupyter widget refuses to plot on my already made plot. Instead, nothing shows up. A simplified example of this is belo...
How do you plot on a premade matplotlib plot with IPyWidgets?
I have a scenario where I would like to initialize the plot and plot a bunch of stuff on it before I run a widget on it. However, the jupyter widget refuses to plot on my already made plot. Instead, nothing shows up. A simplified example of this is below. import matplotlib.pyplot as plt import ipywidgets as widgets fro...
[ "Assuming that you are using Jupyter Notebook, you first have to initialize the interactive matplotlib. You can do that by running either one of the following magic commands:\n\n%matplotlib notebook\n%matplotlib widget. This one requires ipympl to be installed.\n\nThen, execute:\nimport matplotlib.pyplot as plt\nim...
[ 0, 0 ]
[]
[]
[ "ipywidgets", "jupyter_lab", "matplotlib", "python" ]
stackoverflow_0074539146_ipywidgets_jupyter_lab_matplotlib_python.txt
Q: Not able to install node@10 on mac M1 chip device System I have a project which requires node@10 to run. I used https://brew.sh to install node@10. I used the below command to install node@10 brew install --build-from-source node@10 It was not able to install and i got the following error. ./configure: line 3: e...
Not able to install node@10 on mac M1 chip device
System I have a project which requires node@10 to run. I used https://brew.sh to install node@10. I used the below command to install node@10 brew install --build-from-source node@10 It was not able to install and i got the following error. ./configure: line 3: exec: python: not found I installed python using brew. ...
[ "I don't have enough rep to comment so I'll try to phrase this as an answer:\nChances are there is a messed up symlink somewhere\n\nUsually you can use brew info python to troubleshoot your python install with homebrew installs.\nAlso use which python at the terminal to see the actual path to the python executable....
[ 0, 0 ]
[]
[]
[ "apple_m1", "macos", "node.js", "python" ]
stackoverflow_0072036779_apple_m1_macos_node.js_python.txt
Q: Python Telethon - Send messages at timed intervals I'm trying to send a message to my group at defined time intervals, but I get a warning in the output the first time I try to send the message. Next times no warning, but nothing is posted in the group. I'm the owner of the group so in theory there shouldn't be an...
Python Telethon - Send messages at timed intervals
I'm trying to send a message to my group at defined time intervals, but I get a warning in the output the first time I try to send the message. Next times no warning, but nothing is posted in the group. I'm the owner of the group so in theory there shouldn't be any permissions issues. Code from telethon import Telegram...
[ "Telethon uses asyncio, but schedule wasn't designed with asyncio in mind. You should consider using an asyncio-based alternative to schedule, or just use Python's builtin functions in the asyncio module to \"schedule\" things:\nimport asyncio\nfrom telethon import TelegramClient\n\ndef send_image():\n ...\n ...
[ 0 ]
[ "As the output says you need to await the response of the coroutine. The code may trigger exceptions which should be handled.\ntry:\n client = TelegramClient(...)\n client.start()\nexcept Exception as e:\n print(f\"Exception while starting the client - {e}\")\nelse:\n try:\n ret_value = await cli...
[ -1 ]
[ "python", "python_3.x", "telegram", "telegram_bot", "telethon" ]
stackoverflow_0074546581_python_python_3.x_telegram_telegram_bot_telethon.txt
Q: filter dataset in Pandas based on a specific datetime column condition I have a dataframe with recorded dates and event dates, I use the following script to create a new dataframe with only rows where record and event dates match. New_df =df1.loc[(df1['record_date'] == df1['event_date'])] However I want to includ...
filter dataset in Pandas based on a specific datetime column condition
I have a dataframe with recorded dates and event dates, I use the following script to create a new dataframe with only rows where record and event dates match. New_df =df1.loc[(df1['record_date'] == df1['event_date'])] However I want to include rows from dataset where record dates are +- 1 day, 2 day, 3 days from even...
[ "can you try this:\nNew_df =df1.loc[abs((df1['record_date'] - df1['event_date'])).dt.days <= 3] #get +- 3 days\n\n", "new_df = df.loc[df.record_date.sub(df.event_date).abs().le('3d')]\n\n" ]
[ 1, 1 ]
[]
[]
[ "datetime", "pandas", "python" ]
stackoverflow_0074550793_datetime_pandas_python.txt
Q: RE-ORDER VALUES OF COLUMNS PARAMETERS I'm using this code valores.pivot(index='MARCA', columns='MES_C', values=['CMC','CMV','VL_VENDAS']) to pivot this dataframe on python withe pandas. MARCA MES_C CMC CMV VL_VENDAS 3F 01/2022 0,00 33,85 147,70 3M 01/2022 57.130,75 77.457,6...
RE-ORDER VALUES OF COLUMNS PARAMETERS
I'm using this code valores.pivot(index='MARCA', columns='MES_C', values=['CMC','CMV','VL_VENDAS']) to pivot this dataframe on python withe pandas. MARCA MES_C CMC CMV VL_VENDAS 3F 01/2022 0,00 33,85 147,70 3M 01/2022 57.130,75 77.457,69 182.964,37 3M 02/2022 87.177,66 75.4...
[ "pivot = pd.pivot_table(valores, index=['MARCA'], columns='MES_C', aggfunc={'CMC':'sum','CMV':'sum','VL_VENDAS':'sum'}, fill_value=0, margins=True)\n.swaplevel(axis=1)\n.sort_index(level=0, axis=1)\n.reindex(['CMC','CMV','VL_VENDAS'], level=1, axis=1)\n.rename_axis(columns=[None, None])\n\npivot.to_excel('relatorio...
[ 0 ]
[]
[]
[ "pandas", "python", "python_3.x" ]
stackoverflow_0074539380_pandas_python_python_3.x.txt
Q: Multiply / divide dataframe columns by list / series along axis 1 I have a dataframe with N columns, where N may be 0. And I have a list of scalar values, the same length than the list of columns in the dataframe. I want to multiply or divide the columns of the dataframe by the corresponding value in the list. E.g...
Multiply / divide dataframe columns by list / series along axis 1
I have a dataframe with N columns, where N may be 0. And I have a list of scalar values, the same length than the list of columns in the dataframe. I want to multiply or divide the columns of the dataframe by the corresponding value in the list. E.g. Dataframe 1 2 3 1 1 2 3 2 4 5 6 3 7 8 9 Multiplie...
[ "Here is one (hacky) way to do it:\nimport pandas as pd\n\ndef helper(df, other, *args, **kwargs):\n if isinstance(other, list) and not other:\n return pd.DataFrame()\n return mul(df, other, **kwargs)\n\n\nmul = pd.DataFrame.mul\npd.DataFrame.mul = helper\n\n\ndf_1 = pd.DataFrame({})\nlist_1 = []\n\ndf...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074448601_pandas_python.txt
Q: Add a role to a user with the selection menu discord.py I just have a question, I make a bot with discord and the users on the guild add their roles themself with a drop-down menu, for this, in my code, i have this module (with many others options): class selectmenu(discord.ui.View): def __init__(self): ...
Add a role to a user with the selection menu discord.py
I just have a question, I make a bot with discord and the users on the guild add their roles themself with a drop-down menu, for this, in my code, i have this module (with many others options): class selectmenu(discord.ui.View): def __init__(self): super().__init__(timeout=None) options=[ disco...
[ "To improve efficiency, you may want to consider using a dictionary to store your roles, with the menu selection as keys and the role names as values. For example:\nroleDict = {'1': 'Happy', '2': 'Sad', '3': 'In Love'}\n\nFrom this point, the dictionary can be implemented as follows:\nrole = discord.utils.get(guild...
[ 0 ]
[]
[]
[ "discord.py", "python" ]
stackoverflow_0074551165_discord.py_python.txt
Q: Not able to download a file through request in python When I try to download a file online it doesn't work for a particular site while it works for others. Why is this happening and what should I do about it? I write the content of the dl request in my case https://drivers.amd.com/drivers/amd-software-adrenalin-ed...
Not able to download a file through request in python
When I try to download a file online it doesn't work for a particular site while it works for others. Why is this happening and what should I do about it? I write the content of the dl request in my case https://drivers.amd.com/drivers/amd-software-adrenalin-edition-22.11.1-win10-win11-nov15.exe (warning: 500+ MB file)...
[ "If you read the error page, it tells you exactly what the problem is: they don't allow downloads without a referer from their website. Therefore, your headers will need to include a Referer key/value, and I assume a proper User-Agent as well:\nimport requests\nfrom tkinter import filedialog\n\nreferer = \"https://...
[ 1 ]
[]
[]
[ "download", "python", "request" ]
stackoverflow_0074551098_download_python_request.txt
Q: Pandas - Update Column Values If Values in Rows Are Partially Matching I have a dataframe similar to below-given dataframe. I need to add a value in Validated column that matches the below condition: If there are multiple rows with the same values in State, ColorName, and Code columns then at least one row should ...
Pandas - Update Column Values If Values in Rows Are Partially Matching
I have a dataframe similar to below-given dataframe. I need to add a value in Validated column that matches the below condition: If there are multiple rows with the same values in State, ColorName, and Code columns then at least one row should contain a positive value in the Value column. If there is no row with a posi...
[ "df = pd.DataFrame({'State': ['Arizona', 'Alabama', 'Arkansas', 'Kentuky', 'Ohio', 'Alabama', 'Arizona', 'California',\n 'California', 'Arkansas', 'Ohio', 'California'],\n 'ColorName': ['Yellow', 'Orange', 'Red', 'Green', 'Blue', 'Orange', 'Yellow', 'Blue', 'Blue', 'Red...
[ 1, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074551122_dataframe_pandas_python.txt
Q: getting AttributeError: 'numpy.ndarray' object has no attribute 'dim' when converting tensorflow code to pytorch I was translating my TensorFlow code to PyTorch and suddenly faced this error. What am I doing wrong here? AttributeError Traceback (most recent call last) <ipython-in...
getting AttributeError: 'numpy.ndarray' object has no attribute 'dim' when converting tensorflow code to pytorch
I was translating my TensorFlow code to PyTorch and suddenly faced this error. What am I doing wrong here? AttributeError Traceback (most recent call last) <ipython-input-36-058644576709> in <module> 3 batch_size = 1024 4 Xtrain = torch.concat( ----> 5 [tra...
[ "torch.stft is a pytorch function and expects a Tensor as the input. You must convert your numpy array into a tensor and then pass that as the input.\nyou can use torch.from_numpy to do this.\n" ]
[ 0 ]
[]
[]
[ "numpy", "python", "python_3.x", "pytorch", "tensorflow" ]
stackoverflow_0074551169_numpy_python_python_3.x_pytorch_tensorflow.txt
Q: Counting all the odd numbers in a nested list and printing the result in the output I'm new to Python and we received an assignment wherein we must arbitrarily define a nested list, and then implement code that counts up all the odd numbers in the list and prints the result out to the user. Our lecturer instructed...
Counting all the odd numbers in a nested list and printing the result in the output
I'm new to Python and we received an assignment wherein we must arbitrarily define a nested list, and then implement code that counts up all the odd numbers in the list and prints the result out to the user. Our lecturer instructed us to use the modulo (%) operator, as well as nested for loops. However that is as far a...
[ "You're on the right track, but since the arrays are nested you need to use a nested for loop to access the array elements and not just the arrays themselves.\nfor array in m:\n for x in array:\n if x % 2 != 0:\n\nAnd from there just sum up the odd elements.\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074551380_python.txt
Q: ModuleNotFoundError but module is installed I have pip installed colorgram.py but I am still getting an error: ModuleNotFoundError: No module named 'colorgram' I have also created a path to the python location: C:\Users\me\AppData\Local\Programs\Python\Python39 C:\Users\me\AppData\Local\Programs\Python\Python39/s...
ModuleNotFoundError but module is installed
I have pip installed colorgram.py but I am still getting an error: ModuleNotFoundError: No module named 'colorgram' I have also created a path to the python location: C:\Users\me\AppData\Local\Programs\Python\Python39 C:\Users\me\AppData\Local\Programs\Python\Python39/scripts any idea how to fix this?
[ "I guess you've installed the module with a different python version than you have run it. To fix this you can run python -m pip install <the-name-of-the-module> and than run the script with python <path-to-your-script>. If you want to use python3 just replace all python with python3.\n", "I ran into this same is...
[ 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0065458461_python.txt
Q: How to properly Install mediapipe on Raspberry Pi I tried to Install mediapipe for Python on Raspberry Pi 4 Model B with Raspbian OS 11 (Bullseye). I have followed the expected Steps like "sudo pip3 install mediapipe-rpi4". Its successfully installed referring to the terminal, but when i try to import it in a Pyth...
How to properly Install mediapipe on Raspberry Pi
I tried to Install mediapipe for Python on Raspberry Pi 4 Model B with Raspbian OS 11 (Bullseye). I have followed the expected Steps like "sudo pip3 install mediapipe-rpi4". Its successfully installed referring to the terminal, but when i try to import it in a Python file it returns a module not found Error. Is it beca...
[ "Did you ever find a solution to this?\nThe solution posted at github here:\nhttps://github.com/superuser789/MediaPipe-on-RaspberryPi/issues/10\nWorked for me, and could get mediapipe working on the Raspberry Pi running either 64 bit or 32 bit bullseye. Be aware that this method results in the mediapipe install upg...
[ 0 ]
[]
[]
[ "computer_vision", "mediapipe", "python", "raspberry_pi", "raspberry_pi4" ]
stackoverflow_0073635109_computer_vision_mediapipe_python_raspberry_pi_raspberry_pi4.txt
Q: Select pytorch tensor elements by list of indices I guess I have a pretty simple problem. Let's take the following tensor of length 6 t = torch.tensor([10., 20., 30., 40., 50., 60.]) Now I would like to to access only the elements at specific indices, lets say at [0, 3, 4]. So I would like to return # exptected o...
Select pytorch tensor elements by list of indices
I guess I have a pretty simple problem. Let's take the following tensor of length 6 t = torch.tensor([10., 20., 30., 40., 50., 60.]) Now I would like to to access only the elements at specific indices, lets say at [0, 3, 4]. So I would like to return # exptected output tensor([10., 40., 50.]) I found torch.index_sel...
[ "You can in fact use index_select for this:\nt = torch.tensor([10., 20., 30., 40., 50., 60.])\noutput = torch.index_select(t, 0, torch.LongTensor([0, 3, 4]))\n# output: tensor([10., 40., 50.])\n\nYou just need to specify the dimension (0) as the second parameter. This is the only valid dimension to specify for a 1-...
[ 1 ]
[]
[]
[ "python", "pytorch", "tensor" ]
stackoverflow_0074551428_python_pytorch_tensor.txt
Q: How do I assign a split list into different variable names? listA = [11, 18, 19, 21, 29, 46] length = len(listA) splits = np.array_split(listA, length) i = 0 for array in splits: print("test" + str([i])) print(list(array)) i += 1 Output: test[0] [11] test[1] [18] test...
How do I assign a split list into different variable names?
listA = [11, 18, 19, 21, 29, 46] length = len(listA) splits = np.array_split(listA, length) i = 0 for array in splits: print("test" + str([i])) print(list(array)) i += 1 Output: test[0] [11] test[1] [18] test[2] [19] test[3] [21] test[4] [29] test[5] [46] What I am trying...
[ "Are you just looking to make a dictionary?\n\nIf you're looking to make the actual variables test0 test1 test2 etc... that's a TERRIBLE idea unless done explicitly like in Paul M.'s comment: a, b, c, d, e, f = splits\n\nGiven:\nlistA = [11, 18, 19, 21, 29, 46]\n\nDoing:\ndictA = {f'test{i}':v for i, v in enumerate...
[ 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074551265_python_python_3.x.txt
Q: how to keep history of all outputs a user receives when inputting in a program I need to keep track of inputs in my program and store the outputs in a list so they can be replayed(printed out in the end to keep track of the program. history=[] def get_input(): global history answer=input("enter:") hist...
how to keep history of all outputs a user receives when inputting in a program
I need to keep track of inputs in my program and store the outputs in a list so they can be replayed(printed out in the end to keep track of the program. history=[] def get_input(): global history answer=input("enter:") history.append(answer) if answer=="off": print("hi") else: if an...
[ "def get_input(history):\n answer = input(\"enter:\")\n history.append(answer)\n if answer == \"off\":\n print(\"hi\")\n return history\n else:\n if answer == \"forward\":\n print(\"moved forward\")\n elif answer == \"back\":\n print(\"moved back\")\n ...
[ 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074551479_list_python.txt
Q: Python __float__() magic method not converting my custom class object I am trying to use 2 classes to calculate the perimeter of a triangle. Whatever I do I cannot convert the 3 triangle legs' lengths from data type "Point" (vertice1, vertice2, vertice3) into floats. The following error is displayed when I sum th...
Python __float__() magic method not converting my custom class object
I am trying to use 2 classes to calculate the perimeter of a triangle. Whatever I do I cannot convert the 3 triangle legs' lengths from data type "Point" (vertice1, vertice2, vertice3) into floats. The following error is displayed when I sum them to get the perimeter of the triangle : File "main.py", line 37, in per...
[ "\nI understand that I need to convert my custom class object into a float before to be able to use the \"+\" operator but I am obviously wrong somewhere.\n\nAt the part where you're never telling Python how to convert your custom type to a float: float will work out of the box on \"built-in\" types, but for a cust...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074532096_python.txt
Q: I can't figure out pip tensorrt line 17 error I couldn't install it in any way, I wonder what could be the cause of the error. I installed C++ and other necessary stuff I am using windows 11 I installed pip install nvidia-pyindex with no problem. Same as tensorrt I can't install pycuda library and I get same error...
I can't figure out pip tensorrt line 17 error
I couldn't install it in any way, I wonder what could be the cause of the error. I installed C++ and other necessary stuff I am using windows 11 I installed pip install nvidia-pyindex with no problem. Same as tensorrt I can't install pycuda library and I get same error \` (base) PS C:\\Users\\byara\> pip install nvidia...
[ "TensorRT is not available for Windows via pip. You can verify that by looking at the wheel files in PyPI, link. All the wheel files for the latest version are for Linux. Thus, trying to install on Windows will pick the previous releases, which were place-holder packages. Those releases just print the message you a...
[ 0 ]
[]
[]
[ "nvidia", "pip", "python", "tensorrt", "windows" ]
stackoverflow_0074520032_nvidia_pip_python_tensorrt_windows.txt
Q: BeautifulSoup - search by text inside a tag Observe the following problem: import re from bs4 import BeautifulSoup as BS soup = BS(""" <a href="/customer-menu/1/accounts/1/update"> Edit </a> """) # This returns the <a> element soup.find( 'a', href="/customer-menu/1/accounts/1/update", text=re.com...
BeautifulSoup - search by text inside a tag
Observe the following problem: import re from bs4 import BeautifulSoup as BS soup = BS(""" <a href="/customer-menu/1/accounts/1/update"> Edit </a> """) # This returns the <a> element soup.find( 'a', href="/customer-menu/1/accounts/1/update", text=re.compile(".*Edit.*") ) soup = BS(""" <a href="/custo...
[ "The problem is that your <a> tag with the <i> tag inside, doesn't have the string attribute you expect it to have. First let's take a look at what text=\"\" argument for find() does.\nNOTE: The text argument is an old name, since BeautifulSoup 4.4.0 it's called string.\nFrom the docs:\n\nAlthough string is for fin...
[ 91, 79, 17, 6, 1 ]
[]
[]
[ "beautifulsoup", "python", "regex" ]
stackoverflow_0031958637_beautifulsoup_python_regex.txt
Q: How to find the number of unordered pairs of 2D coordinate points, whose joining line passes through origin? (Original problem description) Pair of points You are given the following An integer N A 2D array of length N denoting the points in the 2D coordinate system, that is (x, y) Task Determine the number of uno...
How to find the number of unordered pairs of 2D coordinate points, whose joining line passes through origin?
(Original problem description) Pair of points You are given the following An integer N A 2D array of length N denoting the points in the 2D coordinate system, that is (x, y) Task Determine the number of unordered pairs (i, j) or (j, i) and i != j such that The straight line connecting the points (A[i][1], A[i][2]) and ...
[ "One optimization we can make in your code is not to check previously traversed co-ordinates:\ndef find_pairs(array, size):\n count = 0\n for i in range(size - 1):\n for j in range(i + 1, size):\n if ((array[i][1] * (array[j][0] - array[i][0])) == ((array[i][0] * (array[j][1] - array[i][1]))...
[ 1, 1, 0, 0 ]
[]
[]
[ "math", "performance", "python" ]
stackoverflow_0074551043_math_performance_python.txt
Q: Conditionally match two dataframes of unequal size I have two dataframes of unequal size with examples below. We will refer to the first dataframe as df1: Miles AB Param1 Param2 Param3 Param4 1.5 A 0.12345 0.12345 0.12345 0.12345 1.7 B 0.12345 0.12345 0.12345 0.12345 1.9 A 0.12345 0.12345 0.12345 0.123...
Conditionally match two dataframes of unequal size
I have two dataframes of unequal size with examples below. We will refer to the first dataframe as df1: Miles AB Param1 Param2 Param3 Param4 1.5 A 0.12345 0.12345 0.12345 0.12345 1.7 B 0.12345 0.12345 0.12345 0.12345 1.9 A 0.12345 0.12345 0.12345 0.12345 2.6 A 0.12345 0.12345 0.12345 0.12345 2.7 B 0.123...
[ "Use a merge_asof:\n(pd.merge_asof(df1.reset_index().sort_values(by='Miles'),\n df2.sort_values(by='Miles'),\n by='AB', on='Miles',\n direction='nearest', tolerance=0.1)\n .set_index('index').sort_index()\n)\n\nOutput:\n Miles AB Param1 Param2 Param3 Param4 Par...
[ 0 ]
[]
[]
[ "dataframe", "numpy", "python" ]
stackoverflow_0074551555_dataframe_numpy_python.txt
Q: How do I print a .txt file line-by-line? I am making my first game and want to create a score board within a .txt file, however when I try and print the score board it doesn't work. with open("Scores.txt", "r") as scores: for i in range(len(score.readlines())): print(score.readlines(i + 1)) Inst...
How do I print a .txt file line-by-line?
I am making my first game and want to create a score board within a .txt file, however when I try and print the score board it doesn't work. with open("Scores.txt", "r") as scores: for i in range(len(score.readlines())): print(score.readlines(i + 1)) Instead of printing each line of the .txt file as ...
[ "Assign the result of score.readlines() to a variable. Then you can loop through it and index it.\nwith open(\"Scores.txt\", \"r\") as scores:\n scorelines = scores.readlines()\n\nfor line in scorelines:\n print(line)\n\n", ".readlines() reads everything until it reaches the end of the file. Calling it repe...
[ 1, 0 ]
[]
[]
[ "python", "txt" ]
stackoverflow_0074551613_python_txt.txt
Q: What is a faster method to calculate hourly totals from a pandas DataFrame thatn a for loop? I have a pandas DataFrame with about 200,000 rows of raw data. Each row has start and stop times that can span an hour to years. I am using a for loop to calculate a total for each hour of a year; each hourly total sums ...
What is a faster method to calculate hourly totals from a pandas DataFrame thatn a for loop?
I have a pandas DataFrame with about 200,000 rows of raw data. Each row has start and stop times that can span an hour to years. I am using a for loop to calculate a total for each hour of a year; each hourly total sums records that span that hour. I am calculating hourly totals for a full year, or about 24 * 365 = ...
[ "If you are willing to trade off speed for memory and you have enough of the latter, the following could work:\n# Calculate all possible time-points - similar to hourly_dates but with an additional time-point at the end \nhour_beginning = pd.Series(pd.date_range(test_data['START_TIME'].min(), test_data['STOP_TIME']...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python", "python_3.x" ]
stackoverflow_0074547954_dataframe_pandas_python_python_3.x.txt
Q: How can I use min() without getting "0" or "" for an answer? I'm trying to use min in a list that came from a .csv and some of the values are '' how can I ignore those and also "0"? I tried index1 = (life_expectancy.index(min(life_expectancy,))) print(life_expectancy[index1]) and got nothing, when i tried: index1...
How can I use min() without getting "0" or "" for an answer?
I'm trying to use min in a list that came from a .csv and some of the values are '' how can I ignore those and also "0"? I tried index1 = (life_expectancy.index(min(life_expectancy,))) print(life_expectancy[index1]) and got nothing, when i tried: index1 = (life_expectancy.index(min(life_expectancy, key=int))) I got: ...
[ "I don't think there is a simple way to do this in a single line of code using min.\nOne way to avoid 0-values is to call filter before min. Then, to avoid invalid values, you can write a wrapper around int that returns 0 on invalid values.\ndef int_or_zero(s):\n try:\n return int(s)\n except ValueErro...
[ 2, 1, 0, -1 ]
[ "#You can simply remove all 0 terms and string terms from your list and then use min\nl=[1,34,6,4,1,4,0]\nl1=l\nwhile True:\n try:\n l1.remove(0)\n except ValueError:\n break \nprint(min(l1)) \n\n" ]
[ -2 ]
[ "list", "minimum", "python", "python_3.x" ]
stackoverflow_0074549273_list_minimum_python_python_3.x.txt
Q: First argument to get_object_or_404() must be a Model. How can I get an user's id to the User model? I'm trying to make a favorite functionality where an user can add other users as their favorites. In the View where the profile of an user is shown I have a button that adds an user or removes it if it was already ...
First argument to get_object_or_404() must be a Model. How can I get an user's id to the User model?
I'm trying to make a favorite functionality where an user can add other users as their favorites. In the View where the profile of an user is shown I have a button that adds an user or removes it if it was already added. The problem is that I can't pass to the views the user that will be added as a favorite. models.py ...
[ "One immediate problem I see is that your URL path wants a string for the username, but your URL for the form gives it the ID of the user, so that'll be an int.\nIn terms of your error, you're trying to pass a username, but I don't think that'll be in the POST data. However if it was, you should be able to do;\nget...
[ 0 ]
[]
[]
[ "django", "django_views", "python" ]
stackoverflow_0074551597_django_django_views_python.txt
Q: Filter with a computed field is not working [Odoo 8] I have to display in a tree view the number of attachments an invoice has. This is OK, I'm doing it with a compute. I also have to be able to filter the invoices that have attached files and here is the problem. I can't use this field in searching because it doe...
Filter with a computed field is not working [Odoo 8]
I have to display in a tree view the number of attachments an invoice has. This is OK, I'm doing it with a compute. I also have to be able to filter the invoices that have attached files and here is the problem. I can't use this field in searching because it doesn't have store=True attribute, and if I add it, the compu...
[ "self.search([]) returns a list of recordsets. So when your code doesn't match the \"if\" condition, it will throw an error.\nYou need to add an \"else\" condition to get a list of record ids. For example:\ndef _search_att_count(self, operator, value):\n field_id = self.search([])\n if operator == '=':\n ...
[ 1 ]
[]
[]
[ "odoo", "odoo_8", "python" ]
stackoverflow_0074551614_odoo_odoo_8_python.txt
Q: Lark: How to ignore whitespace after parsing? I am creating a REPL for Linux commands. Since my grammar for command is call: WS? (redirection WS)* argument (WS atom)* WS?, once the parsing is done, I always find whitespace is included as one of the nodes in the parse tree. I understand including WS in the grammar ...
Lark: How to ignore whitespace after parsing?
I am creating a REPL for Linux commands. Since my grammar for command is call: WS? (redirection WS)* argument (WS atom)* WS?, once the parsing is done, I always find whitespace is included as one of the nodes in the parse tree. I understand including WS in the grammar to catch the command line correctly, but I want to ...
[ "You can use a Transformer and have the method for the WS token return Discard.\nTransformers make it much easier to convert the result of the parsing into the format that you need for the rest of your program. Since you didn't include your grammar, and your specific use case is too complex to replicate quickly, I...
[ 0 ]
[]
[]
[ "lark_parser", "parsing", "python", "read_eval_print_loop" ]
stackoverflow_0074550878_lark_parser_parsing_python_read_eval_print_loop.txt
Q: Python - How to properly fill a multiline text field in PDF form using pdfrw? I'm filling a PDF form using python with pdfrw. I have no problem with any single line text field in the form. But when I try to fill a multi-line textfield it doesn`t render properly, it ignores break lines. This is part of my code: pdf...
Python - How to properly fill a multiline text field in PDF form using pdfrw?
I'm filling a PDF form using python with pdfrw. I have no problem with any single line text field in the form. But when I try to fill a multi-line textfield it doesn`t render properly, it ignores break lines. This is part of my code: pdf.Root.AcroForm.update(PdfDict(NeedAppearances=PdfObject('true'))) for x in range(0...
[ "I cannot read Spanish setting, but if you make sure these 2 fields are checked, then you probably will be OK.\nSetting\n", "I've had this issue too. I haven't delved into the implementation of the multi-line feature by pdfrw, but I do know that when I flatten the form field (Ff=1, which you also have in your cod...
[ 0, 0, 0, 0 ]
[]
[]
[ "acrobat", "pdf", "pdf_form", "pdfrw", "python" ]
stackoverflow_0068119744_acrobat_pdf_pdf_form_pdfrw_python.txt
Q: How can I send an embed via my Discord bot, w/python? I've been working a new Discord bot. I've learnt a few stuff,and, now, I'd like to make the things a little more custom. I've been trying to make the bot send embeds, instead, of a common message. embed=discord.Embed(title="Tile", description="Desc", color=0x00...
How can I send an embed via my Discord bot, w/python?
I've been working a new Discord bot. I've learnt a few stuff,and, now, I'd like to make the things a little more custom. I've been trying to make the bot send embeds, instead, of a common message. embed=discord.Embed(title="Tile", description="Desc", color=0x00ff00) embed.add_field(name="Fiel1", value="hi", inline=Fals...
[ "To get it to work I changed your send_message line to\nawait message.channel.send(embed=embed)\nHere is a full example bit of code to show how it all fits:\n@client.event\nasync def on_message(message):\n if message.content.startswith('!hello'):\n embedVar = discord.Embed(title=\"Title\", description=\"D...
[ 42, 7, 2, 2, 1, 0 ]
[]
[]
[ "discord", "discord.py", "embed", "python" ]
stackoverflow_0044862112_discord_discord.py_embed_python.txt
Q: Getting Annotations of a class and all parent classes in python Suppose you have a class structure like this: class parent(object): parent_annotation:str class child(parent): child_annotation:int Right now inspect.get_annotations(child) returns only {'child_annotation': <class:'int'>} I want a general-p...
Getting Annotations of a class and all parent classes in python
Suppose you have a class structure like this: class parent(object): parent_annotation:str class child(parent): child_annotation:int Right now inspect.get_annotations(child) returns only {'child_annotation': <class:'int'>} I want a general-purpose way to get the union of annotations on all classes in the inh...
[ "Thanks @juanpa.arrivillaga, and thanks @chepner\nHere's a solution:\n\nclass parent(object):\n parent_annotation:str\n\n def all_annotations(self):\n all_annotations = {}\n for cls in type(self).mro():\n all_annotations.update(inspect.get_annotations(cls))\n return all_annotat...
[ 0 ]
[]
[]
[ "oop", "python", "python_3.x" ]
stackoverflow_0074551257_oop_python_python_3.x.txt
Q: Create Nothing from falsey values using Returns library Using the Returns library, I have a function that filters a list. I want it to return Nothing if the list is empty (i.e. falsey) or Some([...]) if the list has values. Maybe seems to be mostly focused on "true" nothing, being None. But I'm wondering if there'...
Create Nothing from falsey values using Returns library
Using the Returns library, I have a function that filters a list. I want it to return Nothing if the list is empty (i.e. falsey) or Some([...]) if the list has values. Maybe seems to be mostly focused on "true" nothing, being None. But I'm wondering if there's a way to get Nothing from a falsey value without doing some...
[ "It looks like you have at least a few options. (1) You can create a new class that inherits from Maybe, and then override any methods you like, (2) create a simple function that returns Nothing is data is false, else returns Maybe.from_optional(data) {or whatever other method of Maybe you prefer), or (3) create y...
[ 0 ]
[]
[]
[ "option_type", "python" ]
stackoverflow_0074549388_option_type_python.txt
Q: What is a beautiful soup bound method? I'm experimenting with http://robobrowser.readthedocs.org/en/latest/readme.html, a new python library based on the beautiful soup library. I'm trying to test it out by opening an html page and returning it within a django app, but I can't figure out to do this most simple tas...
What is a beautiful soup bound method?
I'm experimenting with http://robobrowser.readthedocs.org/en/latest/readme.html, a new python library based on the beautiful soup library. I'm trying to test it out by opening an html page and returning it within a django app, but I can't figure out to do this most simple task. My django app contains : def index(reques...
[ "It's a method object, bound to the BeautifulSoup object. You didn't call it.\nIt's representation is a little confusing because the repr() of the BeautifulSoup parse tree is included, which is simply the tree rendered as a HTML source string.\nTo get to the underlying BeautifulSoup parse tree, you can use; use str...
[ 3, 0 ]
[]
[]
[ "beautifulsoup", "django", "python", "robobrowser" ]
stackoverflow_0023414369_beautifulsoup_django_python_robobrowser.txt
Q: Unable to install orjson 3.3.0 on macOS 12.2.1 with Apple M1 chip I am trying to install orjson==3.3.0 on my MacBook Pro with Apple M1 Pro chip running macOS Monterey 12.2.1. Python version: 3.8.9 Command used: pip install orjson==3.3.0 Error: Collecting orjson==3.3.0 Downloading orjson-3.3.0.tar.gz (654 kB) ...
Unable to install orjson 3.3.0 on macOS 12.2.1 with Apple M1 chip
I am trying to install orjson==3.3.0 on my MacBook Pro with Apple M1 Pro chip running macOS Monterey 12.2.1. Python version: 3.8.9 Command used: pip install orjson==3.3.0 Error: Collecting orjson==3.3.0 Downloading orjson-3.3.0.tar.gz (654 kB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 654.9/654.9 KB 2.9 MB/s et...
[ "I don't know if that helps you but I had a similar Problem with 3.6.2, so I ran pip install orjson and it installed orjson==3.8.1 without a Problem.\n" ]
[ 0 ]
[]
[]
[ "apple_m1", "macos", "orjson", "python", "rust" ]
stackoverflow_0071349322_apple_m1_macos_orjson_python_rust.txt
Q: Unable to convert datetime string with timezone to datetime in UTC using datetime python module I am having issues converting a datetime string of this format "%d %b %Y %X %Z" to "%Y-%m-%dT%X%z". The timezone information is stripped out. For example: >> import datetime >> datetime_string_raw = "18 Nov 2022 08:57:0...
Unable to convert datetime string with timezone to datetime in UTC using datetime python module
I am having issues converting a datetime string of this format "%d %b %Y %X %Z" to "%Y-%m-%dT%X%z". The timezone information is stripped out. For example: >> import datetime >> datetime_string_raw = "18 Nov 2022 08:57:04 EST" >> datetime_utc = datetime.datetime.strptime(datetime_string_raw, "%d %b %Y %X %Z").strftime...
[ "Using dateutil's parser and a definition which abbreviated names should resemble which time zone:\nimport datetime\nimport dateutil # pip install python-dateutil\n\ntzinfos = {\"EST\": dateutil.tz.gettz(\"America/New_York\"),\n \"EDT\": dateutil.tz.gettz(\"America/New_York\")}\n\ndatetime_string_raw = \"...
[ 1 ]
[]
[]
[ "datetime", "python", "python_3.x", "python_datetime", "timezone" ]
stackoverflow_0074551570_datetime_python_python_3.x_python_datetime_timezone.txt
Q: What matplotlib rc parameter controls legend title size? Is there an rc parameter to control the size of a legend title in matplotlib? It's possible to set with ax.legend().set_title(prop={"size": title_size}) But it does not seem to correspond to the rc parameters legend.fontsize or axes.titlesize. What paramete...
What matplotlib rc parameter controls legend title size?
Is there an rc parameter to control the size of a legend title in matplotlib? It's possible to set with ax.legend().set_title(prop={"size": title_size}) But it does not seem to correspond to the rc parameters legend.fontsize or axes.titlesize. What parameter controls the size of this element?
[ "Inspecting the source code and trying around a little bit it seems to me that there is no such rc parameter. The default font size is used.\nIt is a bit surprising to me - probably it's because legend titles are not used very often.\nUpdate 2017/18/09: Still not possible. If anybody of you would need it, please op...
[ 3, 3, 0, 0, 0 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0021130576_matplotlib_python.txt
Q: Is it possible to get GridSpec from Figure before adding Axes? Consider the following code from matplotlib import pyplot as plt fig = plt.figure() grid = fig.add_gridspec(2,2) We have that grid is a GridSpec instance. Consider now the following code from matplotlib import pyplot as plt fig = plt.figure() fig.ad...
Is it possible to get GridSpec from Figure before adding Axes?
Consider the following code from matplotlib import pyplot as plt fig = plt.figure() grid = fig.add_gridspec(2,2) We have that grid is a GridSpec instance. Consider now the following code from matplotlib import pyplot as plt fig = plt.figure() fig.add_gridspec(2,2) The only way to retrieve the GridSpec associated to...
[ "This is the code defining the add_gridspec method:\n def add_gridspec(self, nrows=1, ncols=1, **kwargs):\n \"\"\"\n ...\n \"\"\"\n _ = kwargs.pop('figure', None) # pop in case user has added this...\n gs = GridSpec(nrows=nrows, ncols=ncols, figure=self, **kwargs)\n sel...
[ 1 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0074550664_matplotlib_python.txt
Q: DAG not visible in Web-UI I am new to Airflow. I am following a tutorial and written following code. from airflow import DAG from airflow.operators.python_operator import PythonOperator from datetime import datetime, timedelta from models.correctness_prediction import CorrectnessPrediction default_args = { 'o...
DAG not visible in Web-UI
I am new to Airflow. I am following a tutorial and written following code. from airflow import DAG from airflow.operators.python_operator import PythonOperator from datetime import datetime, timedelta from models.correctness_prediction import CorrectnessPrediction default_args = { 'owner': 'abc', 'depends_on_p...
[ "Run airflow list_dags\nto check, whether the dag file is located correctly. \nFor some reason, I didn't see my dag in the browser UI before I executed this. Must be issue with browser cache or something.\nIf that doesn't work, you should just restart the webserver with airflow webserver -p 8080 -D\n", "I have th...
[ 26, 23, 20, 12, 7, 1, 1, 0, 0, 0, 0, 0 ]
[]
[]
[ "airflow", "directed_acyclic_graphs", "python", "python_3.x" ]
stackoverflow_0038992997_airflow_directed_acyclic_graphs_python_python_3.x.txt
Q: Not able to copy file in docker file which is downloaded in github actions I can able to see the .pkl which is downloaded using actions/download-artifact@v3 action in work directory along with Dockerfile as shown below, When I try to COPY file inside Dockefile, I get a file not found error. How to copy the files...
Not able to copy file in docker file which is downloaded in github actions
I can able to see the .pkl which is downloaded using actions/download-artifact@v3 action in work directory along with Dockerfile as shown below, When I try to COPY file inside Dockefile, I get a file not found error. How to copy the files inside docker image that are downloaded(through github actions) before building...
[ "In your workflow file, you're not specifying the context:\n - name: Build container image\n uses: docker/build-push-action@v2\n with:\n push: false\n tags: ${{ env.ACR }}.azurecr.io/${{ env.CONTAINER_NAME }}:${{ github.run_number }}\n file: ./Dockerfile\n\nBy default, ...
[ 2 ]
[]
[]
[ "docker", "fastapi", "github_actions", "python" ]
stackoverflow_0074551520_docker_fastapi_github_actions_python.txt
Q: change after purchase not giving the right breakdown def main(): money1 = input("Purchase price: ") money2 = input("Paid amount of money: ") price = int(money1) paid = int(money2) change = paid - price ten_euro = change // 10 five_euro = change % 10 // 5 two_euro = change % 5 // 2 ...
change after purchase not giving the right breakdown
def main(): money1 = input("Purchase price: ") money2 = input("Paid amount of money: ") price = int(money1) paid = int(money2) change = paid - price ten_euro = change // 10 five_euro = change % 10 // 5 two_euro = change % 5 // 2 one_euro = (change % 2) if price < paid: ...
[ "This line is incorrect: if (change % 2) >= 2.\nThis can never be true. You probably meant: if (change % 2) >= 1.\nApart from that I think you could simplify the program by decrementing the change variable as you calculate the different denominations. You can use the builtin method divmod for this.\nYou can also ch...
[ 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074551585_python.txt
Q: "detail": "Method \"GET\" not allowed" in django-rest-framework (for permission_classes = IsAuthenticated and more where it allowed GET method) Help please! I have installed for view class permission_class which allow GET-requests, but when i send GET-request i get messege: GET method is not allowed i have views.p...
"detail": "Method \"GET\" not allowed" in django-rest-framework (for permission_classes = IsAuthenticated and more where it allowed GET method)
Help please! I have installed for view class permission_class which allow GET-requests, but when i send GET-request i get messege: GET method is not allowed i have views.py file: class WomenAPIList(generics.ListCreateAPIView): queryset = Women.objects.all() serializer_class = WomenSerializer permission_clas...
[ "You need to apply Both cases like this ....\nWith Browser (Session and Basic Both worked with Browser but at time you can apply only one) (Handle Session)\nREST_FRAMEWORK = {\n 'DEFAULT_RENDERER_CLASSES': [\n 'rest_framework.renderers.JSONRenderer',\n 'rest_framework.renderers.BrowsableAPIRenderer...
[ 0, 0 ]
[]
[]
[ "django_rest_framework", "get", "permissions", "python" ]
stackoverflow_0074535625_django_rest_framework_get_permissions_python.txt
Q: Counting number of strings in a List with Python I have a list in my hand and I want to create vocabulary from this list. Then, I want to show each word and count the same strings in this list. The sample list as below. new_list = ['one', 'thus', 'once', 'one', 'count', 'once', 'this', 'thus'] First, I crea...
Counting number of strings in a List with Python
I have a list in my hand and I want to create vocabulary from this list. Then, I want to show each word and count the same strings in this list. The sample list as below. new_list = ['one', 'thus', 'once', 'one', 'count', 'once', 'this', 'thus'] First, I created a vocabulary with below. vocabulary = [] ...
[ "Use a Counter dict to get the word count then just iterate over the .items:\nfrom collections import Counter\n\nnew_list = ['one', 'thus', 'once', 'one', 'count', 'once', 'this', 'thus']\n\ncn = Counter(new_list)\nfor k,v in cn.items():\n print(\"{} appears {} time(s)\".format(k,v))\n\nIf you want that particu...
[ 7, 0 ]
[]
[]
[ "python" ]
stackoverflow_0030692655_python.txt
Q: Getting an infinite loop in pandas when creating a CSV I am trying to create a function that receives two separate CSV files, finds differences between them and create a third CSV file which is populated with the rows that fall into a certain category (if the value of CSV A in row #1 is present in any row in CSV ...
Getting an infinite loop in pandas when creating a CSV
I am trying to create a function that receives two separate CSV files, finds differences between them and create a third CSV file which is populated with the rows that fall into a certain category (if the value of CSV A in row #1 is present in any row in CSV B) but this is creating me an infinite loop. It should retu...
[ "Figured it out, in the def I shouldn't be doing a concat between dataLoader and fila. I should just create fila, add them the values and then return it. That just fixes it.\nSo in summary:\ndef valorPivoteo(ftth_osp, valor_osp, pivote, dataLoader):\n fila = pd.DataFrame({\"FTTH\": [ftth_osp], \"ID\": pivote})\n...
[ 0 ]
[]
[]
[ "csv", "dataframe", "pandas", "python" ]
stackoverflow_0074549452_csv_dataframe_pandas_python.txt
Q: How to pass generated data from a Auth Middleware to a Blueprint function in Flask 2? (Solved) I have a function foo() defined from a Blueprint and from it I need to be able to read to a variable that is only created a moment before when the Middleware is executed. I have something like this: app.py def create_app...
How to pass generated data from a Auth Middleware to a Blueprint function in Flask 2? (Solved)
I have a function foo() defined from a Blueprint and from it I need to be able to read to a variable that is only created a moment before when the Middleware is executed. I have something like this: app.py def create_app(): app = Flask(__name__) with app.app_context(): app.register_blueprint(my_bluepri...
[ "If anyone needs to do something similar to what I needed,\nHere's an example of how I ended up solving it using a decorator.\ndef my_custom_validator(f):\n @wraps(f)\n def decorated_function(*args, **kwargs):\n headers = request.headers\n\n result_validation = some_validations(headers)\n ...
[ 1 ]
[]
[]
[ "blueprint", "flask", "middleware", "python" ]
stackoverflow_0074481991_blueprint_flask_middleware_python.txt
Q: Plot multiples values in the same Column graph I need to plot these graphs in the same plot, but i cant put it together, how can i make this? import pandas as pd import matplotlib.pyplot as plt import random import seaborn as sns plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = Tr...
Plot multiples values in the same Column graph
I need to plot these graphs in the same plot, but i cant put it together, how can i make this? import pandas as pd import matplotlib.pyplot as plt import random import seaborn as sns plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True df = pd.DataFrame(dict( year=range(2010,2021...
[ "\nSee pandas.DataFrame.plot for a description of all parameters.\nPlot grouped bars and set the y-axis to a log scale because the range of 'monetary' is much larger than 'qtd'. See the logy= parameter.\nTested in python 3.11, pandas 1.5.2, matplotlib 3.6.2\n\nThese options do not explicitly require importing matpl...
[ 2 ]
[]
[]
[ "bar_chart", "grouped_bar_chart", "pandas", "python" ]
stackoverflow_0074551033_bar_chart_grouped_bar_chart_pandas_python.txt
Q: Python equivalent of Golang's select on channels Go has a select statement that works on channels. From the documentation: The select statement lets a goroutine wait on multiple communication operations. A select blocks until one of its cases can run, then it executes that case. It chooses one at random if mu...
Python equivalent of Golang's select on channels
Go has a select statement that works on channels. From the documentation: The select statement lets a goroutine wait on multiple communication operations. A select blocks until one of its cases can run, then it executes that case. It chooses one at random if multiple are ready. Is there a Python equivalent of the...
[ "Here's a pretty direct translation, but the \"choosing which if multiple are ready\" part works differently - it's just taking what came in first. Also this is like running your code with gomaxprocs(1).\nimport threading\nimport Queue\n\ndef main():\n c1 = Queue.Queue(maxsize=0)\n c2 = Queue.Queue(maxsize=0)...
[ 19, 12, 9, 4, 4, 3, 2, 1 ]
[]
[]
[ "go", "python" ]
stackoverflow_0019130986_go_python.txt
Q: Draw a Rectangle over an image and get the coordinates in python I'm trying to develop a code that open an image where you can select a point quit the mouse and drag to form a rectangle until you don't release the left button. Then from python I should receive the starting coordinates and the height and width in p...
Draw a Rectangle over an image and get the coordinates in python
I'm trying to develop a code that open an image where you can select a point quit the mouse and drag to form a rectangle until you don't release the left button. Then from python I should receive the starting coordinates and the height and width in pixel of the rectangle, how can I do it? I saw that the packages argpar...
[ "I won't do the job for you but I'm willing to help.\nYou will need 2 blocks of code:\n\nan image displayer\na mouse-event listener\n\nTo start, you may forget about the image displayer. You may concentrate on the mouse listener while you draw your rectangle anywhere on the screen.\nSelect a mouse listener library....
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074549601_python.txt
Q: How to place the buttons side to side in tkinter using place method? I am new to tkinter and learning to create simple widgets. I have encountered on issue, when I was creating many buttons to click, I found that the spacing between the buttons is not uniform and it becomes more congested as it goes left to right....
How to place the buttons side to side in tkinter using place method?
I am new to tkinter and learning to create simple widgets. I have encountered on issue, when I was creating many buttons to click, I found that the spacing between the buttons is not uniform and it becomes more congested as it goes left to right. MWE How to make spacing between buttons uniform? %%writefile a.py import ...
[ "You'll have a much easier time using a different geometry manager like pack() or, better yet, grid()\nUsing pack:\nimport tkinter as tk\n\nchild = tk.Tk()\nchild.geometry('400x300')\n\nx,w = 0,40\nmins = [1,2,5,10,15,20,25,30,35,40]\nmins2 = [45,50,55,60,90,120,150,180]\n# create some frames to contain each row of...
[ 2 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074551930_python_tkinter.txt
Q: Expand json data in a column inside dataframe I know there is a way to expand the columns without extracting and joining/concatenating/appending data. I have this json data which I've already normalized but I have a column that has a nested json: Image of issue So what I want to do is to expand this json data in a...
Expand json data in a column inside dataframe
I know there is a way to expand the columns without extracting and joining/concatenating/appending data. I have this json data which I've already normalized but I have a column that has a nested json: Image of issue So what I want to do is to expand this json data in a way that adds columns automatically in the datafra...
[ "you should use explode before json_normalize because they are lists:\nenviosdf=enviosdf.explode('bultos').reset_index(drop=True)\nenviosdf=enviosdf.join(pd.json_normalize(enviosdf.pop('bultos')))\n\n" ]
[ -1 ]
[]
[]
[ "json", "pandas", "python" ]
stackoverflow_0074551061_json_pandas_python.txt
Q: How to get the difference of two querysets in Django? I have to querysets. alllists and subscriptionlists alllists = List.objects.filter(datamode = 'A') subscriptionlists = Membership.objects.filter(member__id=memberid, datamode='A') I need a queryset called unsubscriptionlist, which possess all records in alllis...
How to get the difference of two querysets in Django?
I have to querysets. alllists and subscriptionlists alllists = List.objects.filter(datamode = 'A') subscriptionlists = Membership.objects.filter(member__id=memberid, datamode='A') I need a queryset called unsubscriptionlist, which possess all records in alllists except the records in subscription lists. How to achieve...
[ "Since Django 1.11, QuerySets have a difference() method amongst other new methods:\n# Capture elements that are in qs_all but not in qs_part\nqs_diff = qs_all.difference(qs_part) \n\nAlso see: https://stackoverflow.com/a/45651267/5497962\n", "You should be able to use the set operation difference to help:\nse...
[ 32, 21, 11, 4, 0 ]
[]
[]
[ "django", "django_queryset", "python" ]
stackoverflow_0005945912_django_django_queryset_python.txt