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: How to get the predict probability in Machine Leaning I have this ML model trained and dumped so I can use it anywhere. And I need to get not just the score, predict values, but also I need predict_proba value as well. I could get that but the problem is, I was expecting the probabilities to be between 0 and 1, bu...
How to get the predict probability in Machine Leaning
I have this ML model trained and dumped so I can use it anywhere. And I need to get not just the score, predict values, but also I need predict_proba value as well. I could get that but the problem is, I was expecting the probabilities to be between 0 and 1, but I get something else like below. array([[1.00000000e+00, ...
[ "To convert the probability array from decimal to percentage, you can write (loaded_model.predict_proba(inputs)) * 100.\nEDIT: The format that is outputted by loaded_model.predict_proba(inputs) is just scientific notation, i.e. all of those numbers are between 0 and 1, but many of them are extremely small probabili...
[ 0, 0, 0 ]
[]
[]
[ "machine_learning", "numpy", "python", "scikit_learn" ]
stackoverflow_0062811076_machine_learning_numpy_python_scikit_learn.txt
Q: Delete elements from numpy arrays at the same position by using zip() and np.delete() I got two 1D arrays of same length (it and l) and I want to delete the element y in l for l < ls and also delete element x in it at the same position. I tried: for x, y in zip(it, l): if y < ls: np.delete(l,y)...
Delete elements from numpy arrays at the same position by using zip() and np.delete()
I got two 1D arrays of same length (it and l) and I want to delete the element y in l for l < ls and also delete element x in it at the same position. I tried: for x, y in zip(it, l): if y < ls: np.delete(l,y) np.delete(it,x) But it is not working and there is the Warning: "DeprecationW...
[ "Here you have an example.\nYou have to indicate the index of the element that you want to remove :\nimport numpy as np\n\nit = np.asarray(range(10))\nl = np.asarray(range(10))\n\nls = 4\nindex = []\nfor i, y in enumerate(l):\n if y < ls:\n index.append(i)\n\nl = np.delete(l, index)\nit = np.delet...
[ 1 ]
[]
[]
[ "arrays", "numpy", "python", "zip" ]
stackoverflow_0074190056_arrays_numpy_python_zip.txt
Q: Inserting a Python datetime.datetime object into MySQL I have a date column in a MySQL table. I want to insert a datetime.datetime() object into this column. What should I be using in the execute statement? I have tried: now = datetime.datetime(2009,5,5) cursor.execute("INSERT INTO table (name, id, datecolumn) VA...
Inserting a Python datetime.datetime object into MySQL
I have a date column in a MySQL table. I want to insert a datetime.datetime() object into this column. What should I be using in the execute statement? I have tried: now = datetime.datetime(2009,5,5) cursor.execute("INSERT INTO table (name, id, datecolumn) VALUES (%s, %s , %s)",("name", 4,now)) I am getting an error ...
[ "For a time field, use:\nimport time \ntime.strftime('%Y-%m-%d %H:%M:%S')\n\nI think strftime also applies to datetime.\n", "You are most likely getting the TypeError because you need quotes around the datecolumn value.\nTry:\nnow = datetime.datetime(2009, 5, 5)\n\ncursor.execute(\"INSERT INTO table (name, id,...
[ 233, 48, 15, 13, 3, 1, 0, 0 ]
[ "when iserting into t-sql\nthis fails:\nselect CONVERT(datetime,'2019-09-13 09:04:35.823312',21)\n\nthis works:\nselect CONVERT(datetime,'2019-09-13 09:04:35.823',21)\n\neasy way:\nregexp = re.compile(r'\\.(\\d{6})')\ndef to_splunk_iso(dt):\n \"\"\"Converts the datetime object to Splunk isoformat string.\"\"\"\n...
[ -1 ]
[ "datetime", "mysql", "python" ]
stackoverflow_0001136437_datetime_mysql_python.txt
Q: Python Os function called from Tkinter does not work when converted to .exe Need your help lads and lasses! I made a very simple hangman game with a GUI in Tkinter and created a button event that calls the following function to restart the game. This works fine as a Python script but does not work when converting ...
Python Os function called from Tkinter does not work when converted to .exe
Need your help lads and lasses! I made a very simple hangman game with a GUI in Tkinter and created a button event that calls the following function to restart the game. This works fine as a Python script but does not work when converting script to .exe with Pyinstaller. ('Window" here is the root Tkinter window) def ...
[ "you should recreate your window and initialize it the same way you originially did.\ndef restart_func():\n global window\n window.destroy()\n window = tk.Tk()\n run_gui_initialization_function()\n\nthis is usually why some applications prefer OOP instead of functional programming, as there is usually n...
[ 1 ]
[]
[]
[ "pyinstaller", "python", "tkinter" ]
stackoverflow_0074189954_pyinstaller_python_tkinter.txt
Q: Is there a way to get my full listening history from the Spotify API? I've been trying to get my listening history from Spotify using spotipy, but unfortunately the recently-played endpoint is limited to 50 tracks. Spotify obviously has to store this data because they use it when displaying my year-end listening s...
Is there a way to get my full listening history from the Spotify API?
I've been trying to get my listening history from Spotify using spotipy, but unfortunately the recently-played endpoint is limited to 50 tracks. Spotify obviously has to store this data because they use it when displaying my year-end listening stats, and I know there are some third-party websites that also use it (e.g:...
[ "Here is an implementation that uses a cron to collect data, so it would get what you need from the point its set up onward: https://gist.github.com/SamL98/c1200a30cdb19103138308f72de8d198\nUnfortunately, there is no way to programmatically access your full streaming history unless you set up a collector like the o...
[ 1 ]
[]
[]
[ "api", "python", "spotify", "spotipy" ]
stackoverflow_0074190136_api_python_spotify_spotipy.txt
Q: Python string conversion - date in Zulu format to standard time How can I convert a string in below format: 20221001T0545Z to 2022-10-01 05:45 The result can just be text or string, it does not need to be an actual date-time A: You can use the datetime library for this conversion, see documentation: https://d...
Python string conversion - date in Zulu format to standard time
How can I convert a string in below format: 20221001T0545Z to 2022-10-01 05:45 The result can just be text or string, it does not need to be an actual date-time
[ "You can use the datetime library for this conversion, see documentation: https://docs.python.org/3/library/datetime.html#datetime-objects\nfrom datetime import datetime\n\nd = datetime.strptime(\"20221001T0545Z\", \"%Y%m%dT%H%MZ\")\n\nprint(d) # >> '2022-10-01 05:45:00'\nprint(d.strftime(\"%Y-%m-%d %H:%M\")) # >> ...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074190051_python.txt
Q: Having problems shifting the characters of a string based on their ascii value enter image description hereProblem : "For this problem you will be implementing a Caesarin Cipher. A Caesarin Cipher takes a string and a shift amount and shifts the characters in the string by the shift amount to create an enciphered ...
Having problems shifting the characters of a string based on their ascii value
enter image description hereProblem : "For this problem you will be implementing a Caesarin Cipher. A Caesarin Cipher takes a string and a shift amount and shifts the characters in the string by the shift amount to create an enciphered string. If a character would be shifted past the end of the alphabet then it wraps b...
[ "you have more than one problem, see below some explanation and a way to solve the issue:\n\nnew_user_input will be resetting each time you will iterate, so only the last character will be changed\n\nthe roll over could be apply using replace, but the problem is, it will return the full string and you will have to ...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074189114_python.txt
Q: How to break a string with numbers by symbol - split()? I have a code: single_amount_product = product_amount[i] amount_products = single_amount_product.to_string().split('#') product_amount is a list with items like that: 1 1#1 1#2 1 3#2#3 I want to break those into parts by split. However I get: 'int' object ...
How to break a string with numbers by symbol - split()?
I have a code: single_amount_product = product_amount[i] amount_products = single_amount_product.to_string().split('#') product_amount is a list with items like that: 1 1#1 1#2 1 3#2#3 I want to break those into parts by split. However I get: 'int' object has no attribute 'to_string' (with or without to_string()) Th...
[]
[]
[ "You can cast single_amount_product to a string before the split:\namount_products = str(single_amount_product).split('#')\n\n\n" ]
[ -1 ]
[ "python", "split", "string" ]
stackoverflow_0074190208_python_split_string.txt
Q: TypeError: create_bool(): incompatible function arguments I made a code detector that can detect hand, face, pose, etc. But when I run this in Visual Studio, I get the following error message: TypeError: create_bool(): incompatible function arguments. The following argument types are supported: 1. (arg0: bool)...
TypeError: create_bool(): incompatible function arguments
I made a code detector that can detect hand, face, pose, etc. But when I run this in Visual Studio, I get the following error message: TypeError: create_bool(): incompatible function arguments. The following argument types are supported: 1. (arg0: bool) -> mediapipe.python._framework_bindings.packet.Packet Invoked...
[ "I solved the problem by passing the named (keyword) arguments instead of positional arguments.\nThis ensured right argument is being passed at right place.\nself.mpHands.Hands(\n static_image_mode=True/False,\n model_complexity=yourNumber,\n smooth_landmarks=Tr...
[ 3, 2, 1, 1, 0 ]
[ "This seems to be related to the version of mediapipe or opencv you are using.\nPlease look out to the appropriate combinaison of version and you should be good\n" ]
[ -1 ]
[ "mediapipe", "python" ]
stackoverflow_0069103694_mediapipe_python.txt
Q: Receiving garbled text when attempting to scrape a certain website with Python using bs4 When attempting to scrape this website (TakeAlot) instead of getting normal html output I am instead receiving a little html but mostly garbled text. Here is what I am receiving: And here is my code: from bs4 import Beautiful...
Receiving garbled text when attempting to scrape a certain website with Python using bs4
When attempting to scrape this website (TakeAlot) instead of getting normal html output I am instead receiving a little html but mostly garbled text. Here is what I am receiving: And here is my code: from bs4 import BeautifulSoup import requests htmlSource = (requests. Get( "https://www.takealot.com/?gclid=CjwKCA...
[ "As @SharuzzamanAhmatRaslan commented, \"that is not a garbled text. that is an image encoded in base64\" - the href value of that link tag just happens to be that long.\nIf you wish to quickly view the overall structure of the html tree, you could use prettify with this custom formatter:\ndef truncateIfLong(str, m...
[ 0 ]
[]
[]
[ "beautifulsoup", "python", "web_scraping" ]
stackoverflow_0074171187_beautifulsoup_python_web_scraping.txt
Q: How do I skip a whole Python 'unittest' module at run time? I would like my Python unittest module to tell the test runner to skip it entirety under some situations (such as being unable to import a module or locate a critical resource). I can use @unittest.skipIf(...) to skip a unittest.TestCase class, but how do...
How do I skip a whole Python 'unittest' module at run time?
I would like my Python unittest module to tell the test runner to skip it entirety under some situations (such as being unable to import a module or locate a critical resource). I can use @unittest.skipIf(...) to skip a unittest.TestCase class, but how do I skip the entire module? Applying skips to every class is not s...
[ "If you look at the definition of unittest.skipIf and unittest.skip, you can see that the key is doing raise unittest.SkipTest(reason) when the test is executed. If you're okay with having it show up as one skipped test instead of several in the testrunner, you can simply raise unittest.SkipTest yourself on import:...
[ 24, 14, 8, 5, 4, 4, 3, 2, 2, 1, 0, 0, 0 ]
[]
[]
[ "python", "unit_testing" ]
stackoverflow_0012487532_python_unit_testing.txt
Q: How to get data some table data in a url using python I am trying to get some data in a website but my code is not really working. I am new to python and I am just trying to get some code working. Any idea or help to make this work is very welcome. Thanks in advance. import requests from bs4 import BeautifulSoup ...
How to get data some table data in a url using python
I am trying to get some data in a website but my code is not really working. I am new to python and I am just trying to get some code working. Any idea or help to make this work is very welcome. Thanks in advance. import requests from bs4 import BeautifulSoup headers = {"User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x...
[ "There's an API you can use to get the data:\nimport requests\n\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:104.0) Gecko/20100101 Firefox/104.0',\n}\n\npublic_key = \"GDOI7OSBDM3WPXWFT3RUPGGLV3Y5MKZJKNN4CZMQITUWWQRUF5IXCLZJ\"\nurl = f\"https://api.testnet.minepi.com/accounts/{p...
[ 1 ]
[]
[]
[ "beautifulsoup", "python", "python_requests", "web_scraping" ]
stackoverflow_0074190128_beautifulsoup_python_python_requests_web_scraping.txt
Q: Plot a 3D bar plot from a list of dictionaries in python So I Have a list of dictionaries like this [ { a:floatval, b:floatval, c:floatval }, { a:floatval, b:floatval, c:floatval } ....... ] I want to plot a 3D bar plot for this distribution.is there any way? A: Basically you can run a simple loop on this lis...
Plot a 3D bar plot from a list of dictionaries in python
So I Have a list of dictionaries like this [ { a:floatval, b:floatval, c:floatval }, { a:floatval, b:floatval, c:floatval } ....... ] I want to plot a 3D bar plot for this distribution.is there any way?
[ "Basically you can run a simple loop on this list of dictionary to get 3 lists corresponding to x axis, y axis and z axis.\nFind out the number of unique values on x axis, y axis. To populate z axis, make an array of size = no of unique entries on x * no of unique entries on y , now populate this array with the dat...
[ 0 ]
[]
[]
[ "bar_chart", "matplotlib", "python" ]
stackoverflow_0074190061_bar_chart_matplotlib_python.txt
Q: Try to download all the csv from the ipython console from datacamp In the working space I have bunch of csv 'summer_xxx1.csv' 'summer_xxx2.csv' 'summer_xxx3.csv' that is accesssable from the remote ipython command shell , I want to download them to local machine and try to make sense out of them. I have try foll...
Try to download all the csv from the ipython console from datacamp
In the working space I have bunch of csv 'summer_xxx1.csv' 'summer_xxx2.csv' 'summer_xxx3.csv' that is accesssable from the remote ipython command shell , I want to download them to local machine and try to make sense out of them. I have try following code import base64 from IPython.display import HTML def create_do...
[ "The .csv and .tsv files are posted on the overview page for the unit and you can download them from there.\n", "If you want to add all of the downloaded files to a Jupyter notebook, you can use the code here\n", "\nfirst, open any datacamp course , it contains dataset section\n\n\n\nclick on file , will be dow...
[ 0, 0, 0, 0 ]
[]
[]
[ "csv", "ipython", "pandas", "python" ]
stackoverflow_0048448472_csv_ipython_pandas_python.txt
Q: Closing an ad button in a website using selenium I was working on a web scraping project with Selenium and was trying to scrape news from the site https://www.businesstimes.com.sg/government-economy. But whenever I open the site with the selenium automated chrome window, one ad comes up in a popup which I want to ...
Closing an ad button in a website using selenium
I was working on a web scraping project with Selenium and was trying to scrape news from the site https://www.businesstimes.com.sg/government-economy. But whenever I open the site with the selenium automated chrome window, one ad comes up in a popup which I want to close. import selenium from selenium import webdriver...
[ "Element you trying to access is inside nested iframe.\nThis should work:\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.common.by import B...
[ 1 ]
[]
[]
[ "python", "selenium", "selenium_chromedriver", "selenium_webdriver", "web_scraping" ]
stackoverflow_0074188532_python_selenium_selenium_chromedriver_selenium_webdriver_web_scraping.txt
Q: Need to add an element to a set and I need the resulting set to be returned I see that the '+' operation is not supported in sets but supported for lists [1, 2, 3] + [4] # Works {1, 2, 3} + {4} # Error If I add an element to set using .add() func it modifies the original set but doesn't return the result inste...
Need to add an element to a set and I need the resulting set to be returned
I see that the '+' operation is not supported in sets but supported for lists [1, 2, 3] + [4] # Works {1, 2, 3} + {4} # Error If I add an element to set using .add() func it modifies the original set but doesn't return the result instead returns None type object. I don't want to modify the original set but I just n...
[ "welcome to Python\nIn python, type({}) is 'dict', however type({x1, x2, ..., x_n}) is 'set'.\nI suppose what you want is a set(to remove duplicated values).\nHere are two mistakes you made:\n\nYou should use 'set()' to initialize a set instead of '{}'\nYou should use '|' to insert a value to set instead of '+'\n\n...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074190178_python.txt
Q: Cannot assign contents of list attribute in Pybind11 defined class I have a sparse matrix implementation in C++, and I used pybind11 to expose it to python. Here is the problem: >>> D1 = phc.SparseMatrix(3, [[0],[1],[2]]) >>> D1.cData [[0], [1], [2]] >>> D1.cData[1] = [1,2] >>> D1.cData [[0], [1], [2]] #Should be ...
Cannot assign contents of list attribute in Pybind11 defined class
I have a sparse matrix implementation in C++, and I used pybind11 to expose it to python. Here is the problem: >>> D1 = phc.SparseMatrix(3, [[0],[1],[2]]) >>> D1.cData [[0], [1], [2]] >>> D1.cData[1] = [1,2] >>> D1.cData [[0], [1], [2]] #Should be [[0], [1,2], [2]] In python, I cannot change the contents of the Sparse...
[ "I found the answer in the pybind11 documentation here: https://pybind11.readthedocs.io/en/stable/advanced/cast/stl.html?highlight=opaque#making-opaque-types\nApparently, STL container data members can be overwritten in their entirety in python, but modification of the data member through list methods does not work...
[ 0 ]
[]
[]
[ "assignment_operator", "c++11", "pybind11", "python" ]
stackoverflow_0074187635_assignment_operator_c++11_pybind11_python.txt
Q: How can I pivot a dataframe? What is pivot? How do I pivot? Is this a pivot? Long format to wide format? I've seen a lot of questions that ask about pivot tables. Even if they don't know that they are asking about pivot tables, they usually are. It is virtually impossible to write a canonical question and answe...
How can I pivot a dataframe?
What is pivot? How do I pivot? Is this a pivot? Long format to wide format? I've seen a lot of questions that ask about pivot tables. Even if they don't know that they are asking about pivot tables, they usually are. It is virtually impossible to write a canonical question and answer that encompasses all aspects of...
[ "Question 1\n\nWhy do I get ValueError: Index contains duplicate entries, cannot reshape\n\nThis occurs because pandas is attempting to reindex either a columns or index object with duplicate entries. There are varying methods to use that can perform a pivot. Some of them are not well suited to when there are dup...
[ 434, 21, 14, 3, 2 ]
[]
[]
[ "group_by", "pandas", "pivot", "python" ]
stackoverflow_0047152691_group_by_pandas_pivot_python.txt
Q: Questions about Python time_to_sleep? When writing the code, the following code will be activated on time, saying it is stopped until the hour. However, to operate the code on time, it takes more than 59 minutes to run the code must run the code. Is there a way to make it work at 12pm by adjusting the minutes and ...
Questions about Python time_to_sleep?
When writing the code, the following code will be activated on time, saying it is stopped until the hour. However, to operate the code on time, it takes more than 59 minutes to run the code must run the code. Is there a way to make it work at 12pm by adjusting the minutes and hours instead of seconds in that code? ent...
[ "Instead of sleep, you can pause until a defined time:\nimport pause\nfrom datetime import datetime\n\npause.until(datetime(2022, 10, 25, 12))\n\n", "or you can do it like this:\nimport datetime\nimport time\n\n\nwhile datetime.datetime(2022,10,25,10,28,0) > datetime.datetime.now():\n time.sleep(30)\n pass\n...
[ 1, 1 ]
[]
[]
[ "python", "time" ]
stackoverflow_0074190356_python_time.txt
Q: Pivot tabele automation with Python I'm trying to automate pivot table creation using Python, but after runing my code I got an error: NameError: name 'run_excel' is not defined I've wrote my script on the bassis of this article : https://towardsdatascience.com/automate-excel-with-python-pivot-table-899eab993966 C...
Pivot tabele automation with Python
I'm trying to automate pivot table creation using Python, but after runing my code I got an error: NameError: name 'run_excel' is not defined I've wrote my script on the bassis of this article : https://towardsdatascience.com/automate-excel-with-python-pivot-table-899eab993966 Can someone explain to me how to solve thi...
[ "Your run_excel function is defined inside the pivot_table function therefore it's not in the scope of you main() function. Did not test this code but fixed the formatting below.\nimport win32com.client as win32\nimport pandas as pd\nimport numpy as np\nfrom pathlib import Path\nimport re\nimport sys\nwin32c = win3...
[ 1, 0 ]
[]
[]
[ "excel", "python" ]
stackoverflow_0070891958_excel_python.txt
Q: How to test kfp components with pytest I'm trying to local test a kubeflow component from kfp.v2.ds1 (which works on a pipeline) using pytest, but struggling with the input/output arguments together with fixtures. Here is a code example to illustrate the issue: First, I created a fixture to mock a dataset. This fi...
How to test kfp components with pytest
I'm trying to local test a kubeflow component from kfp.v2.ds1 (which works on a pipeline) using pytest, but struggling with the input/output arguments together with fixtures. Here is a code example to illustrate the issue: First, I created a fixture to mock a dataset. This fixture is also a kubeflow component. # ./fixt...
[ "After spending my afternoon on this, I finally figured out a way to pytest a python-based KFP component. As I found no other lead on this subject, I hope this can help:\nAccess the function to test\nThe trick is not to directly test the KFP component created by the @component decorator. However you can access the ...
[ 4, 2 ]
[]
[]
[ "kfp", "kubeflow", "kubeflow_pipelines", "pytest", "python" ]
stackoverflow_0073953744_kfp_kubeflow_kubeflow_pipelines_pytest_python.txt
Q: Mutiplying dataframe by -1 loses data I have an issue and I have no idea what is causing it.. I have a very very simply dataframe which looks like the following; A B 01/01/2022 -34 -102.34 02/01/2022 -4 -89.23 03/01/2022 -78 -43.2 . . . 31/12/2022 -32 -34.21 I simply need to convert this dataframe ...
Mutiplying dataframe by -1 loses data
I have an issue and I have no idea what is causing it.. I have a very very simply dataframe which looks like the following; A B 01/01/2022 -34 -102.34 02/01/2022 -4 -89.23 03/01/2022 -78 -43.2 . . . 31/12/2022 -32 -34.21 I simply need to convert this dataframe to positive numbers. When I do this with a...
[ "You likely have strings in your data, multiplying a string by an integer less than 1 converts to empty string:\ndf = pd.DataFrame({'A': [0,1,2], 'B': [0,'1',2]})\ndf*-1\n\noutput:\n A B\n0 0 0\n1 -1 \n2 -2 -2\n\nWorkaround: convert to_numeric:\ndf.apply(pd.to_numeric, errors='coerce')*-1\n\n# or\n# df.a...
[ 2 ]
[]
[]
[ "multiplication", "pandas", "python" ]
stackoverflow_0074190447_multiplication_pandas_python.txt
Q: How to datetime parse a non-standardized time format I would like to create datetime objects from a list of string timecodes like these. However, parse interprets incorrectly for my use case. from datetime import datetime from dateutil import parser timecodes = ['0:00', '0:01', '1:01', '10:01', '1:10:01'] dt = p...
How to datetime parse a non-standardized time format
I would like to create datetime objects from a list of string timecodes like these. However, parse interprets incorrectly for my use case. from datetime import datetime from dateutil import parser timecodes = ['0:00', '0:01', '1:01', '10:01', '1:10:01'] dt = parser.parse(timecode) print(dt) The list above comes from...
[ "This is a little tricky but should work:\nimport datetime\ntimecodes = ['0:00', '0:01', '1:01', '10:01', '1:10:01']\nzeroes = ['0','0','0']\ndt = []\nfor i in timecodes:\n sep = i.split(':')\n sep = zeroes[:3-len(sep)] + sep\n dt.append(str(datetime.timedelta(seconds = sum([int(s) * 60**(2-sep.index(s)) f...
[ 1, 1 ]
[]
[]
[ "datetime", "python", "timedelta" ]
stackoverflow_0074182030_datetime_python_timedelta.txt
Q: Correct way to implement producer consumer pattern in python multiprocessing Pool I want to implement producer-consumer pattern by using multiprocessing.pool.Pool Since the JoinableQueue cannot be used in Pool (would claim RuntimeError: JoinableQueue objects should only be shared between processes through inherita...
Correct way to implement producer consumer pattern in python multiprocessing Pool
I want to implement producer-consumer pattern by using multiprocessing.pool.Pool Since the JoinableQueue cannot be used in Pool (would claim RuntimeError: JoinableQueue objects should only be shared between processes through inheritance), I have to use multiprocessing.Manager() inspired by this answer. The question is:...
[ "You can use a multiprocessing.JoinableQueue by having your process pool workers accessing it as a global variable that gets initialized using a pool initializer:\nimport multiprocessing\n\ndef init_pool(input_q, output_q):\n global in_q, out_q\n in_q = input_q\n out_q = output_q\n\n\ndef worker():\n pr...
[ 2, 1, 0 ]
[]
[]
[ "multiprocessing", "producer_consumer", "python" ]
stackoverflow_0067363793_multiprocessing_producer_consumer_python.txt
Q: Creating a zip file in stream without directory structure I'm working on a Flask app to return a zip file to a user of a directory (a bunch of photos) but I don't want to include my server directory structure in the returned zip. Currently, I have this : def return_zip(): dir_to_send = '/dir/to/the/files' ...
Creating a zip file in stream without directory structure
I'm working on a Flask app to return a zip file to a user of a directory (a bunch of photos) but I don't want to include my server directory structure in the returned zip. Currently, I have this : def return_zip(): dir_to_send = '/dir/to/the/files' base_path = pathlib.Path(dir_to_send) data = io.BytesIO() ...
[ "We can use the arcname parameter to rename the file in the zip file. We can remove the directory structure by simply passing the write function the name of the file you want to add, this can be accomplished as follows:\ndef return_zip():\n dir_to_send = '/dir/to/the/files'\n base_path = pathlib.Path(dir_to_s...
[ 1 ]
[]
[]
[ "flask", "python", "python_zipfile", "stringio", "zip" ]
stackoverflow_0074190297_flask_python_python_zipfile_stringio_zip.txt
Q: time complexity of concatenating strings in python What is is the time complexity for the following function in Python? The function takes two inputs, string1 and string2, concatenates them together using "+" and returns the concatenated string. def concat_strings(string1, string2): return string1 + " " + stri...
time complexity of concatenating strings in python
What is is the time complexity for the following function in Python? The function takes two inputs, string1 and string2, concatenates them together using "+" and returns the concatenated string. def concat_strings(string1, string2): return string1 + " " + string2 is it O(n + m) where n is the length of string1 and...
[ "Yes, it is. Strings in Python are immutable, once-allocated data. So when you do string1 + string2, it will allocate a size n+m, then copy both strings.\n" ]
[ 0 ]
[]
[]
[ "python", "time_complexity" ]
stackoverflow_0074190529_python_time_complexity.txt
Q: Django rest framework post requests gets Forbidden (CSRF cookie not set.) I'm trying to do some post requests to my Django project using DRF but it gives me this error : Forbidden (CSRF cookie not set.) .. here is my code : serializers.py from django.contrib.auth.models import User class UserSerializer(serializer...
Django rest framework post requests gets Forbidden (CSRF cookie not set.)
I'm trying to do some post requests to my Django project using DRF but it gives me this error : Forbidden (CSRF cookie not set.) .. here is my code : serializers.py from django.contrib.auth.models import User class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fi...
[ "add router.register in your urls.py may solve this question\ni solved is after tried decotator @csrf_exempt and comment csrf in settings.py\n" ]
[ 0 ]
[]
[]
[ "django", "django_rest_framework", "python" ]
stackoverflow_0069688466_django_django_rest_framework_python.txt
Q: Change Font style and size in xlwings I am trying to change the font type, size and alignment with xlwings whatever I have it does not seem to work. nsh is equivalent to my sheet adjust row height Dimx =15 Dimy =15 nsh.range('A3').row_height = 15 nsh.range(1, Dimx+4).column_width = 5 nsh.range('A3').expan...
Change Font style and size in xlwings
I am trying to change the font type, size and alignment with xlwings whatever I have it does not seem to work. nsh is equivalent to my sheet adjust row height Dimx =15 Dimy =15 nsh.range('A3').row_height = 15 nsh.range(1, Dimx+4).column_width = 5 nsh.range('A3').expand()[:Dimy+3, :Dimx+5].api.Font=Bold It doe...
[ "Font is natively available:\nnsh.range('A3').expand()[:Dimy+3, :Dimx+5].font.bold = True\n\nSee https://docs.xlwings.org/en/latest/api.html#font\n" ]
[ 0 ]
[]
[]
[ "python", "xlwings" ]
stackoverflow_0074185756_python_xlwings.txt
Q: What does 'show_caches' and 'adaptive' arguments do in `dis.dis` function Python 3.11 introduces new two parameters to the dis.dis function, show_caches and adaptive. >>> import dis >>> >>> help(dis.dis) Help on function dis in module dis: dis(x=None, *, file=None, depth=None, show_caches=False, adaptive=False) ...
What does 'show_caches' and 'adaptive' arguments do in `dis.dis` function
Python 3.11 introduces new two parameters to the dis.dis function, show_caches and adaptive. >>> import dis >>> >>> help(dis.dis) Help on function dis in module dis: dis(x=None, *, file=None, depth=None, show_caches=False, adaptive=False) Disassemble classes, methods, functions, and other compiled objects. W...
[ "The show_caches argument is described at the very top of dis documentation since it is possible to pass it to many of the module's functions:\n\nChanged in version 3.11: Some instructions are accompanied by one or more inline cache entries, which take the form of CACHE instructions. These instructions are hidden ...
[ 4 ]
[]
[]
[ "python", "python_3.11" ]
stackoverflow_0074190554_python_python_3.11.txt
Q: How to limit and randomize the web output? Is there a way where I can limit a website generaot output and make the output more randomize since it outputs the name alphabetically. I tried to use limit and randomize i, but it doesn't seem to work import re from selenium import webdriver import os import json import ...
How to limit and randomize the web output?
Is there a way where I can limit a website generaot output and make the output more randomize since it outputs the name alphabetically. I tried to use limit and randomize i, but it doesn't seem to work import re from selenium import webdriver import os import json import requests import validators from urllib.request i...
[ "Ignoring the Test list of course that should generate 100 addresses as randomly put together as possible.\nTry this:\nimport random\n#Test = ['auth', 'access', 'account', 'admin', 'agree', 'blue', 'business', 'cdn', 'cl', 'click', 'confirm', 'download', 'enroll', 'find', 'group', 'install', 'login', 'mobile', 'my'...
[ 1, 0 ]
[]
[]
[ "jupyter_notebook", "python", "random" ]
stackoverflow_0074190429_jupyter_notebook_python_random.txt
Q: Django: Multi Tenancy : Override Tenant Context I have overridden django_tenants.utils.tenant_context to activate a timezone specific to the tenant. class NewTenantContext(tenant_context): ... I can use the new context like this with ALSTenantContext(tenant): ... All this works fine for a specific process to start...
Django: Multi Tenancy : Override Tenant Context
I have overridden django_tenants.utils.tenant_context to activate a timezone specific to the tenant. class NewTenantContext(tenant_context): ... I can use the new context like this with ALSTenantContext(tenant): ... All this works fine for a specific process to start for a tenant. But how do I make sure NewTenantContex...
[ "I am able to resolve this by overriding middleware django_tenants.middleware.TenantMainMiddleware\n" ]
[ 0 ]
[]
[]
[ "django_tenants", "multi_tenant", "python" ]
stackoverflow_0074154851_django_tenants_multi_tenant_python.txt
Q: Extract only first element of tuple I have a column on my data containing a list of two elements of tuples from POS tagging. I want to extract only the first element of these tuples and append it to another column. All code I found can only be applied to a single list of tuples. I would like to loop the code for e...
Extract only first element of tuple
I have a column on my data containing a list of two elements of tuples from POS tagging. I want to extract only the first element of these tuples and append it to another column. All code I found can only be applied to a single list of tuples. I would like to loop the code for every row as I have more than 100 rows. ...
[ "Well, if each row is stored in pos_tag_clean, you could do a list comprehension:\nword_clean = [[item[0] for item in row] for row in pos_tag_clean]\n\n" ]
[ 0 ]
[]
[]
[ "python", "tuples" ]
stackoverflow_0074190032_python_tuples.txt
Q: How to refer to hierachical column in a pandas query? # hierarchical indices and columns index = pd.MultiIndex.from_product([[2013, 2014], [1, 2]], names=['year', 'visit']) columns = pd.MultiIndex.from_product([['Bob', 'Guido', 'Sue'], ['HR', 'Temp']], ...
How to refer to hierachical column in a pandas query?
# hierarchical indices and columns index = pd.MultiIndex.from_product([[2013, 2014], [1, 2]], names=['year', 'visit']) columns = pd.MultiIndex.from_product([['Bob', 'Guido', 'Sue'], ['HR', 'Temp']], names=['subject', 'type']) # mock some data data...
[ "You can't use MultiIndexes with query.\n(Well, you can to some limit use health_data.query('@health_data.Bob.HR > 35'), but this has many flaws, and you won't be able to do this with a sublevel only).\nYou can use xs instead to select your levels:\n# is Bod/HR > 35?\nm1 = health_data[('Bob', 'HR')].gt(35)\n# is an...
[ 4 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074190736_pandas_python.txt
Q: How do you convert a print output into a Pandas data frame in Python? I've got the following lines of code and I'd love to turn them into a Pandas data frame, not as a print output. embedder = SentenceTransformer('all-MiniLM-L6-v2') corpus = ['About us. About Us · Our Coffees · Starbucks Stories & News · Starbuck...
How do you convert a print output into a Pandas data frame in Python?
I've got the following lines of code and I'd love to turn them into a Pandas data frame, not as a print output. embedder = SentenceTransformer('all-MiniLM-L6-v2') corpus = ['About us. About Us · Our Coffees · Starbucks Stories & News · Starbucks® Ready to Drink · Foodservice Coffee · Customer Service · Tax Strategy 2...
[ "You can save all the result in a Python list and the convert it to a pandas Dataframe. There are a lot of examples out there but here you can check one out.\nSo your code should be someting like this:\nembedder = SentenceTransformer('all-MiniLM-L6-v2')\n\ncorpus = [\n 'About us. About Us · Our Coffees · Starbuc...
[ 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074190639_pandas_python.txt
Q: Is there a way to remove quotes from string Is there a way to remove quotes from string in python. For example, I am trying to get ticker name through equest.args.getlist('tickers') that returns 'Infosys' and which is fine But there is a small issue here. There is a quote here so what happens in the next line is p...
Is there a way to remove quotes from string
Is there a way to remove quotes from string in python. For example, I am trying to get ticker name through equest.args.getlist('tickers') that returns 'Infosys' and which is fine But there is a small issue here. There is a quote here so what happens in the next line is pd.read_sql_query('select * from [dbo].' +str(tic...
[ "It's because you converted a list returned by getlist() into a string.\nYou should use request.args.get(), instead of getlist(), like this.\ntickers = request.args.get('tickers')\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074189504_python.txt
Q: Expand environment variable: ox.expandvars() only working in Json dict not in string? I have an .env File with the following content: SOME_PATH_VARIABLE = PATH_TO_FOLDER I Want to read in a nested Json file ( Log file config ) and expand the SOME_PATH_VARIABLE via os.path.expandvars(). The Json file looks roughly...
Expand environment variable: ox.expandvars() only working in Json dict not in string?
I have an .env File with the following content: SOME_PATH_VARIABLE = PATH_TO_FOLDER I Want to read in a nested Json file ( Log file config ) and expand the SOME_PATH_VARIABLE via os.path.expandvars(). The Json file looks roughly like this: { "version": 1, "disable_existing_loggers": false, "formatters": { ...
[ "According to the docs:\n\nChanged in version 3.6: Accepts a path-like object.\n\nSo I'm guessing that you updated to python 3.6 or later and a JSON string doesn't work with expandvars() since it isn't a path-like object.\nOn the other hand, the string value from j_dict['handlers']['MY_CUSTOM_HANDLER']['filename'] ...
[ 1 ]
[]
[]
[ "dictionary", "expand", "json", "python", "string" ]
stackoverflow_0074190660_dictionary_expand_json_python_string.txt
Q: Is there a way to auto generate a __str__() implementation in python? Being tired manually implementing a string representation for my classes, I was wondering if there is a pythonic way to do that automatically. I would like to have an output that covers all the attributes of the class and the class name. Here is...
Is there a way to auto generate a __str__() implementation in python?
Being tired manually implementing a string representation for my classes, I was wondering if there is a pythonic way to do that automatically. I would like to have an output that covers all the attributes of the class and the class name. Here is an example: class Foo(object): attribute_1 = None attribute_2 = No...
[ "You can iterate instance attributes using vars, dir, ...:\ndef auto_str(cls):\n def __str__(self):\n return '%s(%s)' % (\n type(self).__name__,\n ', '.join('%s=%s' % item for item in vars(self).items())\n )\n cls.__str__ = __str__\n return cls\n\n@auto_str\nclass Foo(ob...
[ 60, 2, 2 ]
[]
[]
[ "boilerplate", "python" ]
stackoverflow_0032910096_boilerplate_python.txt
Q: How to can I obtain a matrix transpose by a Python script? How to check matrix transpose? Can my code be simplified with an available Python function? And why if I test my code with the following input I obtain the error out of range? : Matrix 1 = 3 x 2 (1,1): 1 (1,2): 2 (2,1): 3 (2,2): 4 (3,1): 5 (3,2): 6 Matrix ...
How to can I obtain a matrix transpose by a Python script?
How to check matrix transpose? Can my code be simplified with an available Python function? And why if I test my code with the following input I obtain the error out of range? : Matrix 1 = 3 x 2 (1,1): 1 (1,2): 2 (2,1): 3 (2,2): 4 (3,1): 5 (3,2): 6 Matrix 2 = 3 x 2 (1,1): 1 (1,2): 4 (2,1): 2 (2,2): 5 (3,1): 3 (3,2): 6 ...
[ "It is quite simple. If matrix 1 is (a, b) shape so matrix 2 should be (b, a). Here your first matrix is (3, 2) matrix so second matrix cant be (3, 2) again but (2, 3) and it will work. You can read more about transpose matrix here.\n" ]
[ 0 ]
[]
[]
[ "outofrangeexception", "python", "python_3.x" ]
stackoverflow_0074190722_outofrangeexception_python_python_3.x.txt
Q: how to simultaneously run two cmd line using python(ngrok and localhost)? os.system('python -m http.server 8000') os.system("ngrok http 8000") The 'ngrok command' runs only after the above command, how to run both commands simultaneously? I even tried to run it in different python file. A: Running two things tr...
how to simultaneously run two cmd line using python(ngrok and localhost)?
os.system('python -m http.server 8000') os.system("ngrok http 8000") The 'ngrok command' runs only after the above command, how to run both commands simultaneously? I even tried to run it in different python file.
[ "Running two things truly simultaneously isn't possible based on the way instruction pipelines work at a computer architecture level.\nIf you want them to be run from one command, you can use &:\nos.system('python -m http.server 8000 & ngrok http 8000\")\n\nThis will run them concurrently in the same way you run co...
[ 0, 0 ]
[]
[]
[ "cmd", "command", "ngrok", "python", "server" ]
stackoverflow_0074190682_cmd_command_ngrok_python_server.txt
Q: Can I predict different targets and use different features of my saved model? I'm curious if I can load my saved trained model and predict different features and target, is that even possible? or I have to make several models for all the possibilities? Because I want to deploy ML model into Streamlit web app and u...
Can I predict different targets and use different features of my saved model?
I'm curious if I can load my saved trained model and predict different features and target, is that even possible? or I have to make several models for all the possibilities? Because I want to deploy ML model into Streamlit web app and users can choose features and target whatever they want, just something like this
[ "You can use your saved model for prediction, If you want to move to cloud then you can retrain the model, save the saved model(say h5) in the cloud(say AWS) then you can fetch predictions from in there. Plus it would give you the flexibility to constantly train the model and used the trained model.\n" ]
[ 1 ]
[]
[]
[ "machine_learning", "python", "streamlit" ]
stackoverflow_0074188285_machine_learning_python_streamlit.txt
Q: discord bot to play music, and followed a yt tutorial /home/runner/AdequateEmbarrassedAmoeba/music.py:48: RuntimeWarning: coroutine 'BotBase.add_cog' was never awaited client.add_cog(music(client)) RuntimeWarning: Enable tracemalloc to get the object allocation traceback 2022-10-24 12:01:22 INFO discord.clie...
discord bot to play music, and followed a yt tutorial
/home/runner/AdequateEmbarrassedAmoeba/music.py:48: RuntimeWarning: coroutine 'BotBase.add_cog' was never awaited client.add_cog(music(client)) RuntimeWarning: Enable tracemalloc to get the object allocation traceback 2022-10-24 12:01:22 INFO discord.client logging in using static token 2022-10-24 12:01:23 INFO ...
[ "You need to await in your last line, which is also mentioned in the error message.\nSo, change this\ndef setup(client):\n client.add_cog(music(client))\n\nto this\ndef setup(client):\n await client.add_cog(music(client))\n\nBut both of these are just warnings, so you should be able to ignore them but they could ...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074190795_python.txt
Q: Building a graph from a list or dict - Python I have an example list of word lists like this: [['rowerowy', 'rower'] ['rowerzysta', 'rower'] ['domeczek', 'domek'] ['domek', 'dom'] ['rowerzystka', 'rowerzysta']] and I need to concatenate words into dependency groups, we are making a graph of connections between t...
Building a graph from a list or dict - Python
I have an example list of word lists like this: [['rowerowy', 'rower'] ['rowerzysta', 'rower'] ['domeczek', 'domek'] ['domek', 'dom'] ['rowerzystka', 'rowerzysta']] and I need to concatenate words into dependency groups, we are making a graph of connections between the forms: rowerowy --> rower <-- rowerzysta <--- ...
[ "Here is a solution using the networkx library:\nimport networkx as nx\n\ndata = [['rowerowy', 'rower'],\n['rowerzysta', 'rower'],\n['domeczek', 'domek'],\n['domek', 'dom'],\n['rowerzystka', 'rowerzysta']]\n\n\n#instantiate graph\nG = nx.Graph()\n\n# add word connections as edges\nG.add_edges_from(data)\n\nnx.draw...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074190437_python.txt
Q: ResolutionImpossible from pip despite no apparent version conflict Sometimes pip complains of conflicting dependencies despite there being no actual version conflict, for example in this case even after removing the specific version of elastic-apm from constraints.txt entirely (just leaving it in mypackage's setup...
ResolutionImpossible from pip despite no apparent version conflict
Sometimes pip complains of conflicting dependencies despite there being no actual version conflict, for example in this case even after removing the specific version of elastic-apm from constraints.txt entirely (just leaving it in mypackage's setup.py) it still failed as follows: ERROR: Cannot install elastic-apm becau...
[ "It turns out the problem was that LOCALDIR did not contain a wheel for the current platform.\nThe folder contained this wheel, but not a corresponding Windows wheel (our mistake)\nelastic_apm-6.10.1-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl\n\nHowever the pip...
[ 0 ]
[]
[]
[ "pip", "python" ]
stackoverflow_0074190982_pip_python.txt
Q: Selenium Xpath to get Phone Number from Kijiji I am trying to extract the number from number field in Kijiji, When I write the Xpath in console it identifying and highlighting the filed too but when I run the code I am getting NoSuchElementException exception. Here is the screenshot of DOM And Here is the Screens...
Selenium Xpath to get Phone Number from Kijiji
I am trying to extract the number from number field in Kijiji, When I write the Xpath in console it identifying and highlighting the filed too but when I run the code I am getting NoSuchElementException exception. Here is the screenshot of DOM And Here is the Screenshot of the code and Error Screenshots of Xpath whic...
[ "Try the below code:\nSome of them don't have the phone number, so I updated them as 'No Phone Number Available'.\n# add the below import statement\nfrom selenium.webdriver.chrome.service import Service\n\n# use the below driver instantiation statement instead of yours.\ndriver = webdriver.Chrome(service=Service(\"...
[ 0 ]
[]
[]
[ "python", "selenium" ]
stackoverflow_0074187588_python_selenium.txt
Q: Get browser version using selenium webdriver How would I get the browser version being used? >>> from selenium import webdriver >>> driver = webdriver.Firefox() >>> print version <-- how to do this? Firefox 12.0 A: This answer led me down the right path but is specific to python and the topic is more broad. ...
Get browser version using selenium webdriver
How would I get the browser version being used? >>> from selenium import webdriver >>> driver = webdriver.Firefox() >>> print version <-- how to do this? Firefox 12.0
[ "This answer led me down the right path but is specific to python and the topic is more broad. So, I'm adding an answer for Java which was a bit more tricky. At this time I am using selenium 2.25.0.\n//make sure have correct import statements - I had to add these\nimport org.openqa.selenium.Capabilities;\nimport o...
[ 41, 39, 7, 7, 3, 2, 1, 1, 0 ]
[]
[]
[ "firefox", "geckodriver", "python", "selenium", "selenium_webdriver" ]
stackoverflow_0012556163_firefox_geckodriver_python_selenium_selenium_webdriver.txt
Q: How to I manipulate a value in a class in Python? So i'am new into classes in python, and i was struggling a little bit here :(. So I wanted to make a class point which contained coordinates (x, y). First I made a function which set the values and afterwards a function to print the values in a tuple. But then i wa...
How to I manipulate a value in a class in Python?
So i'am new into classes in python, and i was struggling a little bit here :(. So I wanted to make a class point which contained coordinates (x, y). First I made a function which set the values and afterwards a function to print the values in a tuple. But then i wanted to manipulate the y coordinate to reflect along th...
[ "As it was already pointed out, reflect_x() returns default value (None), since you didn't put any return there. If you are used to the programming language that endorses chaining methods, you should add return self in functions you wanna use like that.\nclass Point:\n def __init__(self, x, y):\n self.x = x\n...
[ 3, 1, 1, 1 ]
[]
[]
[ "class", "function", "python" ]
stackoverflow_0074190346_class_function_python.txt
Q: Python: Randomly remove duplicates among multiple lists Given x = [0,1,2,3] y = [0,4,3,5] z = [1,6,7,8] I need something that removes all duplicates over all three lists randomly. So the desired outcome would be something like: x = [1,2,3] y = [0,4,5] z = [6,7,8] Running it another time should give a different d...
Python: Randomly remove duplicates among multiple lists
Given x = [0,1,2,3] y = [0,4,3,5] z = [1,6,7,8] I need something that removes all duplicates over all three lists randomly. So the desired outcome would be something like: x = [1,2,3] y = [0,4,5] z = [6,7,8] Running it another time should give a different distribution like for example: x = [0,1,2,3] y = [4,5] z = [6,...
[ "If you start randomly (means x,y, z which one to treat first) you could get what you want.\nimport random\ndef rm_dup(**kwargs):\n inp = kwargs\n duplicate = set()\n keys = list(inp.keys())\n random.shuffle(keys)\n out = {k: [] for k in inp.keys()}\n\n for key in keys:\n for v in inp[key]:...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074190488_python.txt
Q: try, except and finally in python def finding(a,b): try: result=a+b return result except TypeError: return "please type only num" finally: return "this line will get print at last" print(finding (5, 2)) I'm getting the output from the finally, but I'm not getting the...
try, except and finally in python
def finding(a,b): try: result=a+b return result except TypeError: return "please type only num" finally: return "this line will get print at last" print(finding (5, 2)) I'm getting the output from the finally, but I'm not getting the output from the try.
[]
[]
[ "Change your last two returns to print statements:\ndef finding(a,b):\n\n try:\n result=a+b\n return result\n except TypeError:\n print(\"please type only num\")\n finally:\n print(\"this line will get print at last\")\n\nprint(finding (5, 2)) \n\n" ]
[ -1 ]
[ "exception", "python", "try_catch_finally" ]
stackoverflow_0074190969_exception_python_try_catch_finally.txt
Q: Automatically assign method arguments to instance variables Is there a way in Python to declare instance variables from the methods arguments without the need for boilerplate writing? For example, is there a way for self.foo, self.bar and all other arguments to be automatically declared? def __init__(self, foo, ba...
Automatically assign method arguments to instance variables
Is there a way in Python to declare instance variables from the methods arguments without the need for boilerplate writing? For example, is there a way for self.foo, self.bar and all other arguments to be automatically declared? def __init__(self, foo, bar, ..., last): self.foo = foo self.bar = bar ... ...
[ "There actually is, though I think it's a very ugly way\nclass Foo:\n def __init__(self, **kwargs):\n for name, value in kwargs.items():\n setattr(self, name, value)\n\n\nFoo(name='foo', baz=123, bar=True, last=None)\n\nAs Tim Roberts suggested in the comments, using a namedtuple is a much bett...
[ 0, 0, 0, 0 ]
[]
[]
[ "class", "python", "variables" ]
stackoverflow_0068369586_class_python_variables.txt
Q: How to create a new list of integers from a parent list containing integers and string? List=["2","10","15","23","exit"] # Output required List_new = [2,10,15,23] A: Use isnumeric: [int(item) for item in List if item.isnumeric()] A: You can use isnumeric >>> List=["2","10","15","23","exit"] >>> output = [int(...
How to create a new list of integers from a parent list containing integers and string?
List=["2","10","15","23","exit"] # Output required List_new = [2,10,15,23]
[ "Use isnumeric:\n[int(item) for item in List if item.isnumeric()]\n\n", "You can use isnumeric\n>>> List=[\"2\",\"10\",\"15\",\"23\",\"exit\"]\n>>> output = [int(i) for i in List if i.isnumeric()]\n>>> print(output)\n[2, 10, 15, 23]\n\n", "You can use .isdigit()\nList_given =[\"2\",\"10\",\"15\",\"23\",\"exit\"...
[ 3, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074189703_python.txt
Q: How to add *or* update columns in a pandas DataFrame? I have an existing DataFrame, and a method that computes a few columns to add to that DataFrame. I currently use pd.concat([left, right], axis=1). When I call this method a second time, however, it adds the columns again (with the same name). With the following...
How to add *or* update columns in a pandas DataFrame?
I have an existing DataFrame, and a method that computes a few columns to add to that DataFrame. I currently use pd.concat([left, right], axis=1). When I call this method a second time, however, it adds the columns again (with the same name). With the following sample data frames left and right: left = pd.DataFrame({'o...
[ "Take intersection and drop columns then merge on index :\nleft = left.drop(left.columns.intersection(right.columns),1).merge(right, left_index=True, right_index=True)\n\nprint(left)\n two one NEW\n0 2 22 33\n1 3 22 33\n2 4 22 33\n\n", "Alternative solution, but it only add new columns, n...
[ 3, 1, 1, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0053276162_pandas_python.txt
Q: LabelEncoder: TypeError: '>' not supported between instances of 'float' and 'str' I'm facing this error for multiple variables even treating missing values. For example: le = preprocessing.LabelEncoder() categorical = list(df.select_dtypes(include=['object']).columns.values) for cat in categorical: print(cat) ...
LabelEncoder: TypeError: '>' not supported between instances of 'float' and 'str'
I'm facing this error for multiple variables even treating missing values. For example: le = preprocessing.LabelEncoder() categorical = list(df.select_dtypes(include=['object']).columns.values) for cat in categorical: print(cat) df[cat].fillna('UNK', inplace=True) df[cat] = le.fit_transform(df[cat]) # p...
[ "This is due to the series df[cat] containing elements that have varying data types e.g.(strings and/or floats). This could be due to the way the data is read, i.e. numbers are read as float and text as strings or the datatype was float and changed after the fillna operation.\nIn other words \n\npandas data type '...
[ 154, 8, 2, 0, 0 ]
[]
[]
[ "pandas", "python", "scikit_learn" ]
stackoverflow_0046406720_pandas_python_scikit_learn.txt
Q: Automatically initialize instance variables? I have a python class that looks like this: class Process: def __init__(self, PID, PPID, cmd, FDs, reachable, user): followed by: self.PID=PID self.PPID=PPID self.cmd=cmd ... Is there any way to autoinitialize these instance variabl...
Automatically initialize instance variables?
I have a python class that looks like this: class Process: def __init__(self, PID, PPID, cmd, FDs, reachable, user): followed by: self.PID=PID self.PPID=PPID self.cmd=cmd ... Is there any way to autoinitialize these instance variables, like C++'s initialization list? It would spare...
[ "You can use a decorator:\nfrom functools import wraps\nimport inspect\n\ndef initializer(func):\n \"\"\"\n Automatically assigns the parameters.\n\n >>> class process:\n ... @initializer\n ... def __init__(self, cmd, reachable=False, user='root'):\n ... pass\n >>> p = process('...
[ 125, 62, 37, 30, 29, 15, 7, 5, 3, 3, 2, 2, 1, 1, 0, 0, 0 ]
[]
[]
[ "class", "initialization_list", "python" ]
stackoverflow_0001389180_class_initialization_list_python.txt
Q: Dynamic function signature in help() I am building a library that automatically discovers remote API endpoints and populates an object with methods corresponding to the inferred endpoints. The dynamically created methods have the following structure: def proxy(*args, **kwds): # 1. Validate arguments: Do argume...
Dynamic function signature in help()
I am building a library that automatically discovers remote API endpoints and populates an object with methods corresponding to the inferred endpoints. The dynamically created methods have the following structure: def proxy(*args, **kwds): # 1. Validate arguments: Do arguments match remote API? # 2. Forward cal...
[ "Poking around the source of the inspect module, I realized that the information in __signature__ is honored. Therefore, one can create a new, more informative signature dynamically as follows\nfrom inspect import Signature, Parameter\n\ndef proxy(*args, **kwds):\n pass\n\nuser_param = Parameter(\"user\", kind=P...
[ 1 ]
[]
[]
[ "adapter", "python" ]
stackoverflow_0074178236_adapter_python.txt
Q: Why QWebEngineView doesn't show my image? from PyQt5.QtWebEngineWidgets import QWebEngineView ... ... q = QWebEngineView() q.setHtml('''<img border="0" height="200" src="E:/img.png" style="display: block; text-align: left;" width="600">''') ... ... above is the only code I deal with webengineview. I want to show ...
Why QWebEngineView doesn't show my image?
from PyQt5.QtWebEngineWidgets import QWebEngineView ... ... q = QWebEngineView() q.setHtml('''<img border="0" height="200" src="E:/img.png" style="display: block; text-align: left;" width="600">''') ... ... above is the only code I deal with webengineview. I want to show image within the webengineview, but it doesn't ...
[ "I suppose the issue might be connected to wrong path you specified. I assume you use Windows, and then the correct src would be E:\\img.png (notice the slash has opposite direction).\n" ]
[ 0 ]
[]
[]
[ "html", "pyqt", "pyqt5", "python", "qt" ]
stackoverflow_0074191037_html_pyqt_pyqt5_python_qt.txt
Q: Clear valid form after it is submitted I want to reset the form after it validates. Currently the form will still show the previous data after it is submitted and valid. Basically, I want the form to go back to the original state with all fields clean. What is the correct to do this? @mod.route('/', methods=['G...
Clear valid form after it is submitted
I want to reset the form after it validates. Currently the form will still show the previous data after it is submitted and valid. Basically, I want the form to go back to the original state with all fields clean. What is the correct to do this? @mod.route('/', methods=['GET', 'POST']) def home(): form = NewRegi...
[ "The issue is that you're always rendering the form with whatever data was passed in, even if that data validated and was handled. In addition, the browser stores the state of the last request, so if you refresh the page at this point the browser will re-submit the form.\nAfter handling a successful form request, ...
[ 44, 8, 0, 0 ]
[]
[]
[ "flask", "flask_wtforms", "python", "wtforms" ]
stackoverflow_0031945329_flask_flask_wtforms_python_wtforms.txt
Q: Scheduled tasks in Django to update data in the models (database) I need to schedule tasks via Pythonanywhere, to update some records in my database. As an example, I do have Events as models: models.py class Events(models.Model): event_title = models.CharField(max_length=300) event_info = models.TextField...
Scheduled tasks in Django to update data in the models (database)
I need to schedule tasks via Pythonanywhere, to update some records in my database. As an example, I do have Events as models: models.py class Events(models.Model): event_title = models.CharField(max_length=300) event_info = models.TextField(max_length=2000) event_date = models.DateField(default=now) ev...
[ "ImportError has nothing to do with the database, it's a Python error raised on your line 1. Its description is pretty accurate: \"attempted relative import with no known parent package\"\n" ]
[ 1 ]
[]
[]
[ "django", "python", "pythonanywhere", "scheduled_tasks" ]
stackoverflow_0074191063_django_python_pythonanywhere_scheduled_tasks.txt
Q: How to select images with numbered filenames and append all images together horizontally I have several image files whose names are numbered 1-300. (frame1jpg, .. ,frame300.jpg) I would like to append all images together horizontally by select (n) and Start/End file. And I can change (n) and start/end files. Exam...
How to select images with numbered filenames and append all images together horizontally
I have several image files whose names are numbered 1-300. (frame1jpg, .. ,frame300.jpg) I would like to append all images together horizontally by select (n) and Start/End file. And I can change (n) and start/end files. Example1: (n) = 5, start frame5.jpg end frame30.jpg. After that append from frame5.jpg, frame10.jp...
[ "Just get the list of filenames given your start, end and step:\ndef get_images(start, end, step):\n file_list = [f\"frame{i}.jpg\" for i in range(start, end, step)] \n return [Image.open(x) for x in file_list]\n\nimages = get_images(start, end, step)\n\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0074191016_python.txt
Q: isna search on mulitple columns/rows gives error: duplicate columns & possible reduce dimensionality I'm trying to search for NaN values in different columns and rows and want to show all rows. My dataset: import pandas as pd df = pd.read_excel('./file.xlsx') df = df.replace(' ', np.nan) df.head() ...
isna search on mulitple columns/rows gives error: duplicate columns & possible reduce dimensionality
I'm trying to search for NaN values in different columns and rows and want to show all rows. My dataset: import pandas as pd df = pd.read_excel('./file.xlsx') df = df.replace(' ', np.nan) df.head() col1 col2 col3 row1 NaN NaN test row2 ...
[ "You need double square brackets to slice with a list of columns:\ndf[df[['col1', 'col2', 'col3']].isna().any(axis=1)]\n\nAlternative using a named list:\ncols = ['col1', 'col2', 'col3']\n\ndf[df[cols].isna().any(axis=1)]\n\noutput:\n col1 col2 col3\nrow1 NaN NaN test\nrow3 words place NaN...
[ 1 ]
[]
[]
[ "keyerror", "nan", "pandas", "python" ]
stackoverflow_0074191175_keyerror_nan_pandas_python.txt
Q: Whats wrong in my code my code for scheduled messages on discord.py on replit so I've been trying to make my discord bot send a message every day at 12:30 UCT but i cant seem to get my code to work I'm not sure if its not working because of incorrect code or because its on replit or whatever else the issue could b...
Whats wrong in my code my code for scheduled messages on discord.py on replit
so I've been trying to make my discord bot send a message every day at 12:30 UCT but i cant seem to get my code to work I'm not sure if its not working because of incorrect code or because its on replit or whatever else the issue could be as i get no errors from this it just send the message once it loads online and th...
[ "await asyncio.sleep is non blocking. Your script will execute beyond that statement. You will need to use time.sleep, which that will block all execution of code until the timer has run out.\nSee here for a more in depth explanation and how to use this in functions:\nasyncio.sleep() vs time.sleep()\nA way to imple...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074191050_python.txt
Q: How do I delete items from a dictionary while iterating over it? Can I delete items from a dictionary in Python while iterating over it? I want to remove elements that don't meet a certain condition from the dictionary, instead of creating an entirely new dictionary. Is the following a good solution, or are there ...
How do I delete items from a dictionary while iterating over it?
Can I delete items from a dictionary in Python while iterating over it? I want to remove elements that don't meet a certain condition from the dictionary, instead of creating an entirely new dictionary. Is the following a good solution, or are there better ways? for k, v in mydict.items(): if k == val: del ...
[ "For Python 3+:\n>>> mydict\n{'four': 4, 'three': 3, 'one': 1}\n\n>>> for k in list(mydict.keys()):\n... if mydict[k] == 3:\n... del mydict[k]\n\n>>> mydict\n{'four': 4, 'one': 1}\n\nThe other answers work fine with Python 2 but raise a RuntimeError for Python 3:\n\nRuntimeError: dictionary changed size...
[ 403, 113, 31, 25, 12, 12, 11, 4, 3, 2, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0005384914_dictionary_python.txt
Q: How to zip a file in python? I have been trying to make a python script to zip a file with the zipfile module. Although the text file is made into a zip file, It doesn't seem to be compressing it; testtext.txt is 1024KB whilst testtext.zip (The code's creation) is also equal to 1024KB. However, if I compress testt...
How to zip a file in python?
I have been trying to make a python script to zip a file with the zipfile module. Although the text file is made into a zip file, It doesn't seem to be compressing it; testtext.txt is 1024KB whilst testtext.zip (The code's creation) is also equal to 1024KB. However, if I compress testtext.txt manually in File Explorer,...
[ "Well that's odd. Python's zipfile defaults to the stored compression method, which does not compress! (Why would they do that?)\nYou need to specify a compression method. Use ZIP_DEFLATED, which is the most widely supported.\nimport zipfile\nzip = zipfile.ZipFile(\"stuff.zip\", \"w\", zipfile.ZIP_DEFLATED)\nzip.wr...
[ 4, 0 ]
[ "https://docs.python.org/3/library/zipfile.html#:~:text=with%20ZipFile(%27spam.zip%27%2C%20%27w%27)%20as%20myzip%3A%0A%20%20%20%20myzip.write(%27eggs.txt%27)\nIn the docs they have it written with a with statement so I would try that first.\nEdit:\nI just came back to say that you have to specify your compression m...
[ -1 ]
[ "compression", "python", "python_module", "txt", "zip" ]
stackoverflow_0071277957_compression_python_python_module_txt_zip.txt
Q: How to write all the sentences with the word "apple" from a txt file I have tried this using regex, loops and simple functions as well but cannot figure out anything. here are the few codes I have tried. import re fp = open("apple.txt") re.findall(r"([^.]*?apple[^.]*\.)",fp) A: with open("./WABA-crash.txt", "r")...
How to write all the sentences with the word "apple" from a txt file
I have tried this using regex, loops and simple functions as well but cannot figure out anything. here are the few codes I have tried. import re fp = open("apple.txt") re.findall(r"([^.]*?apple[^.]*\.)",fp)
[ "with open(\"./WABA-crash.txt\", \"r\") as input:\n content = input.read().replace('\\n', '')\nsentences = list(map(str.strip, content.split(\".\")))\nwith open(\"./resultFile.txt\", \"w\") as output:\n for result in sentences:\n if ('police' in result or 'Police' in result):\n output.write(...
[ 1, 1 ]
[]
[]
[ "nlp", "nltk", "python" ]
stackoverflow_0074190959_nlp_nltk_python.txt
Q: Python - get dict's keys' values if matching specific name I have two list comprehensions that do exactly same thing but differ in one dict's element - key of stopped and warning. logs_warning = [ DDLog(self.HOST, "dms", log["name"], log["StopReason"], f"env:{env}").to_log() for env in self.envs for lo...
Python - get dict's keys' values if matching specific name
I have two list comprehensions that do exactly same thing but differ in one dict's element - key of stopped and warning. logs_warning = [ DDLog(self.HOST, "dms", log["name"], log["StopReason"], f"env:{env}").to_log() for env in self.envs for log in tasks[env]["warning"]["tasks"] ] logs_stopped = [ DDLo...
[ "Just an additional for-loop in the list comprehension:\nlogs_stopped = [\n DDLog(self.HOST, \"dms\", log[\"name\"], log[\"StopReason\"], f\"env:{env}\").to_log()\n for env in self.envs\n for key in (\"warning\", \"stopped\")\n for log in tasks[env][key][\"tasks\"]\n]\n\n", "Did you try this? I tried ...
[ 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074191077_python.txt
Q: How do i make Xlsxwriter clear its memory? Im building a web scraping script with python that gets output to Excel. Also using PyQt5 for user interface. Im having trouble executing the function more than 1 time. Function is basically: Delete Xlsx file if its already there Create new workbook Read the keywords to ...
How do i make Xlsxwriter clear its memory?
Im building a web scraping script with python that gets output to Excel. Also using PyQt5 for user interface. Im having trouble executing the function more than 1 time. Function is basically: Delete Xlsx file if its already there Create new workbook Read the keywords to search with for loop (Example: japanese katana, ...
[ "You are creating a new xlsxwriter object each time so that gives you a clean instance every time. So that is not causing the issue you are seeing.\nThe issue is more likely that search_list isn't cleared between calls. This could result in having the same search query, such as 'japanese katana' more that once in t...
[ 2 ]
[]
[]
[ "garbage_collection", "memory_management", "pyqt5", "python", "xlsxwriter" ]
stackoverflow_0074190315_garbage_collection_memory_management_pyqt5_python_xlsxwriter.txt
Q: Add non-datetime variables in SQL python as function parameters I have a function that executes many SQL queries with different dates. What I want is to pass all dates and other query variables as function parameters and then just execute the function. I have figured out how to do this for datetime variables as be...
Add non-datetime variables in SQL python as function parameters
I have a function that executes many SQL queries with different dates. What I want is to pass all dates and other query variables as function parameters and then just execute the function. I have figured out how to do this for datetime variables as below. But I also have a query that looks at specific campaign_names in...
[]
[]
[ "Please, do not use f-strings for creating SQL queries!\nMost likely, any library you use for accessing a database already has a way of creating queries: SQLite docs (check code examples).\nAnother example: cur.execute(\"SELECT * FROM tasks WHERE priority = ?\", (priority,)).\nNot only this way is safer (fixes SQL ...
[ -2 ]
[ "function", "python", "sql", "variables" ]
stackoverflow_0074191183_function_python_sql_variables.txt
Q: Pyraf rspectext RuntimeError: dictionary keys changed during iteration I have to convert a classic ascii file with two columns (wavelength and flux) into a fits file and I used rspectext from pyraf (with dtype=interp) in a python script but I get this error message: Traceback (innermost last): File "<CL script CL1...
Pyraf rspectext RuntimeError: dictionary keys changed during iteration
I have to convert a classic ascii file with two columns (wavelength and flux) into a fits file and I used rspectext from pyraf (with dtype=interp) in a python script but I get this error message: Traceback (innermost last): File "<CL script CL1>", line 1, in <module> File "<CL script onedspec.rspectext>", line 54, in r...
[ "That is actually a bug in PyRAF 2.2.0, which is fixed in 2.2.1. See iraf-community/pyraf#146 for details. So the way to fix this is to upgrade to 2.2.1.\n" ]
[ 1 ]
[]
[]
[ "bash", "iraf", "python" ]
stackoverflow_0074066408_bash_iraf_python.txt
Q: How can I know where the request.user from in Django View? How can I know where the request.user from ? I have a TestRequestUserAPIView: class TestRequestUserAPIView(View): def dispatch(self, request, *args, **kwargs): result = super(TestRequestUserAPIView, self).dispatch(request, *args, **kwargs) ...
How can I know where the request.user from in Django View?
How can I know where the request.user from ? I have a TestRequestUserAPIView: class TestRequestUserAPIView(View): def dispatch(self, request, *args, **kwargs): result = super(TestRequestUserAPIView, self).dispatch(request, *args, **kwargs) return result def get(self, request): user = r...
[ "I'm assuming you're using Django's built-in authentication system - i.e. you have the django.contrib.auth included in your settings installed apps.\nMiddlewares get a chance to intercept the request before any of your views receive it.\nThis request.user attribute is set by Django's auth middleware, here: \nclass...
[ 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0047544617_django_python.txt
Q: Reading csv where one column is a list in python I have the following lines inside a csv file [0 1 2 3 4 5],2145004.491585603,5.784000000019773e-05 [0 1 2 3 4 5],4986045.063898375,1.771400000016854e-05 [0 1 2 3 4 5],2185254.9265346257,1.468399999993153e-05 As you can see, the first entry is a list of integers. Ho...
Reading csv where one column is a list in python
I have the following lines inside a csv file [0 1 2 3 4 5],2145004.491585603,5.784000000019773e-05 [0 1 2 3 4 5],4986045.063898375,1.771400000016854e-05 [0 1 2 3 4 5],2185254.9265346257,1.468399999993153e-05 As you can see, the first entry is a list of integers. How can I read in the data, so that I end up with a list...
[ "I noticed that the list is not an actual list (no commas between items), so this should work\nIn [1]: with open('data.csv') as f:\n ...: reader = csv.reader(f)\n ...: data = []\n ...: for line in reader:\n ...: lst_of_nums = [int(x) for x in line[0][1:-1].split()]\n ...: data....
[ 0, 0, 0 ]
[]
[]
[ "arrays", "csv", "python" ]
stackoverflow_0074191121_arrays_csv_python.txt
Q: Is there any way to get the latest chrome version? I am writing a simple program in python and I need to get the latest release version of Chrome. But I can not find anywhere how to get the latest version of Chrome. Is there a way to get the latest release version of Chrome programmatically? A: The official link...
Is there any way to get the latest chrome version?
I am writing a simple program in python and I need to get the latest release version of Chrome. But I can not find anywhere how to get the latest version of Chrome. Is there a way to get the latest release version of Chrome programmatically?
[ "The official link from Chrome team.\nhttps://chromedriver.storage.googleapis.com/LATEST_RELEASE \nThis gives the latest Chrome release version\nI wrote a simple Python function getting the latest versions from the above source.\nimport requests\n\ndef get_chrome_latest_release():\n url = \"https://chromedriver....
[ 5, 1, 0, 0 ]
[]
[]
[ "google_chrome", "python", "selenium" ]
stackoverflow_0058840609_google_chrome_python_selenium.txt
Q: How to append another column header and values to CSV file using Pandas in Python I'm trying to append an extra column heading to a CSV file, and to also add a column value for each row in the CSV file. I am able to partially get this right, but my code adds an additional header row as well. The TIMESTAMP column d...
How to append another column header and values to CSV file using Pandas in Python
I'm trying to append an extra column heading to a CSV file, and to also add a column value for each row in the CSV file. I am able to partially get this right, but my code adds an additional header row as well. The TIMESTAMP column does not exist in the CSV file - this is the new header and column values I am trying to...
[ "The reason why you're getting this additional header is because you're using names inside your pd.read_csv call. If you want to read only the columns from the fields list, change the parameter names to usecols.\nFor example:\nimport os\nimport pandas as pd\nfrom datetime import datetime\n\n\n# Get the list of all ...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074190422_pandas_python.txt
Q: adding data to dataframe issue I have a code that scrapes a betting site. Here is my code: from os import pardir import time from selenium import webdriver from bs4 import BeautifulSoup from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.by import By from selenium.webdriver.chrome....
adding data to dataframe issue
I have a code that scrapes a betting site. Here is my code: from os import pardir import time from selenium import webdriver from bs4 import BeautifulSoup from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.by import By from selenium.webdriver.chrome.options import Options from urllib.p...
[ "I'll post just the relevant part of the code as the rest is the same as in the original post.\ntry:\n exp_clicks = 0\n for i in expand:\n i.click()\n time.sleep(0.2)\n exp_clicks +=1\n time.sleep(1)\n\n market_data = []\n market_list = driver.find_elements(By.CLASS_NAME,'event-r...
[ 0 ]
[]
[]
[ "python", "selenium", "web_scraping" ]
stackoverflow_0074151572_python_selenium_web_scraping.txt
Q: How to fix seaborn kde error for geographic coordinates I have the following dataframe (2000 rows) Latitude Longitude 31.400091 -109.782830 31.400091 -108.782830 31.410091 -108.782830 31.405091 -109.782830 31.400091 -110.77830 31.460091 -12.782830 ... ... I'm currently trying to represen...
How to fix seaborn kde error for geographic coordinates
I have the following dataframe (2000 rows) Latitude Longitude 31.400091 -109.782830 31.400091 -108.782830 31.410091 -108.782830 31.405091 -109.782830 31.400091 -110.77830 31.460091 -12.782830 ... ... I'm currently trying to represent it the point mass concentration with kde from seaborn packa...
[ "Try this:\nsns.kdeplot(x=x, y=y, zorder=0, n_levels=6, shade=True, \n cbar=True, shade_lowest=False, cmap='viridis')\n\n" ]
[ 2 ]
[]
[]
[ "kdeplot", "python", "seaborn" ]
stackoverflow_0074191301_kdeplot_python_seaborn.txt
Q: Python - how to resize an array and duplicate the elements I've got an array with data like this a = [[1,2,3],[4,5,6],[7,8,9]] and I want to change it to b = [[1,1,2,2,3,3],[1,1,2,2,3,3],[4,4,5,5,6,6],[4,4,5,5,6,6],[7,7,8,8,9,9],[7,7,8,8,9,9]] I've tried to use numpy.resize() function but after resizing, it give...
Python - how to resize an array and duplicate the elements
I've got an array with data like this a = [[1,2,3],[4,5,6],[7,8,9]] and I want to change it to b = [[1,1,2,2,3,3],[1,1,2,2,3,3],[4,4,5,5,6,6],[4,4,5,5,6,6],[7,7,8,8,9,9],[7,7,8,8,9,9]] I've tried to use numpy.resize() function but after resizing, it gives [[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]. I can use a for loo...
[ "My initial though was that np.tile would work but in fact what you are looking for is np.repeat twice on two different axes.\nTry this runnable example!\n\n\n#!/usr/bin/env python\n\nimport numpy as np\na = [[1,2,3],[4,5,6],[7,8,9]]\nb = np.repeat(np.repeat(a, 2, axis=1), 2, axis=0)\nb\n<script src=\"https://modul...
[ 4, 1 ]
[]
[]
[ "multidimensional_array", "numpy", "python" ]
stackoverflow_0074188468_multidimensional_array_numpy_python.txt
Q: How to find the desired values between two dataframes in python I have two dataframes. One is music. name Date Edition Song_ID Singer_ID LA 01.05.2009 1 1 1 Second 13.07.2009 1 2 2 Mexico 13.07.2009 1 3 1 Let's go 13.09.2009 1 4 3 Hello 18.09.2009 1 5 (4,5) Don't give up 12.02.2010 2 6 (5,6) ZIC ZAC 18.03....
How to find the desired values between two dataframes in python
I have two dataframes. One is music. name Date Edition Song_ID Singer_ID LA 01.05.2009 1 1 1 Second 13.07.2009 1 2 2 Mexico 13.07.2009 1 3 1 Let's go 13.09.2009 1 4 3 Hello 18.09.2009 1 5 (4,5) Don't give up 12.02.2010 2 6 (5,6) ZIC ZAC 18.03.2010 2 7 7 Blablabla 14.04.2010 2 8 2 Oh la la 14.05....
[ "You need to merge the two dataframes on the key shared\nhttps://pandas.pydata.org/docs/reference/api/pandas.merge.html\nmerged = singer.merge(music,on=\"Singer_ID\")\nmerged['nationality'].value_counts()['USA']\n\n\n\neditions = merged.groupby(\"Edition\")\n# or print(merged.groupby([\"Edition\", \"nationality\"])...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074191288_python.txt
Q: Plotly python : how to make a dropdown menu with several lines? I would like to make a dropdown menu in a plotly line graph such as the one in this post but with several lines. Let's take a sample dataframe : import pandas as pd df = pd.DataFrame({"Date": ["2022-10-01","2022-10-02","2022-10-03","2022-10-01","2022-...
Plotly python : how to make a dropdown menu with several lines?
I would like to make a dropdown menu in a plotly line graph such as the one in this post but with several lines. Let's take a sample dataframe : import pandas as pd df = pd.DataFrame({"Date": ["2022-10-01","2022-10-02","2022-10-03","2022-10-01","2022-10-02","2022-10-03","2022-10-01","2022-10-02","2022-10-03","2022-10-0...
[ "I think there's a few issues here. The first problem is that when you plot the data filtered by \"Category\" (such as \"Big\" or \"Small\"), you'll be plotting data that repeats dates and this is what causes the lines to go backwards in time which makes the plot hard to interpret.\nYou can instead add traces by pe...
[ 2, 0 ]
[]
[]
[ "drop_down_menu", "linegraph", "plotly", "plotly_python", "python" ]
stackoverflow_0074137808_drop_down_menu_linegraph_plotly_plotly_python_python.txt
Q: Can't trigger clicks while using Left Button in win32api with pyautogui If you test that code you'll see that you can't click and wait for a press on the same key(it's left mouse button in this case, 0x01 is for left) see : https://learn.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes If you put 0x02 ...
Can't trigger clicks while using Left Button in win32api with pyautogui
If you test that code you'll see that you can't click and wait for a press on the same key(it's left mouse button in this case, 0x01 is for left) see : https://learn.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes If you put 0x02 and pyautogui(button='right') that's the same problem import pyautogui impo...
[]
[]
[ "About GetAsyncKeyState, you also can refer to this thread Detecting Key Presses using win32api in Python.\nIt is recommended that you use pyhook or pynput.\nhm = pyHook.HookManager()\n\nhm.MouseAll = onMouseEvent\n\nhm.HookMouse()\n\npythoncom.PumpMessages()\n\n" ]
[ -1 ]
[ "pyautogui", "python", "winapi" ]
stackoverflow_0074169129_pyautogui_python_winapi.txt
Q: python lib html_requests html.render() don't get all elements import requests_html url = 'https://www.crous-bordeaux.fr/restaurant/resto-u-pierre-bidart/' s = requests_html.HTMLSession() r = s.get(url) r.html.render() print(r) J'aimerais récupérer le menu de mon restaurant universitaire, mais j'arrive pas à r...
python lib html_requests html.render() don't get all elements
import requests_html url = 'https://www.crous-bordeaux.fr/restaurant/resto-u-pierre-bidart/' s = requests_html.HTMLSession() r = s.get(url) r.html.render() print(r) J'aimerais récupérer le menu de mon restaurant universitaire, mais j'arrive pas à récupérer l'éléments content-repas. The page that is retrieved by my...
[ "You can access that menu with Requests. here is an example:\nimport requests\nfrom bs4 import BeautifulSoup as bs\n\nurl = 'https://www.crous-bordeaux.fr/restaurant/resto-u-pierre-bidart/'\nr = requests.get(url)\nsoup = bs(r.text, 'html.parser')\nmenu = soup.select_one('div[id=\"menu-repas\"]').text\nprint(menu)\n...
[ -1 ]
[]
[]
[ "python", "python_3.x", "request", "web_scraping" ]
stackoverflow_0074190876_python_python_3.x_request_web_scraping.txt
Q: How to count the number of rows that have the value 1 for all the columns in a dataframe? The following is an example dataframe for this issue: name gender address phone no. --------------------------------------- 1 1 1 1 1 0 0 0 1 1 1 1...
How to count the number of rows that have the value 1 for all the columns in a dataframe?
The following is an example dataframe for this issue: name gender address phone no. --------------------------------------- 1 1 1 1 1 0 0 0 1 1 1 1 1 1 0 1 The desired output here is 2 because the number of rows contai...
[ "Use eq(1) to identify the values with 1, then aggregate per row with any to have True when all values are True and sum the True taking advantage of the True/1 equivalence:\ndf.eq(1).all(axis=1).sum()\n\noutput: 2\nIntermediates:\ndf.eq(1)\n name gender address phone no.\n0 True True True True\n1...
[ 2, 1, 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074190856_dataframe_pandas_python.txt
Q: Generating unique permutations from a list of big size n, while addressing the memory problem I am trying to find an efficient and quick way to generate an enormous set of possible permutations. Here is an examplary list from which I want to get all unique permutations. [-1,1,-1,1,-1,1,-1,1,-1,1,-1,1,-1,1,-1,1,0,0...
Generating unique permutations from a list of big size n, while addressing the memory problem
I am trying to find an efficient and quick way to generate an enormous set of possible permutations. Here is an examplary list from which I want to get all unique permutations. [-1,1,-1,1,-1,1,-1,1,-1,1,-1,1,-1,1,-1,1,0,0,0,0]. My 12 gb ram gets full before the process gets completed. One idea is to append each generat...
[ "itertools.permutations will yield one permutation at a time, so it solves the memory issue.\nBut in your sample list you only have 3 distinct values. This means that while the permutations of 20 items are around 2.43e+18 the distinct permutations you can obtain from that list are just 6.23e+07 - still a large numb...
[ 0 ]
[]
[]
[ "memory", "permutation", "python" ]
stackoverflow_0074191228_memory_permutation_python.txt
Q: Opencv-python successfully installs but is missing from site-packages Bit of a strange one here - I've installed opencv-python via pip install opencv-python, the installation was successful and can be seen via pip show opencv-python, but when trying to import it into a project the package can't be found. On furthe...
Opencv-python successfully installs but is missing from site-packages
Bit of a strange one here - I've installed opencv-python via pip install opencv-python, the installation was successful and can be seen via pip show opencv-python, but when trying to import it into a project the package can't be found. On further investigation there isn't actually an opencv (cv2?) folder in my site-pac...
[ "I had the same problem. So it's NOT Python's fault.\nIn my case i was working on VDI (some kind of virtual machine)\nand when i installed a library in venv, situated in \"C:/Users/Anton/Projects/My_Project/venv\"\nit happened to be created in some strange folder like \"\\some_symbols--08.bla.bla.bla\\data...\\anto...
[ 0 ]
[]
[]
[ "opencv_python", "pip", "python" ]
stackoverflow_0056994072_opencv_python_pip_python.txt
Q: Best way to compare elements pairwise in a Pandas DataFrame (generating a "cross product" matrix) Good morning all, I have a dataframe in which one of the columns is made by lists: import pandas as pd df = pd.DataFrame({'Ind':['A','B','C','D'],'lists':[['dog','cat','horse','squirrel','bird'], ...
Best way to compare elements pairwise in a Pandas DataFrame (generating a "cross product" matrix)
Good morning all, I have a dataframe in which one of the columns is made by lists: import pandas as pd df = pd.DataFrame({'Ind':['A','B','C','D'],'lists':[['dog','cat','horse','squirrel','bird'], ['dog','horse','fish','whale'], ['moose','cat','squirrel','ant','chicken'], ...
[ "You can use itertools.combinations with a custom function to compute the similarity (here using 1 - jaccard similarity, you can use any function that takes 2 lists as input and returns a float), then a bit of numpy magic:\nimport numpy as np\nfrom itertools import combinations\n\ndef similarity(l1, l2):\n s1 = ...
[ 1 ]
[]
[]
[ "dataframe", "optimization", "pandas", "python" ]
stackoverflow_0074191276_dataframe_optimization_pandas_python.txt
Q: How do I bypass the "harmful file" download warning on chrome with selenium? I am using python/selenium to download multiple config files from a few hundred IP devices. How can I bypass this warning and download these files automatically? "This type of file may be harmful to your computer" Keep/Discard" A: You c...
How do I bypass the "harmful file" download warning on chrome with selenium?
I am using python/selenium to download multiple config files from a few hundred IP devices. How can I bypass this warning and download these files automatically? "This type of file may be harmful to your computer" Keep/Discard"
[ "You can use chrome_options to change the default download settings for Chrome:\nfrom selenium import webdriver\n\nchrome_options = webdriver.ChromeOptions()\nprefs = {}\nprefs[\"download.prompt_for_download\"] = False\nprefs[\"download.directory_upgrade\"] = True\nprefs[\"default_content_setting_values.notificatio...
[ 0, 0 ]
[]
[]
[ "google_chrome", "python", "selenium", "selenium_chromedriver", "selenium_webdriver" ]
stackoverflow_0073900684_google_chrome_python_selenium_selenium_chromedriver_selenium_webdriver.txt
Q: Python - Class object as function argument: Object only - Class not in argument I am trying to write a function taking a string as an argument and using this argument as a class object. Note that my explanantion might be strangely formulated sice I could not find an answer online. The MWE below should clarify what...
Python - Class object as function argument: Object only - Class not in argument
I am trying to write a function taking a string as an argument and using this argument as a class object. Note that my explanantion might be strangely formulated sice I could not find an answer online. The MWE below should clarify what I mean, the problematic line is indicated. Edit: in the MWE, "print" is an example. ...
[ "Looks like you need the built-in function called getattr\nmy_object = myClass()\n\ndef my_function(parameter):\n print(getattr(my_object, parameter, None))\n\nalso this is not the best practice to call objects from outer scope like that. i'd suggest to use dict magic methods:\nclass MyClass:\n def __init__(s...
[ 2, 0 ]
[]
[]
[ "class", "python" ]
stackoverflow_0074191423_class_python.txt
Q: What is the python equivalent of g_log_set_handler when using GLib from python I want to set the log level in my python glib project. Therefore I am looking for the g_log_set_handler() equivalent when using GLib from python via gi.repository. But the expected GLib.log_set_handler function seems to be missing. Here...
What is the python equivalent of g_log_set_handler when using GLib from python
I want to set the log level in my python glib project. Therefore I am looking for the g_log_set_handler() equivalent when using GLib from python via gi.repository. But the expected GLib.log_set_handler function seems to be missing. Here is a sample output of my python shell: ~$ python Python 2.7.3 (default, Apr 10 2013...
[ "I found out this is currently not possible and a known bug within either gobject-introspection or glib, since g_log_set_handler is not bindable.\nSee:\nhttps://bugzilla.gnome.org/show_bug.cgi?id=670507\n", "Recently I got into this problem, and solved using ctypes, like the following example.\nfrom ctypes import...
[ 3, 0 ]
[]
[]
[ "glib", "gobject", "gobject_introspection", "pygobject", "python" ]
stackoverflow_0018918443_glib_gobject_gobject_introspection_pygobject_python.txt
Q: Groupby dataframe by column value and calculate new column I have a dataframe that looks like that (Date is the index): Date Value Sensor 19/08/2021 8787 A 20/08/2021 7360 A 23/08/2021 17570 A 24/08/2021 18993 A 25/08/2021 17947 A 26/08/2021 18317 A 27/08/2021 16940 A 30/08/2021 23837 ...
Groupby dataframe by column value and calculate new column
I have a dataframe that looks like that (Date is the index): Date Value Sensor 19/08/2021 8787 A 20/08/2021 7360 A 23/08/2021 17570 A 24/08/2021 18993 A 25/08/2021 17947 A 26/08/2021 18317 A 27/08/2021 16940 A 30/08/2021 23837 A 31/08/2021 18353 A 19/08/2021 15010 B 20/08/2021 1087...
[ "You can use DataFrameGroupBy.shift, for avoid repeating is assign groupby object to variable g, but first add missing datetimes per groups:\ndf['Date'] = pd.to_datetime(df['Date'], dayfirst=True)\ndf = df.set_index('Date').groupby('Sensor')['Value'].resample('D').first().reset_index()\nprint (df)\n Sensor ...
[ 0, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074191585_dataframe_pandas_python.txt
Q: Check if all substrings of list are in a string Assuming I have a list of strings: Dates_list = [DD_MM_YYYY, DD_MM_YYYY, DD_MM_YYYY, ...] Where DD is a day, MM is a month and YYYY is a year. I want a pythonic way to generate a new list extracting all elements of Dates_list where DD = 01 and MM = 06 and YYYY=1950....
Check if all substrings of list are in a string
Assuming I have a list of strings: Dates_list = [DD_MM_YYYY, DD_MM_YYYY, DD_MM_YYYY, ...] Where DD is a day, MM is a month and YYYY is a year. I want a pythonic way to generate a new list extracting all elements of Dates_list where DD = 01 and MM = 06 and YYYY=1950. The following command new_list= [f for f in Dates_li...
[ "Dates_list = [\"01_06_1950\", \"DD_MM_YYYY\", \"DD_MM_YYYY\"]\nprint(list(filter(lambda x: x.split(\"_\")[0] == \"01\" or x.split(\"_\")[1] == \"06\" or x.split(\"_\")[2] == \"1950\",Dates_list)))\n\nyou can get the expected result using above code. filter use to filter the dates only match given conditions. In th...
[ 1 ]
[]
[]
[ "if_statement", "python", "string", "substring" ]
stackoverflow_0074191479_if_statement_python_string_substring.txt
Q: How do I write multiple dataframes to excel using python and download the results using streamlit? I have a Python script using streamlit, that allows the user to upload certain excel files, then it automatically runs my anslysis on it, and then I want them to download the results in xlsx format using the streamli...
How do I write multiple dataframes to excel using python and download the results using streamlit?
I have a Python script using streamlit, that allows the user to upload certain excel files, then it automatically runs my anslysis on it, and then I want them to download the results in xlsx format using the streamlit download button. However, I know how to make them download one dataframe to a csv, but not an xlsx fil...
[ "The Pluviophile's answer is correct, but you should use output in pd.ExcelWriter instead of file_name:\ndef dfs_tabs(df_list, sheet_list, file_name):\n\n output = BytesIO()\n\n writer = pd.ExcelWriter(output, engine='xlsxwriter') \n for dataframe, sheet in zip(df_list, sheet_list):\n dataframe.to...
[ 2, 1 ]
[]
[]
[ "excel", "python", "streamlit" ]
stackoverflow_0070637535_excel_python_streamlit.txt
Q: Unable to scrape and make a dictionary from a news website I want to scrape the news articles from a number of pages on the site: https://koreajoongangdaily.joins.com/section/business At the end, I want to create a dictionary out of the scraped data which should have the date, UTC_date, title, authors_name, news_c...
Unable to scrape and make a dictionary from a news website
I want to scrape the news articles from a number of pages on the site: https://koreajoongangdaily.joins.com/section/business At the end, I want to create a dictionary out of the scraped data which should have the date, UTC_date, title, authors_name, news_content, url. Here is my code, which I tried but couldn't make th...
[ "There's an API endpoint that holds (almost) all data you need and each item is a dictionary, so you can construct your own data structure out of the API response.\nNOTE There's no author key in the response, so if you really need this, you'll have to visit each article URL.\nHere's how to get the first 10 items:\n...
[ 1 ]
[]
[]
[ "beautifulsoup", "python", "selenium", "selenium_webdriver", "web_scraping" ]
stackoverflow_0074191495_beautifulsoup_python_selenium_selenium_webdriver_web_scraping.txt
Q: How to get choices field from django models in a list? I have a model having choices field. I want to fetch the choices options in a list. How can I achieve that? OPTIONS = ( ('COOL', 'COOL'), ('WARM', 'WARM'), ) class My_Model(models.Model): options = models.CharField(max_length=20, choices=OPTIONS, ...
How to get choices field from django models in a list?
I have a model having choices field. I want to fetch the choices options in a list. How can I achieve that? OPTIONS = ( ('COOL', 'COOL'), ('WARM', 'WARM'), ) class My_Model(models.Model): options = models.CharField(max_length=20, choices=OPTIONS, default=None,blank=True, null=True) I want options values i...
[ "You can obtain the data with:\n>>> My_Model.options.field.choices\n(('COOL', 'COOL'), ('WARM', 'WARM'))\n\nyou thus can get a list of keys with:\n>>> [c[0] for c in My_Model.options.field.choices]\n['COOL', 'WARM']\n\nand use c[1] if you want the value (the part that is rendered for that choice).\n", "I checked...
[ 8, 1, 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0068301644_django_django_models_python.txt
Q: how to convert json text to png in python I have files uploaded to a server via ajax calls. The files contain images. I need to read the uploaded files and convert them to .png in python. How can I achieve that? The images, stored as .txt files, look like this: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAm4 .....
how to convert json text to png in python
I have files uploaded to a server via ajax calls. The files contain images. I need to read the uploaded files and convert them to .png in python. How can I achieve that? The images, stored as .txt files, look like this: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAm4 ... RK5CYII=" Thanks! FP
[ "The string starting from iV... is your actual bytes data of png converted in base 64. decode the string and with as binary to file, you will get your image\nimport base64\npng_str = \"iVBORw0 ... NS==\"\npng_bytes = base64.b64decode(png_str) # get your raw bytes\n\nwith open('test.png', 'bw') as fid: # write as bi...
[ 2 ]
[]
[]
[ "json", "python", "python_imaging_library" ]
stackoverflow_0074191606_json_python_python_imaging_library.txt
Q: Iterating through a date range in python that generates a start_date and end_date n days apart from each other Let's say I have an url that looks like this and yields data in json format by specifying a start and end date in the following format: "YYYY-MM-DD". url = "https://thisisaurl.com/data/asd007?start=2021-1...
Iterating through a date range in python that generates a start_date and end_date n days apart from each other
Let's say I have an url that looks like this and yields data in json format by specifying a start and end date in the following format: "YYYY-MM-DD". url = "https://thisisaurl.com/data/asd007?start=2021-10-01&end=2021-10-28" The maximum number of days for which data can be retrieved via this url is 28. In order to ret...
[ "I'm not sure I understood the question, but does this answer it?\nfrom datetime import date, timedelta\n\nstart_date = date(2021, 5, 1)\nend_date = date(2021, 10, 24)\ndelta = timedelta(days=28)\nwhile start_date < end_date:\n end_period = start_date + delta\n if end_period > end_date:\n end_period = ...
[ 1, 1 ]
[]
[]
[ "json", "loops", "pandas", "python", "web_scraping" ]
stackoverflow_0074191586_json_loops_pandas_python_web_scraping.txt
Q: Plots not showing in Jupyter notebook I am trying to create a 2x2 plots for Anscombe data-set Loading Data-set and separating each class in data-set import seaborn as sns import matplotlib.pyplot as plt anscombe = sns.load_dataset('anscombe') dataset_1 = anscombe[anscombe['dataset'] == 'I'] dataset_2 = anscombe[...
Plots not showing in Jupyter notebook
I am trying to create a 2x2 plots for Anscombe data-set Loading Data-set and separating each class in data-set import seaborn as sns import matplotlib.pyplot as plt anscombe = sns.load_dataset('anscombe') dataset_1 = anscombe[anscombe['dataset'] == 'I'] dataset_2 = anscombe[anscombe['dataset'] == 'II'] dataset_3 = an...
[ "If you are working with a Jupyter Notebook then you can add the following line to the top cell where you call all your imports. The following command will render your graph\n%matplotlib inline\n\n\n", "I've tried all of the above, eventually I've found out there is a conflict between matplotlib and a library cal...
[ 16, 1, 0, 0 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0061128143_matplotlib_python.txt
Q: hugging face, Numpy is not available CODE I AM RUNNING: from transformers import pipeline classifier = pipeline('sentiment-analysis') res = classifier("I Love Python.'") print(res) ERROR I AM GETTING: No model was supplied, defaulted to distilbert-base-uncased-finetuned-sst-2-english and revision af0f99b (http...
hugging face, Numpy is not available
CODE I AM RUNNING: from transformers import pipeline classifier = pipeline('sentiment-analysis') res = classifier("I Love Python.'") print(res) ERROR I AM GETTING: No model was supplied, defaulted to distilbert-base-uncased-finetuned-sst-2-english and revision af0f99b (https://huggingface.co/distilbert-base-uncased...
[ "The immediate fix for you is probably\npip install --upgrade numpy\n\nWhich should get you numpy==1.23.1 at the time of this answer.\nI didn't take too much of a look at the host of other requirements you have, but if you had other things that required older versions of numpy, you should really look into running v...
[ 2, 0 ]
[]
[]
[ "huggingface_transformers", "nlp", "numpy", "python" ]
stackoverflow_0073346095_huggingface_transformers_nlp_numpy_python.txt
Q: Different features give the same Accuracy in SVM For a classification task I try to compare two models (with SVM) where the difference between the models is just one feature (namely, cult_distance & inst_dist). Even after HP-tuning (using GridSearchCV) both models show the exact same accuracy. When I try a third ...
Different features give the same Accuracy in SVM
For a classification task I try to compare two models (with SVM) where the difference between the models is just one feature (namely, cult_distance & inst_dist). Even after HP-tuning (using GridSearchCV) both models show the exact same accuracy. When I try a third model with both cult_distance & inst_dist in the model...
[ "The problem seems to be connected with unbalanced dataset. One class present much more in your dataset, so model learns to predict only that class. There are numerous ways to combat that, the simplest one is to adjust class_weight parameter in your model. In your situation it should be around class_weight = {0 : 3...
[ 1 ]
[]
[]
[ "classification", "hyperparameters", "machine_learning", "python", "svm" ]
stackoverflow_0074191577_classification_hyperparameters_machine_learning_python_svm.txt
Q: Combinations with restrictions in Python I have a list S = ["A", "B", "C", "D", "E", "F"] and I want all combinations 3-by-3 without repetition but with restrictions: some elements cannot be in the same combination. Say, for example, that A, B, and C cannot be taken together: if there's A then B or C cannot belon...
Combinations with restrictions in Python
I have a list S = ["A", "B", "C", "D", "E", "F"] and I want all combinations 3-by-3 without repetition but with restrictions: some elements cannot be in the same combination. Say, for example, that A, B, and C cannot be taken together: if there's A then B or C cannot belong to the combination, so in this case [A, B, D...
[ "If all you want is a shorter/nicer code then you can use this list comprehension:\ncombs = [\n comb for comb in combinations(S, 3)\n if all(len(set(comb).intersection(r)) < 2 for r in restricts)\n]\n\nYou could also represent restrictions in a different way:\nfrom collections import defaultdict\n\nnew_restri...
[ 2, 0 ]
[]
[]
[ "combinations", "python", "restriction" ]
stackoverflow_0074191528_combinations_python_restriction.txt
Q: Adding items to nested lists I am new to python and struggling with adding values to nested lists. I have a list that contains 6 values. My lists of lists contains 3 lists and I would like to add the values the 6 values in such a way that the 1 value goes to the 1 list, 2 value to 2nd list, 3rd value to 3 list. Th...
Adding items to nested lists
I am new to python and struggling with adding values to nested lists. I have a list that contains 6 values. My lists of lists contains 3 lists and I would like to add the values the 6 values in such a way that the 1 value goes to the 1 list, 2 value to 2nd list, 3rd value to 3 list. Then I would like to continue loopin...
[ "You can use the position of the item in the list of values (modulo the total number of target lists) to get the right list to append to.\nlists = [[], [], []] \nvalues = [1, 2, 3, 4, 5, 6] \nfor i, x in enumerate(values)...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074191499_python.txt
Q: How I create a smart splitting regex on special characters? I am struggling to create a special regex, that tokenize in smartly the text. Some of the rules are: Don't split on "," or "." if they appear between two digits. ex: "12,3" or "12.3" Split for all other special characters besides " ' " Here is a an exam...
How I create a smart splitting regex on special characters?
I am struggling to create a special regex, that tokenize in smartly the text. Some of the rules are: Don't split on "," or "." if they appear between two digits. ex: "12,3" or "12.3" Split for all other special characters besides " ' " Here is a an example of an input and what I am looking for: Input: "J'aime coder a...
[ "Try (regex101):\nimport re\n\ns = \"\"\"\\\nJ'aime coder avec python 3.7, et 3,8. c'est dûr de coder avec 3.9!\nThis is other phrase.And this is another.\"\"\"\n\npat = re.compile(\n r\"(?:(.*?)\\s*([.,!?])\\s*(?=\\D|\\Z))|(?:(.*?\\D)\\s*([.,!?])\\s*(?=\\d|\\Z))\"\n)\n\nout = [v for v in pat.split(s) if v]\npri...
[ 1 ]
[]
[]
[ "python", "regex", "regex_greedy" ]
stackoverflow_0074191724_python_regex_regex_greedy.txt
Q: How to convert audio bytes generated by mediaRecorder and transfered using websocket to python to numpy array I have a simple WebSocket project created by FastAPI like the following code: import uvicorn from fastapi import FastAPI, WebSocket from fastapi.responses import HTMLResponse import numpy as np import soun...
How to convert audio bytes generated by mediaRecorder and transfered using websocket to python to numpy array
I have a simple WebSocket project created by FastAPI like the following code: import uvicorn from fastapi import FastAPI, WebSocket from fastapi.responses import HTMLResponse import numpy as np import soundfile as sf app = FastAPI() html = """ <!DOCTYPE html> <html> <body> <h1>Transcribe Audio With FastA...
[ "Finally, by creating a bit similar issue on pytorch/audio github repository. I got the answer from moto in this comment. The final solution is as follows:\n@app.websocket(\"/listen\")\nasync def websocket_endpoint(websocket: WebSocket):\n await websocket.accept()\n try:\n chunk_size = 1000\n wh...
[ 0 ]
[]
[]
[ "javascript", "numpy", "python", "websocket" ]
stackoverflow_0074176807_javascript_numpy_python_websocket.txt
Q: 'charmap' codec can't decode byte 0x9d in position 2273: character maps to I am trying to perform Sentiment analysis and am getting stuck adding a library of words for embedding vectors to help my model convert words into numbers. I am receiving an error and cannot get past. Can you please take a look and offer...
'charmap' codec can't decode byte 0x9d in position 2273: character maps to
I am trying to perform Sentiment analysis and am getting stuck adding a library of words for embedding vectors to help my model convert words into numbers. I am receiving an error and cannot get past. Can you please take a look and offer a suggestion to move forward? import pandas as pd d213_data = pd.read_csv('D21...
[ "Consider opening or reading your file this way:\nwith open('filename.extension', \"r+\", encoding=\"utf-8\") as json_data:\n #file.read()\n #file.load()\n\n" ]
[ 0 ]
[]
[]
[ "lstm", "python", "sentiment_analysis", "stanford_nlp", "word_embedding" ]
stackoverflow_0072114395_lstm_python_sentiment_analysis_stanford_nlp_word_embedding.txt