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: value counts not working with a column filter in Pandas everyone I was trying to count the number of Yes answered in a column depending on the answer from another previous column to generate pie charts so I'm having problems with this because is giving me counts in boolean like in image below, (This is my codeline...
value counts not working with a column filter in Pandas
everyone I was trying to count the number of Yes answered in a column depending on the answer from another previous column to generate pie charts so I'm having problems with this because is giving me counts in boolean like in image below, (This is my codeline): answers = ['Yes'] hello = (df['Are you okay?']== 'No') &(d...
[ "hello in this case, is an array of boolean. Apply the array to original dataframe.\nanswers = ['Yes']\nhello = df[(df['Are you okay?']== 'No') &(df['Are yu sad?'].isin(answers))]\n\nthen apply hello.value_counts()\n", "If need count values of boolean mask use sum for processing Trues:\nanswers = ['Yes']\nhello =...
[ 1, 1 ]
[]
[]
[ "count", "dataframe", "multiple_columns", "pandas", "python" ]
stackoverflow_0074247639_count_dataframe_multiple_columns_pandas_python.txt
Q: Return to first step in program after the user enters the wrong data, I would like enter the data again again. a=int(input("enter the value: ")) b=int(input("enter the value: ")) def d(a,b): if(b == 0): return "back to menu" else: return a / b print(d(a,b)) A: you would have to use a whi...
Return to first step in program
after the user enters the wrong data, I would like enter the data again again. a=int(input("enter the value: ")) b=int(input("enter the value: ")) def d(a,b): if(b == 0): return "back to menu" else: return a / b print(d(a,b))
[ "you would have to use a while loop, such as:\nb = 1\nwhile b != 0:\n a=int(input(\"enter the value: \"))\n b=int(input(\"enter the value: \"))\nprint(a,b)\n\nyou will probably have to change b != 0 to a more suitable conditiuon for your code, but this should work!\n", "a=0\nb=0\nwhile(a!=\"what you want\"...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074247685_python.txt
Q: combining rss feeds in python How can I combine multiple rss feeds in python to convert them to a single JSON file? import urllib.request import xmltodict import json url = "https://www.feedforall.com/sample.xml" with urllib.request.urlopen(url) as response: data_dict = xmltodict.parse(response.read()) j...
combining rss feeds in python
How can I combine multiple rss feeds in python to convert them to a single JSON file? import urllib.request import xmltodict import json url = "https://www.feedforall.com/sample.xml" with urllib.request.urlopen(url) as response: data_dict = xmltodict.parse(response.read()) json_data = json.dumps(data_dict) ...
[ "You can use the url as an array and use for loop to use multiple urls\nurls = [\"link1\",\"link2\"]\nfor url in urls:\n /*rest of your code */\n\nand then append all data to a new array and you can have a combined array\n" ]
[ 1 ]
[]
[]
[ "json", "python", "rss" ]
stackoverflow_0066870793_json_python_rss.txt
Q: Random-generated boolean values in pygame - understanding my code I had some help making this star generator code that creates random x,y variables and appends the data to a list, then blits each star to the screen. Occasionally each star blinks, based on randomly generated boolean values. Though the code works pe...
Random-generated boolean values in pygame - understanding my code
I had some help making this star generator code that creates random x,y variables and appends the data to a list, then blits each star to the screen. Occasionally each star blinks, based on randomly generated boolean values. Though the code works perfectly, I'm just not understanding how the if not-statements that deci...
[ "The information that you're missing (and it is admittedly pretty unintuitive) is that integers can be used as boolean values, and all numbers are considered the same as True except for 0, which is considered the same as False. Therefore, not randint(0, 600) can only return True if the random number was 0 - in othe...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074247607_python.txt
Q: pydiffmap: How to reverse Diffusion Map Embedding and reconstruct original variables from several principal components? using pydiffmap, I could find a nice low dimension Manifold in my data, and extract what seems to be meaningful low dimension components. I would like now to reverse the operator, and project my ...
pydiffmap: How to reverse Diffusion Map Embedding and reconstruct original variables from several principal components?
using pydiffmap, I could find a nice low dimension Manifold in my data, and extract what seems to be meaningful low dimension components. I would like now to reverse the operator, and project my data back to my original high dimensional space keeping only these few important dimensions I could identify. First, is this ...
[ "I just went into the Diffusion algorithm behind the package, and realized that there is no guarantee that you can go from a vector in the diffusion space back into the data space.\nThis is because the diffusion space represent the distances to the original data points. So if at least two points are different, the ...
[ 0, 0 ]
[]
[]
[ "dimensionality_reduction", "python", "reverse" ]
stackoverflow_0073025089_dimensionality_reduction_python_reverse.txt
Q: How solving Problem installing the noise package I tried to install noise Python package, but I encountered this error ` PS C:\Users\MacBook\Desktop\python-superhi> python -m pip install noise Collecting noise Using cached noise-1.2.2.zip (132 kB) Preparing metadata (setup.py) ... done Building wheels for collecte...
How solving Problem installing the noise package
I tried to install noise Python package, but I encountered this error ` PS C:\Users\MacBook\Desktop\python-superhi> python -m pip install noise Collecting noise Using cached noise-1.2.2.zip (132 kB) Preparing metadata (setup.py) ... done Building wheels for collected packages: noise Building wheel for noise (setup.py) ...
[]
[]
[ "It is always better to use PyCharm IDE for python projects because it is easy to download modules and to setup environment.\nyou can download this IDE here: download\n" ]
[ -2 ]
[ "noise", "perlin_noise", "pip", "python", "python_packaging" ]
stackoverflow_0074247726_noise_perlin_noise_pip_python_python_packaging.txt
Q: Beginner question, how to combine x and y ticks from 2 plots on a shared x and y axis I try to get x and y ticks from 2 plots and share it on the x and y axis. With one plot it works import matplotlib.pyplot as plt import matplotlib.dates as md from datetime import datetime v1 = datetime.fromisoformat("2022-10-15...
Beginner question, how to combine x and y ticks from 2 plots on a shared x and y axis
I try to get x and y ticks from 2 plots and share it on the x and y axis. With one plot it works import matplotlib.pyplot as plt import matplotlib.dates as md from datetime import datetime v1 = datetime.fromisoformat("2022-10-15T23:45:51.159618277Z") v2 = datetime.fromisoformat("2022-10-16T23:49:51.159618277Z") v3 = d...
[ "Please see how ax.set_xticks and ax.set_yticks work.\nYou are getting the current output because of your code: it is explicitly setting the x-ticks according to datenums2 because how you have asked it to at line number 28: ax.set_xticks(datenums2).\nThis is undoing the expected result from the line written just be...
[ 1 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0074246179_matplotlib_python.txt
Q: Element not Interactable exception when using Python/Selenium I am trying to sign into a website (https://myaccount.play-cricket.com/) using selenium in python. I am struggling to send text (from the password variable in the python code) to the password textbox field on the website. Here is my code: from selenium ...
Element not Interactable exception when using Python/Selenium
I am trying to sign into a website (https://myaccount.play-cricket.com/) using selenium in python. I am struggling to send text (from the password variable in the python code) to the password textbox field on the website. Here is my code: from selenium import webdriver from selenium.webdriver.common.keys import Keys fr...
[ "Try adding a wait for the element to be clickable, as following:\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\n\nwait = WebDriverWait(driver, 20)\nwait.until(EC.element_to_be_clickable((By.NAM...
[ 0, 0, 0 ]
[]
[]
[ "python", "selenium", "selenium_chromedriver", "selenium_webdriver", "web_scraping" ]
stackoverflow_0074246930_python_selenium_selenium_chromedriver_selenium_webdriver_web_scraping.txt
Q: Best way to loop over a python string backwards What is the best way to loop over a python string backwards? The following seems a little awkward for all the need of -1 offset: string = "trick or treat" for i in range(len(string)-1, 0-1, -1): print string[i] The following seems more succinct, but is it actual...
Best way to loop over a python string backwards
What is the best way to loop over a python string backwards? The following seems a little awkward for all the need of -1 offset: string = "trick or treat" for i in range(len(string)-1, 0-1, -1): print string[i] The following seems more succinct, but is it actually generate a reversed string so that there is a mino...
[ "Try the reversed builtin:\nfor c in reversed(string):\n print c\n\nThe reversed() call will make an iterator rather than copying the entire string. \nPEP 322 details the motivation for reversed() and its advantages over other approaches.\n", "EDIT: It has been quite some time since I wrote this answer. It is...
[ 112, 10, 5, 5, 3, 3, 2, 2, 1, 0, 0 ]
[ "string reverse\ndef reverse(a_string):\n rev = ''\n for i in range(len(a_string)-1, -1, -1):\n rev = rev + a_string[i]\n return rev\nprint(reverse(\"This string should be reversed!\"))\n\noutput is:\n!desrever eb dluohs gnirts sihT\n" ]
[ -1 ]
[ "iterator", "optimization", "python", "reverse", "string" ]
stackoverflow_0007961499_iterator_optimization_python_reverse_string.txt
Q: Python - Logging in TWITTER using Selenium I am using Python 3.10 and I am trying to log in on Twitter using Selenium. I am not able to get a hold of the input button to enter my user. Looks like the selenium documentation has changed. I could not find a good example. This is the code I try: from selenium import ...
Python - Logging in TWITTER using Selenium
I am using Python 3.10 and I am trying to log in on Twitter using Selenium. I am not able to get a hold of the input button to enter my user. Looks like the selenium documentation has changed. I could not find a good example. This is the code I try: from selenium import webdriver from selenium.webdriver.common.by im...
[ "There are several problems here:\n\nAs mentioned, executable_path has been deprecated. You should use Service object instead as following.\nVery long absolute XPath locators are very breakable. You have to use relative locators.\nYou also have to use WebDriverWait expected_conditions to wait for elements to become...
[ 0 ]
[]
[]
[ "python", "selenium", "selenium_chromedriver", "selenium_webdriver", "xpath" ]
stackoverflow_0074243348_python_selenium_selenium_chromedriver_selenium_webdriver_xpath.txt
Q: How to make this code more efficient in python and in less time? I have have an homework where I have to decode and codify a string of number using the Romanian alphabet. 1000 500 100 50 10 5 1 In this function I have a string like '10010010010100511' called xkcd and I have to return an int list like [100, 100, 1...
How to make this code more efficient in python and in less time?
I have have an homework where I have to decode and codify a string of number using the Romanian alphabet. 1000 500 100 50 10 5 1 In this function I have a string like '10010010010100511' called xkcd and I have to return an int list like [100, 100, 100, 10, 100, 5, 1, 1,] where I separate the numbers. I would like to k...
[ "The best plan is to notice that zeros are the key. If the character is not a 0, then it starts a new value. If it is a zero, then it tacks on to the previous value. This code looks at each character exactly once:\ndef analyze(xkcd):\n result = []\n for c in xkcd:\n if c == '0':\n result[...
[ 1 ]
[]
[]
[ "cycle", "python" ]
stackoverflow_0074247787_cycle_python.txt
Q: How can I run python in terminal on a mac? I'm extremely new to programming, in fact I'm trying to learn Python now as a first language. I found that Google has a python course and it said to download python 2 from python's website, which I did, and I now realize that python was already installed on my mac by appl...
How can I run python in terminal on a mac?
I'm extremely new to programming, in fact I'm trying to learn Python now as a first language. I found that Google has a python course and it said to download python 2 from python's website, which I did, and I now realize that python was already installed on my mac by apple. Anyways, I also had to download some exercise...
[ "\nFirst, the lesson said to simply type, python, into terminal to start coding in python (I don't know if this is the way to say that, or if that just gives you the ability to run python code?)\n\nWhat happens when you type a program name into terminal is that it basically executes the program, and if it has a GUI...
[ 4, 1, 1 ]
[ "The first thing is that your file can't be named python hellow.py it should be named python_hellow.py.\nAnd to run it:\nOn macOS: type: python python_hellow.py\nOn Windows: type: python3 python_hellow.py\n" ]
[ -2 ]
[ "macos", "python" ]
stackoverflow_0030408127_macos_python.txt
Q: ROS2: Troubleshooting 'colcon build' for python packages? I'm working in a ROS2 workspace 'home_ws' with 5 of my packages: home_core home_devices home_extras home_launch home_ui All packages are python, all built following the same example from the ROS2 doc. After 'colcon_build' I only see 3 of the 5 packages. O...
ROS2: Troubleshooting 'colcon build' for python packages?
I'm working in a ROS2 workspace 'home_ws' with 5 of my packages: home_core home_devices home_extras home_launch home_ui All packages are python, all built following the same example from the ROS2 doc. After 'colcon_build' I only see 3 of the 5 packages. Output of ros2 pkg list: ... geometry geometry_msgs home_core ho...
[ "I found my issue by reviewing the very, very detailed colcon build logs, which I didn't know about.\nmatt@molokai:~/Projects/home_ws$ colcon build --symlink-install\nStarting >>> home_core\nStarting >>> home_devices\nStarting >>> home_extras\nStarting >>> home_ui\nFinished <<< home_devices [2.11s]\nFinished <<< ho...
[ 0 ]
[]
[]
[ "colcon", "package", "python", "ros", "ros2" ]
stackoverflow_0074185026_colcon_package_python_ros_ros2.txt
Q: Can't name a file containing special characters I want to name a file containing special characters, but I get an error when I try to do so with open('My filename: one | two.txt', 'a') as f: f.write('something') and get this error : OSError: [Errno 22] Invalid argument: 'My filename: one | two.txt' How can I...
Can't name a file containing special characters
I want to name a file containing special characters, but I get an error when I try to do so with open('My filename: one | two.txt', 'a') as f: f.write('something') and get this error : OSError: [Errno 22] Invalid argument: 'My filename: one | two.txt' How can I name a file containing special characters?
[ "It depends on the OS, but for Microsoft, these are the specific characters not allowed in filenames and vertical bar (|) is one of them.\nFrom https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file:\n\nUse any character in the current code page for a name, including\nUnicode characters and characters...
[ 2 ]
[]
[]
[ "filenames", "python" ]
stackoverflow_0074247886_filenames_python.txt
Q: context must be a dict rather than module When I am filtering for my search bar I am getting this error. I am not sure what I am doing wrong here Watching this tutorial: https://www.youtube.com/watch?v=llbtoQTt4qw&t=3399s views.py class pplList(LoginRequiredMixin,ListView): model = People context_o...
context must be a dict rather than module
When I am filtering for my search bar I am getting this error. I am not sure what I am doing wrong here Watching this tutorial: https://www.youtube.com/watch?v=llbtoQTt4qw&t=3399s views.py class pplList(LoginRequiredMixin,ListView): model = People context_object_name = 'people' def get_context_d...
[ "There are some minor mistakes such as it should be self.request.GET.get('search-area'), also you haven't called the super() method, so try this view:\nclass pplList(LoginRequiredMixin,ListView):\n model = People\n context_object_name = 'people_list'\n def get_context_data(self, **kwargs):\n context...
[ 2 ]
[]
[]
[ "django", "django_forms", "django_templates", "django_views", "python" ]
stackoverflow_0074247727_django_django_forms_django_templates_django_views_python.txt
Q: How to add up all instances of a class. This total value will be available through the class as well as any of the instances Any instance of the class Square starts as an integer equal to 2. When the square_me method is called on the instance, the instance is multiplied by itself. This can be done any number of ti...
How to add up all instances of a class. This total value will be available through the class as well as any of the instances
Any instance of the class Square starts as an integer equal to 2. When the square_me method is called on the instance, the instance is multiplied by itself. This can be done any number of times (e.g. calling square_me once on an instance results in the value 4, and calling square_me again on the same instance results i...
[ "Square.get_total is a function. You need Square.get_total(). In that case, get_total is not going to get a self argument. Also, you never update total, so it's going to return anything. You would need get_total to do return sum(Square.instances.values()). Also, you'll want to store the instance in the list dur...
[ 2 ]
[]
[]
[ "class", "oop", "python", "python_3.x" ]
stackoverflow_0074247867_class_oop_python_python_3.x.txt
Q: A Python script works fine on Windows but throws an error on Mac I wish to get different product information from this webpage using requests module. I've created a script in Python to get a JSON response by issuing post requests with appropriate parameters. The script works fine on windows but throws this error J...
A Python script works fine on Windows but throws an error on Mac
I wish to get different product information from this webpage using requests module. I've created a script in Python to get a JSON response by issuing post requests with appropriate parameters. The script works fine on windows but throws this error JSONDecodeError: Expecting value: line 1 column 1 (char 0) on mac. Here...
[ "Your request headers include:\n'accept-encoding': 'gzip, deflate, br'\n\nand the post response includes this:\n'Content-Encoding': 'br'\n\nSo the response is compressed using Brotli compression, which is not automatically handled by the requests module.\nHere's how to decode it (note, this is hardcoded to use Brot...
[ 4 ]
[]
[]
[ "python", "python_3.x", "python_requests", "web_scraping" ]
stackoverflow_0074210120_python_python_3.x_python_requests_web_scraping.txt
Q: Swap/order values by row I have (N,2) numpy array : [3,5] [4,2] [1,6] [5,4] ..... I want to swap the values on every row so that the bigger value is FIRST [5,3] [4,2] [6,1] [5,4] ..... A: You could use something like this: array.sort() array = array[:, ::-1] if array is your numpy array A: ori_arr ...
Swap/order values by row
I have (N,2) numpy array : [3,5] [4,2] [1,6] [5,4] ..... I want to swap the values on every row so that the bigger value is FIRST [5,3] [4,2] [6,1] [5,4] .....
[ "You could use something like this:\narray.sort()\narray = array[:, ::-1]\n\nif array is your numpy array\n", "ori_arr = np.array([[3, 5], [4, 2], [1, 6], [5, 4]])\nprint('''{}\nThe original array:\n{}\n'''.format(\"=\"*20, ori_arr))\n# Straight forward way\nfor i in range(len(ori_arr)):\n ori_arr[i] = sorted(...
[ 2, 0, 0 ]
[]
[]
[ "numpy", "python", "row" ]
stackoverflow_0074247647_numpy_python_row.txt
Q: How to call a function when you delete a model object in django admin page? (or override delete action?) I need to call a function whenever I have an object of a model deleted via admin page. How can I do such thing? A: Yes, it's called a post_delete signal. Here is one way of doing it (you can add this to the ...
How to call a function when you delete a model object in django admin page? (or override delete action?)
I need to call a function whenever I have an object of a model deleted via admin page. How can I do such thing?
[ "Yes, it's called a post_delete signal. Here is one way of doing it (you can add this to the bottom of your models.py file, or at least after your model:\nfrom django.db.models.signals import post_delete\nfrom django.dispatch import receiver\n\n@receiver(post_delete, sender=YourModelName)\ndef signal_function_name...
[ 2, 0, 0 ]
[ "def delete(self):\nfiles = WidgetFile.objects.filter(widget=self)\nif files:\n for file in files:\n file.delete()\nsuper(Widget, self).delete()\n\nThis triggered the necessary delete() method on each of the related objects, thus triggering my custom file deleting code. It's more database expensive yes, b...
[ -1 ]
[ "django", "django_models", "python" ]
stackoverflow_0071278989_django_django_models_python.txt
Q: Calling the sklearn2pmml() function in Python 3.8 throws RuntimeError I'am trying to save my scikit learn logistic regression as pmml but get a RuntimeError: My code: from sklearn2pmml import sklearn2pmml from sklearn2pmml.pipeline import PMMLPipeline from sklearn.linear_model import LogisticRegression pipe_pmml ...
Calling the sklearn2pmml() function in Python 3.8 throws RuntimeError
I'am trying to save my scikit learn logistic regression as pmml but get a RuntimeError: My code: from sklearn2pmml import sklearn2pmml from sklearn2pmml.pipeline import PMMLPipeline from sklearn.linear_model import LogisticRegression pipe_pmml = PMMLPipeline(steps=[('mapper', mapper), (...
[ "Solution: Downgrade joblib to 1.1.0\nsee: https://github.com/jpmml/jpmml-python/issues/19\n", "Joblib 1.2.0 generates pickle-like files, which contain extra padding for array memory alignment purposes: joblib/joblib#563\nThis extra padding is what is causing standard pickle data format readers to fail.\nThe SkL...
[ 1, 0 ]
[]
[]
[ "pmml", "python", "python_3.8", "runtime_error", "scikit_learn" ]
stackoverflow_0074071396_pmml_python_python_3.8_runtime_error_scikit_learn.txt
Q: None value in a return function I had to write a function in Python that returns the highest number of three integer numbers (as arguments), it seemed to easy to me, but proving this in Spyder and VSC, the output is None. I don't understand the reason because the input are three integer numbers. def max_tres_num(a...
None value in a return function
I had to write a function in Python that returns the highest number of three integer numbers (as arguments), it seemed to easy to me, but proving this in Spyder and VSC, the output is None. I don't understand the reason because the input are three integer numbers. def max_tres_num(a,b,c): if a>=b and a>=c: ...
[ "You made an error while writing the program where in last condition you put '<' sign rather than '>' sign.\ndef max_tres_num(a,b,c):\n if a>=b and a>=c: \n return a \n if b>=a and b>=c: \n return b \n if c>=a and c>=b: \n return c\n\nprint(max_tres_num(1, 2, 3))\n\nThis should work no...
[ 0 ]
[]
[]
[ "function", "python", "return" ]
stackoverflow_0074247882_function_python_return.txt
Q: Rust and Python subprocess module with stdin.readline Minimal reproducible example I have created a minimal reproducible example that can be cloned and easily ran on Github for testing: https://github.com/VirxEC/python-no-run If you don't want to go to GitHub then the code snippets will be at the bottom of this po...
Rust and Python subprocess module with stdin.readline
Minimal reproducible example I have created a minimal reproducible example that can be cloned and easily ran on Github for testing: https://github.com/VirxEC/python-no-run If you don't want to go to GitHub then the code snippets will be at the bottom of this post. The issue, described as quickly as possible When launch...
[ "subprocess.Popen with default parameters requests a handle to stdout and stdin from the operating system on windows ... which seems to get stuck or fail for some reason.\nanyway passing the parent's stdout or a PIPE seems to fix it on windows, simply replacing\nproc = subprocess.Popen([sys.executable, \"say-hi.py\...
[ 2 ]
[]
[]
[ "python", "rust", "stdin", "subprocess", "windows" ]
stackoverflow_0074246945_python_rust_stdin_subprocess_windows.txt
Q: Sklearn2pmml doesn't seem to support custom feature conversion functions? My pipeline uses a custom conversion function, it cannot be successfully converted using sklearn2pmml. Here is my custom function code def calc_modify_days(X): X['modify_date_new'] = X['modify_date'].apply(lambda x:x[:4]+'-'+x[4:6]+'-'+...
Sklearn2pmml doesn't seem to support custom feature conversion functions?
My pipeline uses a custom conversion function, it cannot be successfully converted using sklearn2pmml. Here is my custom function code def calc_modify_days(X): X['modify_date_new'] = X['modify_date'].apply(lambda x:x[:4]+'-'+x[4:6]+'-'+x[6:8] if x!='' and x<'20221230' else '2022-12-30' ) X['modify_days'] = (pd...
[ "This question has been answered in jpmml/sklearn2pmml#354\nIn short, the inability to pickle FunctionTransformer instances that contain lambda functions (or reference local functions) is a Python limitation. The SkLearn2PMML package is simply complaining about incomplete pipeline object here.\nIn the current case,...
[ 0 ]
[]
[]
[ "pmml", "python", "scikit_learn", "sklearn2pmml" ]
stackoverflow_0074218832_pmml_python_scikit_learn_sklearn2pmml.txt
Q: aws connect search_available_phone_numbers API for python does not work I am trying to use the available phone number API in order to claim and attach a contact flow. I tried following the documentation provided by AWS for python. https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/connect.h...
aws connect search_available_phone_numbers API for python does not work
I am trying to use the available phone number API in order to claim and attach a contact flow. I tried following the documentation provided by AWS for python. https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/connect.html#Connect.Client.search_available_phone_numbers when I try to use it, it gi...
[ "You will need to create a layer for boto3 pointing to the latest version of the package that includes the search_available_phone_numbers API that you are trying to call and add that layer to the lambda.\nThe AWS Lambda service supports up to python 3.9 runtimes currently, and it's associated boto3 package version ...
[ 1, 0 ]
[]
[]
[ "amazon_connect", "amazon_web_services", "aws_lambda", "boto3", "python" ]
stackoverflow_0074152747_amazon_connect_amazon_web_services_aws_lambda_boto3_python.txt
Q: discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions when I try to send message @tasks.loop(seconds=20) async def __random_time_money(): value = random.randint(4, 15) time.sleep(value) for guild in bot.guilds: ch = guild.get_channel(base.execute("""SELECT main_channe...
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions when I try to send message
@tasks.loop(seconds=20) async def __random_time_money(): value = random.randint(4, 15) time.sleep(value) for guild in bot.guilds: ch = guild.get_channel(base.execute("""SELECT main_channel FROM guild_name WHERE guild_id = {}""".format(guild.id)).fetchone()[0]) print(ch) await ch.send...
[ "Your bot can't send messages in the channel you're trying to send it.\nPlease, make sure your bot has correct permissions to send messages in a desired channel (Which ID is in your database)\n" ]
[ 0 ]
[]
[]
[ "discord", "python" ]
stackoverflow_0074248086_discord_python.txt
Q: Python Phone Number Pattern Matching w/ RegEx (findall) I need to match to a NANP standard 10-digit phone number with some using – as a separator (e.g. 123-456-7890) and some will have a dot (.) as a separator (e.g. 123.456.7890). I have tried: numbers = "123-456-7890, 123.456.7890" phones = re.findall("\d{3}*\D*\...
Python Phone Number Pattern Matching w/ RegEx (findall)
I need to match to a NANP standard 10-digit phone number with some using – as a separator (e.g. 123-456-7890) and some will have a dot (.) as a separator (e.g. 123.456.7890). I have tried: numbers = "123-456-7890, 123.456.7890" phones = re.findall("\d{3}*\D*\d{3}*\D*\d{4}", numbers)
[ "Try this:\nimport re\nresult = re.findall('\\d{3}[-.]\\d{3}[-.]\\d{4}', numbers)\nprint(result)\n\nOutput: ['123-456-7890', '123.456.7890']\n\n[-.] : match only - or .\n\\d{3} : three times match any digit (0-9)\n\n" ]
[ 2 ]
[]
[]
[ "python", "python_3.x", "regex" ]
stackoverflow_0074248072_python_python_3.x_regex.txt
Q: SyntaxError: invalid syntax mkdir I'm doing for having mqtt python.. I'm beginer # Create a workspace directory to hold all the SDK files mkdir sdk-workspace File "<ipython-input-12-5c70212e7b48>", line 2 mkdir sdk-workspace ^ SyntaxError: invalid syntax I don't know what is wrong. I want to know...
SyntaxError: invalid syntax mkdir
I'm doing for having mqtt python.. I'm beginer # Create a workspace directory to hold all the SDK files mkdir sdk-workspace File "<ipython-input-12-5c70212e7b48>", line 2 mkdir sdk-workspace ^ SyntaxError: invalid syntax I don't know what is wrong. I want to know what is wrong
[]
[]
[ "The mkdir (make directory) is an operating system command, not a command in Python..\nIf you want use it in python, try in function like this:\nimport os\n\nos.mkdir(path, mode=0o777, *, dir_fd=None)\n\n" ]
[ -1 ]
[ "mkdir", "python" ]
stackoverflow_0074248138_mkdir_python.txt
Q: Kick command won't kick people when used I tried to make a kick command, everything works except when the command is run, the user specified will not be kicked. @bot.tree.command(name='kick', description='Kicks a user from the server [S]') async def embed(interaction : discord.Interaction, user : discord.Member, r...
Kick command won't kick people when used
I tried to make a kick command, everything works except when the command is run, the user specified will not be kicked. @bot.tree.command(name='kick', description='Kicks a user from the server [S]') async def embed(interaction : discord.Interaction, user : discord.Member, reason : str = None): permissions = intera...
[ "I figured out how to fix it. Thanks for helping!\n", "Try using this, and work your way from there:\nThe command should be !kick @user reason for kick\nimport discord\nfrom discord.ext.commands import Bot\nfrom discord.ext import commands\nbot= commands.Bot(command_prefix='!', intents=discord.Intents.all())\n#ad...
[ 1, 0 ]
[]
[]
[ "bots", "command", "discord.py", "python" ]
stackoverflow_0074199615_bots_command_discord.py_python.txt
Q: deleting the common parts of two images Say I have the following two images: before.png: after.png: I'd like to remove all the parts of after.png that are in before.png so that, unto the end, I have this: . My question is... how can I do this? Here's what I've tried so far: import cv2 refFilename = 'before.pn...
deleting the common parts of two images
Say I have the following two images: before.png: after.png: I'd like to remove all the parts of after.png that are in before.png so that, unto the end, I have this: . My question is... how can I do this? Here's what I've tried so far: import cv2 refFilename = 'before.png' newFilename = 'after.png' outFilename = 'o...
[ "Here is one way to do that in Python/OpenCV.\n\nRead the two images as grayscale\nConvert to binary by Otsu thresholding\nInvert the two binary images\nGet the absolute difference\nInvert the difference\nSave results\n\nInput:\n\n\nimport cv2\n\n# read the two images\nimg1 = cv2.imread('circle1.jpg', cv2.IMREAD_GR...
[ 3 ]
[]
[]
[ "opencv", "python" ]
stackoverflow_0074246292_opencv_python.txt
Q: ValueError: Shapes (None, 10) and (None, 32, 32, 10) are incompatible (Keras tuner) I have a CNN based on 32 by 32 images defined as follows: from keras.datasets import cifar10 (x_train, y_train), (x_test, y_test) = cifar10.load_data() img = plt.imshow(x_train[0]) print('The label is:', y_train[0]) img = plt.imsh...
ValueError: Shapes (None, 10) and (None, 32, 32, 10) are incompatible (Keras tuner)
I have a CNN based on 32 by 32 images defined as follows: from keras.datasets import cifar10 (x_train, y_train), (x_test, y_test) = cifar10.load_data() img = plt.imshow(x_train[0]) print('The label is:', y_train[0]) img = plt.imshow(x_train[1]) print('The label is:', y_train[1]) y_train_one_hot = keras.utils.to_categ...
[ "The problem was rooted in the shape of one of the variables not matching the preferred shape as I was trying to use custom data. I just had to re-define the shapes.\n", "Change\nloss='categorical_crossentropy' \n\nto\nloss='sparse_categorical_crossentropy'\n\n" ]
[ 0, 0 ]
[]
[]
[ "keras", "python", "tensorflow" ]
stackoverflow_0062702853_keras_python_tensorflow.txt
Q: Is leiden algorithm is applied on a dataframe which is undirected I constructed a graph and wanted to know how can we apply the Leiden algorithm. I have started using the Louvain algorithm but it's taking a lot of time. I am new to community detection and came to know that Leiden works very fast when compared to L...
Is leiden algorithm is applied on a dataframe which is undirected
I constructed a graph and wanted to know how can we apply the Leiden algorithm. I have started using the Louvain algorithm but it's taking a lot of time. I am new to community detection and came to know that Leiden works very fast when compared to Louvain. Can anyone help me with how can I implement the Leiden algorith...
[ "You have constructed a graph using networkx. The leidenalg package works with igraph, not with networkx. You can easily first convert the graph to an igraph graph using ig.Graph.from_networkx (after installing igraph and doing import igraph as ig).\n" ]
[ 0 ]
[]
[]
[ "cluster_computing", "graph", "networkx", "python" ]
stackoverflow_0072882911_cluster_computing_graph_networkx_python.txt
Q: Partial update overwriting nested fields in MongoDB and FastAPI I have this schema { "_id": "5060ad4b-fb4a-4a34-b44a-32e97626dc0a", "isDeleted": false, "user": { "timestamp": "2022-10-29", "name": "john2", "surname": "doe2", "email": "12345@abcd.edu.tr", "phone": "+012345678912", "age...
Partial update overwriting nested fields in MongoDB and FastAPI
I have this schema { "_id": "5060ad4b-fb4a-4a34-b44a-32e97626dc0a", "isDeleted": false, "user": { "timestamp": "2022-10-29", "name": "john2", "surname": "doe2", "email": "12345@abcd.edu.tr", "phone": "+012345678912", "age": 20, "gender": "male", "nationality": "smth", "universi...
[ "One simple option is to divide it to nested and not nested stages:\ndb.collection.find_one_and_update(\n {_id: id},\n [\n {$set: {\n \"user.preferences\": {$mergeObjects: [\"$user.preferences\", new_user.preferences]}\n }},\n {$set: {\n user: {$mergeObjects: [\"$user\", new_user_first_layer]}\...
[ 1 ]
[]
[]
[ "fastapi", "mongodb", "nosql", "pymongo", "python" ]
stackoverflow_0074247081_fastapi_mongodb_nosql_pymongo_python.txt
Q: How do you set functions for a button, on Tkinter? my function wont carry out for the button assigned. Im using visual studio code. For the def myClick(): myLabel =Label(window, text ..., command... it wont occur. on visual studio code, the 'myLabel' greys out and has the error 'is not accessedPylance' # add respo...
How do you set functions for a button, on Tkinter?
my function wont carry out for the button assigned. Im using visual studio code. For the def myClick(): myLabel =Label(window, text ..., command... it wont occur. on visual studio code, the 'myLabel' greys out and has the error 'is not accessedPylance' # add response to input def myClick(): myLabel = Label(window...
[ "I think its just that you are not calling pack(). When I fix that I see the label appear:\ndef myClick():\n myLabel = Label(window, text=\"Hello\" + e.get() + \"... \")\n myLabel.pack()\n\n", "I think you should pack myLabel inside the function, and add \"()\" at the end:\ndef myClick():\n myLabel ...
[ 1, 0, 0, 0 ]
[]
[]
[ "button", "python", "tkinter" ]
stackoverflow_0074248108_button_python_tkinter.txt
Q: Strip \n \t \r in scrapy I'm trying to strip \r \n \t characters with a scrapy spider, making then a json file. I have a "description" object which is full of new lines, and it doesn't do what I want: matching each description to a title. I tried with map(unicode.strip()) but it doesn't really works. Being new to ...
Strip \n \t \r in scrapy
I'm trying to strip \r \n \t characters with a scrapy spider, making then a json file. I have a "description" object which is full of new lines, and it doesn't do what I want: matching each description to a title. I tried with map(unicode.strip()) but it doesn't really works. Being new to scrapy I don't know if there's...
[ "unicode.strip only deals with whitespace characters at the beginning and end of strings\n\nReturn a copy of the string with the leading and trailing characters removed.\n\nnot with \\n, \\r, or \\t in the middle.\nYou can either use a custom method to remove those characters inside the string (using the regular ex...
[ 23, 7, 3, 1, 0, 0, 0, 0 ]
[]
[]
[ "python", "scrapy", "unicode" ]
stackoverflow_0035288184_python_scrapy_unicode.txt
Q: How can i turn a list into a dict getting something like this? I have a list like this: how to get something like this? A: Start with an empty dict, iterate over the list, and append each value to a list in the dict, creating it if needed. >>> a_list = [['a', 1], ['b', 18], ['a', 3], ['b', 21], ['a', 51], ['b',...
How can i turn a list into a dict getting something like this?
I have a list like this: how to get something like this?
[ "Start with an empty dict, iterate over the list, and append each value to a list in the dict, creating it if needed.\n>>> a_list = [['a', 1], ['b', 18], ['a', 3], ['b', 21], ['a', 51], ['b', 88]]\n>>> a_dict = {}\n>>> for k, v in a_list:\n... a_dict.setdefault(k, []).append(v)\n...\n>>> a_dict\n{'a': [1, 3, 51...
[ 1 ]
[]
[]
[ "dictionary", "list", "python" ]
stackoverflow_0074248216_dictionary_list_python.txt
Q: Python a badly formatted JSON with "extra" double quotes I need some help!! I need to handle in Python a badly formatted JSON with "extra" double quotes. Unfortunately it is not possible to adjust at the origin. Any idea how I can fix this??? Bad JSON json_input='{"value_ok" : "ok", "empth" : """", "value_2" : ""t...
Python a badly formatted JSON with "extra" double quotes
I need some help!! I need to handle in Python a badly formatted JSON with "extra" double quotes. Unfortunately it is not possible to adjust at the origin. Any idea how I can fix this??? Bad JSON json_input='{"value_ok" : "ok", "empth" : """", "value_2" : ""text"", "value_3" : ""2022-01-01""}' Attempt 1 d = json.loads(...
[ "You can try to substitute : \"\" and \"\",, but I would be careful as this could break the document in other places.\nimport re\njson_input = re.sub(r'\"\"([,}])', r'\"\\1', re.sub(r': \"\"', r': \"', json_input))\n\n" ]
[ 0 ]
[]
[]
[ "formatted", "json", "python" ]
stackoverflow_0074248011_formatted_json_python.txt
Q: Tensor repeat for image patches I have a batch of 20 flattened tensors representing 256X256 images. >>> imgs.shape (20, 65536) Each image was split into 32x32 patches (a total of 64 patches per image). I have calculated a score for each patch and got a vector with the shape of (20,64) I would like to multiply eac...
Tensor repeat for image patches
I have a batch of 20 flattened tensors representing 256X256 images. >>> imgs.shape (20, 65536) Each image was split into 32x32 patches (a total of 64 patches per image). I have calculated a score for each patch and got a vector with the shape of (20,64) I would like to multiply each pixel with the corresponding patch ...
[ "I would suggest reshaping your scores array to preserve information about how it relates to the original image, then using repeat_interleave() twice.\nExample:\nimport torch\nimg_size = 4\npatch_size = 2\npatches_per_axis = int(img_size / patch_size)\nnum_images = 2\nimg = torch.rand((2,img_size,img_size)) # (2,4,...
[ 2 ]
[]
[]
[ "python", "pytorch", "tensor" ]
stackoverflow_0074248099_python_pytorch_tensor.txt
Q: Creating a world cup sweetstakes using Python and Tkinter. How to select a player and team from two lists and remove from the next selection I'm creating a World Cup sweepstake using Python and Tkinter and I would like to have two buttons; one that selects a random person from a list of persons, and another button...
Creating a world cup sweetstakes using Python and Tkinter. How to select a player and team from two lists and remove from the next selection
I'm creating a World Cup sweepstake using Python and Tkinter and I would like to have two buttons; one that selects a random person from a list of persons, and another button that selects a random world cup team from a list of teams. Each time one of each is selected it should be removed from the list so it isn't selec...
[ "players and teams list should be defined outside the functions . use code below:\nfrom tkinter import *\nimport random\n\ndef select_player():\n global players,player_label\n select_player_button.config(state=\"disabled\")\n select_team_button.config(state=\"active\")\n \n chosen_player = players.pop(r...
[ 1 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074245978_python_tkinter.txt
Q: FLASK SQLAlchemy query,filter and give multiple returns I am trying to create an API with flask-sqlalchemy that takes employee_id number and returns all info of them. Some employees are in two departments so I want it to return json of all the departments that the employee might belong. The code runs but it gives ...
FLASK SQLAlchemy query,filter and give multiple returns
I am trying to create an API with flask-sqlalchemy that takes employee_id number and returns all info of them. Some employees are in two departments so I want it to return json of all the departments that the employee might belong. The code runs but it gives me an empty list when I enter an employee id. @app.route('/ge...
[ "You give SQLAlchemy a string not the real employee_id.\nTherefore you have to change ratings to this:\nratings = credit_scores.query.filter_by(employee_id=employee_id).all()\n\nThe second problem I see is, that you are referencing a variable, that is not assigned, which is rate. You have to change rate to rating.\...
[ 1 ]
[]
[]
[ "flask", "python", "sqlalchemy" ]
stackoverflow_0074247546_flask_python_sqlalchemy.txt
Q: Check if user exists before inserting into Mysql How do i go about something like this, I want to check if a user exists against a table in python, and if the user exists , it should report that the particular user exists, else if the user does not, it should register (insert the user into the mysql database) So f...
Check if user exists before inserting into Mysql
How do i go about something like this, I want to check if a user exists against a table in python, and if the user exists , it should report that the particular user exists, else if the user does not, it should register (insert the user into the mysql database) So far, this is what my code is looking like @app.route('/...
[ "I did a similar program a few weeks ago which is the same concept but a slightly rudamentary approach, I hope it helps.\nAssuming the SQL connection was properly setup and in my case using the table \"userdata\" and searching the column \"username\"\ndef login(user):\n cursor.execute(\"SELECT * FROM userdata WH...
[ 0, 0 ]
[]
[]
[ "flask", "mysql", "python" ]
stackoverflow_0074247490_flask_mysql_python.txt
Q: How to create a precision-recall curve plot to compare 2 classifiers in Python? My goal is to find the precision-recall curve, comparing with Logistic Regression and Random Forest and plotting them in one graph. I wanted to know if I used the right steps to create a plot to compare both classifiers. I appreciate a...
How to create a precision-recall curve plot to compare 2 classifiers in Python?
My goal is to find the precision-recall curve, comparing with Logistic Regression and Random Forest and plotting them in one graph. I wanted to know if I used the right steps to create a plot to compare both classifiers. I appreciate all the help! Code: from sklearn.preprocessing import MultiLabelBinarizer as mlb impor...
[ "This is my attempt to plot it.\nimport pathlib\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import (MultipleLocator, AutoMinorLocator)\nfrom sklearn.metrics import PrecisionRecallDisplay\nfrom sklearn.multiclass import OneVsRestClassifier\nfrom sklearn.metrics import precision_recal...
[ 1 ]
[]
[]
[ "logistic_regression", "plot", "precision_recall", "python", "random_forest" ]
stackoverflow_0073396647_logistic_regression_plot_precision_recall_python_random_forest.txt
Q: Python function which I can not call from kivy ### main.py ### from kivy.app import App class MainScreen(): def button_clicked(self): print("*") class KivyApp(App): pass KivyApp().run() ### kivy.kv ### MainScreen: <MainScreen@BoxLayout>: Button: on_press: root.button_clicked() Why I...
Python function which I can not call from kivy
### main.py ### from kivy.app import App class MainScreen(): def button_clicked(self): print("*") class KivyApp(App): pass KivyApp().run() ### kivy.kv ### MainScreen: <MainScreen@BoxLayout>: Button: on_press: root.button_clicked() Why I can not call button_clicked() function from kivy? ...
[ "So, I am not 100% sure about my answer but here is what I think is happening...\nThe py file runs first and then the kv file, so if in the py file you have Class MainScreen(BoxLayout): the MainScreen class is defined and inherits from BoxLayout... Then the rules are defined in the kV file as normal. When you use t...
[ 0 ]
[]
[]
[ "function", "kivy", "python" ]
stackoverflow_0074242087_function_kivy_python.txt
Q: Extract text available between two keywords and store that text into a list in python In my text file, I have below contents: fdsjhgjhg fdshkjhk Start Good Morning Hello World End dashjkhjk dsfjkhk What should I do I want to extract the text available between word 'start' and 'End' and store in a list ?? A: Here...
Extract text available between two keywords and store that text into a list in python
In my text file, I have below contents: fdsjhgjhg fdshkjhk Start Good Morning Hello World End dashjkhjk dsfjkhk What should I do I want to extract the text available between word 'start' and 'End' and store in a list ??
[ "Here's one way to do it:\ntext = '''fdshkjhk\nStart\nGood Morning\nHello World\nEnd\ndashjkhjk\n'''\nm = re.search(r\"Start.*End\", text, re.S)\nif m is not None:\n print(m[0].split(\"\\n\")[1:-1])\n\nThe subscript [1:-1] peels off the Start and End lines.\nYou could also modify the re to just capture the porti...
[ 0 ]
[]
[]
[ "data_extraction", "information_extraction", "python", "text" ]
stackoverflow_0074248081_data_extraction_information_extraction_python_text.txt
Q: Replace NaNs in multi-index pivot with the mean of columns under specific index I have a DataFrame that is similar this: id = ['A','A','A','A','A','A','A','A','A','A','A','A','B','B','B','B','B','B','C','C','C','C','C','C',] time = ['2021-05-02 01:00:00','2021-05-02 02:00:00','2021-05-02 03:00:00','2021-05-02 04:0...
Replace NaNs in multi-index pivot with the mean of columns under specific index
I have a DataFrame that is similar this: id = ['A','A','A','A','A','A','A','A','A','A','A','A','B','B','B','B','B','B','C','C','C','C','C','C',] time = ['2021-05-02 01:00:00','2021-05-02 02:00:00','2021-05-02 03:00:00','2021-05-02 04:00:00', '2021-05-02 05:00:00','2021-05-02 06:00:00','2021-05-02 07:00:00','2021...
[ "Use slicing and fillna:\ndf['in_dist'] = df['in_dist'].T.fillna(df['in_dist'].mean(axis=1)).T\n\nAs fillna does not support a Series on axis=1 we can use a double transposition.\n" ]
[ 1 ]
[]
[]
[ "multi_index", "pandas", "python" ]
stackoverflow_0074248320_multi_index_pandas_python.txt
Q: Find a certain tag in HTML with web scraping I'm doing web scraping on different html pages with a for loop, and I need to find for every page a certain tag (I'm using BeautifulSoup and find_all method). But not in all the pages that tag exist. So I need to find a simple way to check if that tag exist. I've tried ...
Find a certain tag in HTML with web scraping
I'm doing web scraping on different html pages with a for loop, and I need to find for every page a certain tag (I'm using BeautifulSoup and find_all method). But not in all the pages that tag exist. So I need to find a simple way to check if that tag exist. I've tried to write this code in order to check if the tag do...
[ "As the error message is saying, you can't run find on a list directly - you have to run it on each item\nIf you want to print '1' only if none of them have heading row use:\nif not [s for s in sal_play if s.find('tr', class_='thead')]: \n print('1')\n\nor if you want to print '1' as long some of them don't have...
[ 0 ]
[]
[]
[ "beautifulsoup", "html", "python" ]
stackoverflow_0074147426_beautifulsoup_html_python.txt
Q: Item yield through a visitor page in Scrapy I spent my whole sunday struggling to get a proper response from this website with Scrapy. This is a website containing tenders: I want to get the name of the "Etablissement" (entity) by fetching their respective url (for example https://mapa.aji-france.com/mapa/marche/1...
Item yield through a visitor page in Scrapy
I spent my whole sunday struggling to get a proper response from this website with Scrapy. This is a website containing tenders: I want to get the name of the "Etablissement" (entity) by fetching their respective url (for example https://mapa.aji-france.com/mapa/marche/122942/show) and scrape the content : But sometim...
[ "If you'll check the network tab from the website, you'd find that the subsequent /mapa/guest/anonymous calls contain a cookie that is used to create the very next call to the show page.\n\nYou'll be able to scrape items, once you enable cookies in your spider. The cookies can be enabled by setting the COOKIES_ENAB...
[ 1 ]
[]
[]
[ "python", "scrapy", "web_scraping" ]
stackoverflow_0074174567_python_scrapy_web_scraping.txt
Q: Getting elements from a list that has a prefix Let's say I have a few lists: list = ["MacOS-1", "MacOS-2", "Windows-1", "Windows-2"] maclist = [] windowslist = [] How do I get elements from "list" and sort them into "maclist" or "windowslist" according to if they have "MacOS" or "Windows" in front of them? I was ...
Getting elements from a list that has a prefix
Let's say I have a few lists: list = ["MacOS-1", "MacOS-2", "Windows-1", "Windows-2"] maclist = [] windowslist = [] How do I get elements from "list" and sort them into "maclist" or "windowslist" according to if they have "MacOS" or "Windows" in front of them? I was thinking: (I haven't tested this yet) for element in...
[ "You can use startswith function in Python.\nfor element in list:\n if element.startswith(\"MacOS\"):\n maclist.append(element)\n elif element.startswith(\"Windows\"):\n windowslist.append(element)\n\nIn your code, you don't only check prefixes, also you check all substrings in any index range.\nOr, you can...
[ 1, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0072257835_list_python.txt
Q: how to use while loop? number = 50 while number >= 0: if number % 5 == 0: print(number) number = number - 1 elif number % 5 == 1: continue number = number = number - 1 the answer it's giving me is 50 then the loop stops executing Here is the program I am trying to make:...
how to use while loop?
number = 50 while number >= 0: if number % 5 == 0: print(number) number = number - 1 elif number % 5 == 1: continue number = number = number - 1 the answer it's giving me is 50 then the loop stops executing Here is the program I am trying to make: While Loops Practice #2 Cre...
[ "Here is your code, improved:\nnumber = 50\n\nwhile number >= 0:\n if number % 5 == 0:\n print(number)\n number = number - 1\n\nI'm confused about that too, but here are my thoughts: you only subtracted when number % 5 == 1, but it can also be 2, 3, 4 or 5.\n", "Make sure you always subtract 1 from n...
[ 1, 0, 0, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074248245_python_python_3.x.txt
Q: HDF5 error when opening .nc files in python with xarray I'm attempting to open MERRA-2 files using xarray, as my title suggests. The specific error I am encountering occurs when I attempt to view the values in a certain variable using a print statement. The error is as follows: HDF5-DIAG: Error detected in HDF5 (1...
HDF5 error when opening .nc files in python with xarray
I'm attempting to open MERRA-2 files using xarray, as my title suggests. The specific error I am encountering occurs when I attempt to view the values in a certain variable using a print statement. The error is as follows: HDF5-DIAG: Error detected in HDF5 (1.12.2) thread 5: #000: H5A.c line 528 in H5Aopen_by_name():...
[ "This error occurs due to conflicting non-python (e.g. fortran/C/C++) dependencies.\nThis commonly happens when you install packages using conda with conflicting channels. This happens a lot when using Anaconda. Anaconda is a nice place to start, because it gives you a pre-built bundle (or \"distribution\") of data...
[ 1 ]
[]
[]
[ "hdf5", "netcdf", "python", "python_xarray" ]
stackoverflow_0074226436_hdf5_netcdf_python_python_xarray.txt
Q: Telethon find .session file phone number I have already authorized .session file I forgot his number, tried adding other account to contact, tried changing privacy so I can see from other accs, all with no success.. any suggestions ? A: Log in to the Telethon .session file normally and get the current user of th...
Telethon find .session file phone number
I have already authorized .session file I forgot his number, tried adding other account to contact, tried changing privacy so I can see from other accs, all with no success.. any suggestions ?
[ "Log in to the Telethon .session file normally and get the current user of the session:\nuser = await client.get_entity(\"me\")\nprint(user.phone)\n\n" ]
[ 0 ]
[]
[]
[ "pyrogram", "python", "session", "telethon" ]
stackoverflow_0074247684_pyrogram_python_session_telethon.txt
Q: Retrieve JSON string from pydantic Json type I have a pydantic model as follows. from pydantic import Json, BaseModel class Foo(BaseModel): id: int bar: Json Foo.bar can parse JSON string as input and store it as a dict which is nice. foo = Foo(id=1, bar='{"foo": 2, "bar": 3}') type(foo.bar) #outputs dict...
Retrieve JSON string from pydantic Json type
I have a pydantic model as follows. from pydantic import Json, BaseModel class Foo(BaseModel): id: int bar: Json Foo.bar can parse JSON string as input and store it as a dict which is nice. foo = Foo(id=1, bar='{"foo": 2, "bar": 3}') type(foo.bar) #outputs dict And if i want the entire object to be a dict I c...
[ "Pydantic author here.\nThere's currently no way to do that without calling json.dumps(foo.bar). You could make that a method on Foo if you liked, which would be easier to use but require the same processing.\nIf performance is critical, or you need the exact same JSON string you started with (same spaces etc.) You...
[ 10, 0, 0, 0 ]
[]
[]
[ "pydantic", "python" ]
stackoverflow_0067735198_pydantic_python.txt
Q: IndexError: list index out of range in python while using greater than operator I'm checking if the element in the first index is greater than its corresponding element in the next index. if it is greater to be added into the new list. Here is the code. def solution(A): row1 = [] for index in range(len(A...
IndexError: list index out of range in python while using greater than operator
I'm checking if the element in the first index is greater than its corresponding element in the next index. if it is greater to be added into the new list. Here is the code. def solution(A): row1 = [] for index in range(len(A)): if A[index] > A[index + 1]: row1.append(A[index]) return...
[ "According to this answer. You are trying to reach the non-existing element.\nA[index + 1]\n\nin the last step of the iteration, you will get IndexError.\nUse range(len(A) - 1) instead.\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074248398_python.txt
Q: Show a 2d numpy array where contents are tuples as an image I have a 2d (M * N) numpy array, where each cell contains a tuple of length 3. The tuple contains R, G, and B values for each pixel, e.g. A[0,0] = (0, 255, 0) Is there a way to show this array as an image, possibly without the need to transform it first t...
Show a 2d numpy array where contents are tuples as an image
I have a 2d (M * N) numpy array, where each cell contains a tuple of length 3. The tuple contains R, G, and B values for each pixel, e.g. A[0,0] = (0, 255, 0) Is there a way to show this array as an image, possibly without the need to transform it first to a 3d (M * N *3) array?
[ "Image from PIL should be able to generate a picture from a M*N matrix with RGB as a tuple.\nfrom PIL import Image\nimport numpy as np\nmatrix = np.array([[(100,100,100),(100,100,100),(100,100,100)],[(100,100,100),(100,255,100),(100,100,100)],[(100,100,100),(100,100,100),(100,100,100)]])\nim = Image.fromarray(matri...
[ 1, 0 ]
[]
[]
[ "image", "image_processing", "numpy", "numpy_ndarray", "python" ]
stackoverflow_0073382388_image_image_processing_numpy_numpy_ndarray_python.txt
Q: Convert columns to string in Pandas I have the following DataFrame from a SQL query: (Pdb) pp total_rows ColumnID RespondentCount 0 -1 2 1 3030096843 1 2 3030096845 1 and I want to pivot it like this: total_data = total_rows.pivot_table(cols=['ColumnID...
Convert columns to string in Pandas
I have the following DataFrame from a SQL query: (Pdb) pp total_rows ColumnID RespondentCount 0 -1 2 1 3030096843 1 2 3030096845 1 and I want to pivot it like this: total_data = total_rows.pivot_table(cols=['ColumnID']) (Pdb) pp total_data ColumnID ...
[ "One way to convert to string is to use astype:\ntotal_rows['ColumnID'] = total_rows['ColumnID'].astype(str)\n\nHowever, perhaps you are looking for the to_json function, which will convert keys to valid json (and therefore your keys to strings):\nIn [11]: df = pd.DataFrame([['A', 2], ['A', 4], ['B', 6]])\n\nIn [12...
[ 553, 122, 79, 32, 19, 7, 1, 0 ]
[]
[]
[ "pandas", "python", "string", "type_conversion" ]
stackoverflow_0022005911_pandas_python_string_type_conversion.txt
Q: How to calculate row-wise average of a 2-D numpy array of only non-zero elements and subtract average from the non-zero elements I am building a recommendation system. I am using NumPy arrays to represent users, where each row is a user and each column is a movie. I want to normalize each row by subtracting the av...
How to calculate row-wise average of a 2-D numpy array of only non-zero elements and subtract average from the non-zero elements
I am building a recommendation system. I am using NumPy arrays to represent users, where each row is a user and each column is a movie. I want to normalize each row by subtracting the average of each row from the non-zero elements (i.e from only those entries for which the user provided a rating). I have tried many way...
[ "First compute where condition array (which elements to operate on):\nwh = x != 0\n\nThen compute the mean of the \"wanted\" elements:\nmn = np.mean(x, axis=1, where=wh)[:, np.newaxis]\n\nNote that [:, np.newaxis] converts a 1-D result into a 2-D\narray with a single column.\nCaution: where parameter has been intro...
[ 0 ]
[]
[]
[ "collaborative_filtering", "numpy", "python" ]
stackoverflow_0074243187_collaborative_filtering_numpy_python.txt
Q: Why is Gaussian Filter different between cv2 and skimage? I've got an image that I apply a Gaussian Blur to using both cv2.GaussianBlur and skimage.gaussian_filter libraries, but I get significantly different results. I'm curious as to why, and what can be done to make skimage look more like cv2. I know skimage....
Why is Gaussian Filter different between cv2 and skimage?
I've got an image that I apply a Gaussian Blur to using both cv2.GaussianBlur and skimage.gaussian_filter libraries, but I get significantly different results. I'm curious as to why, and what can be done to make skimage look more like cv2. I know skimage.gaussian_filter is a wrapper around scipy.scipy.ndimage.filters...
[ "If anyone is curious about how to make skimage.gaussian_filter() match Matlab's equivalent imgaussfilt() (the reason I found this question), pass the parameter 'truncate=2' to skimage.gaussian_filter(). Both skimage and Matlab calculate the kernel size as a function of sigma. Matlab's default is 2. Skimage's defau...
[ 7, 5, 4, 1, 1 ]
[]
[]
[ "gaussianblur", "image", "opencv", "python", "scikit_image" ]
stackoverflow_0036263738_gaussianblur_image_opencv_python_scikit_image.txt
Q: How to divide multi digit number into fewer digit number in Python? I want divide a 8-digit number into parts with a 4 digit. pls help def div4(a, n = 4): return [a [i*4: (i + 1) * 4] for i in range (len(a) // n)] i tried this but it wont work A: You can use stdlib divmod: >>> divmod(12345678, 10**4) (1234...
How to divide multi digit number into fewer digit number in Python?
I want divide a 8-digit number into parts with a 4 digit. pls help def div4(a, n = 4): return [a [i*4: (i + 1) * 4] for i in range (len(a) // n)] i tried this but it wont work
[ "You can use stdlib divmod:\n>>> divmod(12345678, 10**4)\n(1234, 5678)\n\nGeneralizing this idea:\n>>> def div(a, n=4):\n... if a < 0:\n... result = div(-a, n)\n... result[0] *= -1\n... return result\n... p = 10 ** n\n... results = []\n... while a >= p:\n... a, b = di...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074248195_python.txt
Q: Plotly Dash Sharing data between more than two pages While using plotly dash, I want to choose something from a dropdown on page 1, pass that value to page 2 (and filter some data on here), choose from a dropdown on page 2 and pass both values from page 1 and 2 to page 3 to filter some more data here. I've tried u...
Plotly Dash Sharing data between more than two pages
While using plotly dash, I want to choose something from a dropdown on page 1, pass that value to page 2 (and filter some data on here), choose from a dropdown on page 2 and pass both values from page 1 and 2 to page 3 to filter some more data here. I've tried using the Store but encounter a problem that "A nonexistent...
[ "The dcc.Store is the way to do this. I expect what you are doing wrong is that the Store is situated within one of your pages in your layout, hence when the page switches out you lose the store. What you need to do is create the store in the root of your layout, so that it is accessible from all the pages.\nHere i...
[ 1 ]
[]
[]
[ "plotly", "plotly_dash", "python" ]
stackoverflow_0074233479_plotly_plotly_dash_python.txt
Q: TypeError: 'str' object is not callable beautifulsoup i have this code for scraping facebook using beautifulsoup but getting an error in the 'str' part. i've read that python reads this like a variable which should be a function. but I still don't understand the point. from selenium import webdriver from selenium...
TypeError: 'str' object is not callable beautifulsoup
i have this code for scraping facebook using beautifulsoup but getting an error in the 'str' part. i've read that python reads this like a variable which should be a function. but I still don't understand the point. from selenium import webdriver from selenium.webdriver.chrome.options import Options from bs4 import Be...
[ "This might be easier to figure out if you share which line triggered this, but according to this thread about the same error message,\n\n...suggests that this can happen if you've defined a variable called str before running your script. Then python thinks you are referring to this variable and wonders why you are...
[ 0 ]
[]
[]
[ "beautifulsoup", "python", "web_scraping" ]
stackoverflow_0074198654_beautifulsoup_python_web_scraping.txt
Q: Error when working with kivymd "AttributeError: 'super' object has no attribute '__getattr__'" I know that this question has probably already been asked many times, but I have a slightly different style structure. I am trying to write a dynamic 3D Card to a dynamic Tab by id, but an error comes out. Here is a piec...
Error when working with kivymd "AttributeError: 'super' object has no attribute '__getattr__'"
I know that this question has probably already been asked many times, but I have a slightly different style structure. I am trying to write a dynamic 3D Card to a dynamic Tab by id, but an error comes out. Here is a piece of KivyMD style: <Tab> ScrollView: MDBoxLayout: id: tab_box or...
[ "Code snippet:\nif tab_text == \"section name\":\n newss = [\"news1\", \"news2\", \"news3\", \"news4\", \"news5\"]\n for news in newss:\n self.root.ids.tab_box.add_widget(\n MD3Card(\n text=news\n )\n )\n\nReplace with:\nif tab_text == \"section name\":\n i...
[ 0 ]
[]
[]
[ "kivy", "kivymd", "python" ]
stackoverflow_0074247628_kivy_kivymd_python.txt
Q: mp3 file name replace So my concern on a logic of a program. I have a Music folder with many mp3 files with underscores in names (MC_-_Best_track.mp3). So I want to scan this folder and replace all underscores with whitespaces. I want to write it myself first but I need a kickstart for that) Can you help me in log...
mp3 file name replace
So my concern on a logic of a program. I have a Music folder with many mp3 files with underscores in names (MC_-_Best_track.mp3). So I want to scan this folder and replace all underscores with whitespaces. I want to write it myself first but I need a kickstart for that) Can you help me in logic? Update: Still struggle ...
[ "I think this maybe work\nimport os \n\npath = \"your folder path\"\n\n\ndata = os.listdir(path)\n\n\nfor file in data:\n if file.endswith(\".mp3\"):\n\n\n file_name = file.lower()\n file = file_name\n \n\n os.rename(os.path.join(path, file), os.path.join(path, file.replace(\"_\",\" \")))\n ...
[ 1 ]
[]
[]
[ "directory", "python", "rename", "subdirectory" ]
stackoverflow_0074248372_directory_python_rename_subdirectory.txt
Q: Repeating prints on backtracking/recursion algorithm: I am studying a backtracking solution, but I don’t understand why a print is repeating inside the loop. It does not seem instantiated by the recursive function or the loop. I think it will be explained better by the code (leave here the source link as well://le...
Repeating prints on backtracking/recursion algorithm:
I am studying a backtracking solution, but I don’t understand why a print is repeating inside the loop. It does not seem instantiated by the recursive function or the loop. I think it will be explained better by the code (leave here the source link as well://leetcode.com/problems/subsets/discuss/2739067/PythonJavaJSC++...
[ "The second BAG2 goes with the second BAG1. Try adding indentation to your output so you can see which level of recursion each is happening at:\nfrom typing import List\n\ndef subsets(nums: List[int]) -> List[List[int]]:\n all_subset = []\n bag = []\n \n \n def makeSubsetFrom( startIndex ):\n ...
[ 1 ]
[]
[]
[ "algorithm", "backtracking", "python", "recursion" ]
stackoverflow_0074248483_algorithm_backtracking_python_recursion.txt
Q: What is the meaning of this code, how does the sum of a consecutive number work? N = int(input()) count = N x = range(1, N +1) for i in x: N = i + N print(N - count) can someone tell me and explain how this code works? I have been spending minutes looking at this and still cant figure out whats going on, t...
What is the meaning of this code, how does the sum of a consecutive number work?
N = int(input()) count = N x = range(1, N +1) for i in x: N = i + N print(N - count) can someone tell me and explain how this code works? I have been spending minutes looking at this and still cant figure out whats going on, the concept is called "sum of consecutive numbers" I tried this code and for example wh...
[ "the given code is unnecessarily complicated and confusing. her a reworked version with some comments:\nN = int(input()) # get input and convert it to int\ntotal = 0 # variable to hold the running total\nfor i in range(1, N + 1): # create numbers from 1 upto N using a range\n total += i ...
[ -1 ]
[]
[]
[ "math", "python", "sum" ]
stackoverflow_0074248235_math_python_sum.txt
Q: Shared class and function code management in Python I'm new to Python for the last 3 months but have quite a bit of development experience. I'm trying to figure out a good way to manage a collection of functions and classes that are shared across several projects. I'm working on a Windows 10 machine that I don't...
Shared class and function code management in Python
I'm new to Python for the last 3 months but have quite a bit of development experience. I'm trying to figure out a good way to manage a collection of functions and classes that are shared across several projects. I'm working on a Windows 10 machine that I don't have admin access to, so the PATH variable is not an opt...
[ "The easiest way would be to package everything in Common into a single .py file in the same folder as your projects.\nThe reasoning is that when you do\nfrom Common.ClassA import ClassA\n\nIt looks in the Common folder, finds the ClassA file, and imports the ClassA class.\nBy organizing your directory structure li...
[ 1, 1 ]
[]
[]
[ "module", "package", "python" ]
stackoverflow_0074247945_module_package_python.txt
Q: Is it possible to change the output alias in pydantic? Setup: # Pydantic Models class TMDB_Category(BaseModel): name: str = Field(alias="strCategory") description: str = Field(alias="strCategoryDescription") class TMDB_GetCategoriesResponse(BaseModel): categories: list[TMDB_Category] @router.get(pat...
Is it possible to change the output alias in pydantic?
Setup: # Pydantic Models class TMDB_Category(BaseModel): name: str = Field(alias="strCategory") description: str = Field(alias="strCategoryDescription") class TMDB_GetCategoriesResponse(BaseModel): categories: list[TMDB_Category] @router.get(path="category", response_model=TMDB_GetCategoriesResponse) a...
[ "Switch aliases and field names and use the allow_population_by_field_name model config option:\nclass TMDB_Category(BaseModel):\n strCategory: str = Field(alias=\"name\")\n strCategoryDescription: str = Field(alias=\"description\")\n\n class Config:\n allow_population_by_field_name = True\n\nLet th...
[ 30, 4, 0, 0 ]
[]
[]
[ "fastapi", "json", "json_deserialization", "pydantic", "python" ]
stackoverflow_0069306103_fastapi_json_json_deserialization_pydantic_python.txt
Q: Pydantic field JSON alias simply does not work I need to specify a JSON alias for a Pydantic object. It simply does not work. from pydantic import Field from pydantic.main import BaseModel class ComplexObject(BaseModel): for0: str = Field(None, alias="for") def create(x: int, y: int): print("was here") ...
Pydantic field JSON alias simply does not work
I need to specify a JSON alias for a Pydantic object. It simply does not work. from pydantic import Field from pydantic.main import BaseModel class ComplexObject(BaseModel): for0: str = Field(None, alias="for") def create(x: int, y: int): print("was here") co = ComplexObject(for0=str(x * y)) return ...
[ "You need to use the alias for object initialization. ComplexObject(for=str(x * y))\nHowever for cannot be used like this in python, because it indicates a loop!\nYou can use it like this : co = ComplexObject(**{\"for\": str(x * y)})\n", "You can add the allow_population_by_field_name=True value on the Config for...
[ 6, 0 ]
[]
[]
[ "fastapi", "pydantic", "python" ]
stackoverflow_0066936511_fastapi_pydantic_python.txt
Q: Python / Tensorflow - required broadcastable shapes I am facing an error while training my model. required broadcastable shapes [[{{node binary_crossentropy/logistic_loss/mul}}]] [Op:__inference_train_function_5643] I have tried following this. https://towardsdatascience.com/ai-for-textiles-convolutional-neu...
Python / Tensorflow - required broadcastable shapes
I am facing an error while training my model. required broadcastable shapes [[{{node binary_crossentropy/logistic_loss/mul}}]] [Op:__inference_train_function_5643] I have tried following this. https://towardsdatascience.com/ai-for-textiles-convolutional-neural-network-based-fabric-structure-classifier-c0db5433501...
[ "Ok, I got it\nI change at import libary from\nfrom keras.layers import AveragePooling2D;\nfrom keras. layers.core import Dense, Flatten;\nfrom keras.models import Model;\n\nto\nfrom tensorflow.keras.models import *\nfrom tensorflow.keras.layers import *\n\nAnd change\nx = Dense(2, activation = 'softmax')(x);\n\nt...
[ 0 ]
[]
[]
[ "google_colaboratory", "keras", "python", "tensorflow" ]
stackoverflow_0074248163_google_colaboratory_keras_python_tensorflow.txt
Q: Find linked elements betwenn two list Probably this is a very stupid mistake but I can't find a solution. I have the lists below: node_pair = [('a', 'b'), ('b', 'a')] edge_list = [ (1, 'unuseful thing', {'orig-id': 'a'}), (11, 'unuseful thing', {'orig-id': 'b'}), ] I need to find the numeric couple in edg...
Find linked elements betwenn two list
Probably this is a very stupid mistake but I can't find a solution. I have the lists below: node_pair = [('a', 'b'), ('b', 'a')] edge_list = [ (1, 'unuseful thing', {'orig-id': 'a'}), (11, 'unuseful thing', {'orig-id': 'b'}), ] I need to find the numeric couple in edge_list that is related to node_pair. For ('...
[ "Using append works only when the order in the node_pair list is the same as in the edge_list, because this way the value is added at the end of the list. When the order could vary you have to place the matched value in a specific position - like:\ngraph_start_end_node = [None, None]\nfor edge in edge_list:\n ed...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074248440_python.txt
Q: Struggling to graph a Beta Distribution using Python Given some measures I am trying to create a beta distribution. Given a max, min, mean and also an alpha and beta how do I call the beta.ppf or beta.pfd to generate a proper data set? Working Sample https://www.kaggle.com/iancoetzer/betaworking Broken Sample http...
Struggling to graph a Beta Distribution using Python
Given some measures I am trying to create a beta distribution. Given a max, min, mean and also an alpha and beta how do I call the beta.ppf or beta.pfd to generate a proper data set? Working Sample https://www.kaggle.com/iancoetzer/betaworking Broken Sample https://www.kaggle.com/iancoetzer/betaproblem import matplotli...
[ "We managed to code a simple solution to compute and plot the Beta Distribution as follow: see the red beta curve.\nNow we are trying to plot a Weibull distribution ...\n\n\n#import libraries\nimport pandas as pd, numpy as np, gc, time, os, uuid, math, datetime\nfrom joblib import Parallel, delayed\nfrom numpy.rand...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074154672_python.txt
Q: RuntimeError: Cannot close a running event loop I'm trying to resolve this error: RuntimeError: Cannot close a running event loop in my asyncio process. I believe it's happening because there's a failure while tasks are still pending, and then I try to close the event loop. I'm thinking I need to await the remaini...
RuntimeError: Cannot close a running event loop
I'm trying to resolve this error: RuntimeError: Cannot close a running event loop in my asyncio process. I believe it's happening because there's a failure while tasks are still pending, and then I try to close the event loop. I'm thinking I need to await the remaining responses prior to closing the event loop, but I'm...
[ "To answer the question as originally stated, there is no need to close() a running loop, you can reuse the same loop for the whole program.\nGiven the code in the update, your queue_manager could look like this:\ntry:\n self.loop.run_until_complete(future)\nexcept Exception as e:\n self.check_in_records()\n ...
[ 4, 0 ]
[]
[]
[ "aiohttp", "asynchronous", "python", "python_asyncio" ]
stackoverflow_0051862318_aiohttp_asynchronous_python_python_asyncio.txt
Q: How to edit a csv file using pandas in python So I have this data file I generated from a bigger one. Now I want to add a summary to the new file which includes MAX MIN MEAN all of these functions but i don't know how to write it into the file after generating it file1 = file.sample(int(sample)) file1_max = file1....
How to edit a csv file using pandas in python
So I have this data file I generated from a bigger one. Now I want to add a summary to the new file which includes MAX MIN MEAN all of these functions but i don't know how to write it into the file after generating it file1 = file.sample(int(sample)) file1_max = file1.max() file1.to_csv( Path,index=False, header=False...
[ "The following code shows mean, max, min and other stats:\nfile1.describe()\n\n" ]
[ 0 ]
[]
[]
[ "csv", "max", "pandas", "python", "sample" ]
stackoverflow_0074230782_csv_max_pandas_python_sample.txt
Q: Content not visible on webpage I am creating a database website with python and django. My problem is that the content I try to get data from my class' fields doesn't appear on the id-page on django. I am able to make a successful search, and I get links for my searches. The name-field is visible in searches and o...
Content not visible on webpage
I am creating a database website with python and django. My problem is that the content I try to get data from my class' fields doesn't appear on the id-page on django. I am able to make a successful search, and I get links for my searches. The name-field is visible in searches and on the page, but nothing else appears...
[ "You have named the key of context as luokkalistaus not luokka, so the template should be:\n{% extends 'tietokanta/base.html' %}\n\n{% block content %}\n\n<center>\n\n{{ luokkalistaus.nimi }}\n{{ luokkalistaus.vara }}\n{{ luokkalistaus.varaaja }}\n \n</center>\n\n{% endblock %}\n\n" ]
[ 2 ]
[]
[]
[ "django", "django_models", "django_templates", "django_views", "python" ]
stackoverflow_0074248459_django_django_models_django_templates_django_views_python.txt
Q: Python loop continues without stop import random given_number = round(float(input("Enter a number;\n"))) loop = True while loop: def Possibility(maximum): count = 0 while count == 0: x = random.randint(0, maximum) if x: print("X is True") else: print("X is...
Python loop continues without stop
import random given_number = round(float(input("Enter a number;\n"))) loop = True while loop: def Possibility(maximum): count = 0 while count == 0: x = random.randint(0, maximum) if x: print("X is True") else: print("X is false") count += 1 ...
[ "import random\n\ngiven_number = round(float(input(\"Enter a number;\\n\")))\n\n\ndef Possibility(maximum):\n count = 0\n while count == 0:\n x = random.randint(0, maximum)\n print(x)\n if x:\n print(\"X is True\")\n return True\n else:\n print(\"X...
[ 0 ]
[]
[]
[ "function", "loops", "python", "while_loop" ]
stackoverflow_0074248663_function_loops_python_while_loop.txt
Q: turning list of dictionaries into geopandas geometry I am struggling to solve this and have been working for a solution for several days now with no luck. I have a GeoPandas GeoDataFrame which contains a column named geometry. This column consists of a list of dictionaries, in which there are two key:value pairs r...
turning list of dictionaries into geopandas geometry
I am struggling to solve this and have been working for a solution for several days now with no luck. I have a GeoPandas GeoDataFrame which contains a column named geometry. This column consists of a list of dictionaries, in which there are two key:value pairs representing lat/long coordinates for nodes in a linestring...
[ "The key to the answer was provided by @michaelDelgado:\n# create a dataframe from the geometry column\nparsed = pd.DataFrame.from_records(results_gdf['geometry'])\n\n# extract the coordinate pairs from each dictionary\nparsed2 = parsed.applymap(lambda x: [x['lat'], x['lon']], na_action='ignore')\n\n# concatenate t...
[ 1 ]
[]
[]
[ "geopandas", "pandas", "python" ]
stackoverflow_0074242512_geopandas_pandas_python.txt
Q: Pass a python variable to SQL query with koalas I am using a databricks notebook and I would like to pass several python variables to an SQL query using koalas.sql. Here a simplified example of what I am trying to do. import databricks.koalas as ks query = """ SELECT * FROM my_database WHE...
Pass a python variable to SQL query with koalas
I am using a databricks notebook and I would like to pass several python variables to an SQL query using koalas.sql. Here a simplified example of what I am trying to do. import databricks.koalas as ks query = """ SELECT * FROM my_database WHERE animal = pyth_var """ ks.sql(query, global...
[ "I think all you need is to wrap the reference variables in your SQL statement in curly braces, so that Koalas can interpret them as variables. The\ndocs say:\n\n(koalas.sql) This function also supports embedding Python variables (locals, globals, and parameters) in the SQL statement by wrapping them in curly brace...
[ 0 ]
[]
[]
[ "databricks", "python", "spark_koalas", "sql" ]
stackoverflow_0074208130_databricks_python_spark_koalas_sql.txt
Q: How to repair an error "Pyperclip could not find a copy/paste mechanism in your device" in Python Kivy? I am using Pyperclip library in Python in Kivy UI, and I want to be able to copy a text by pressing a button, but it gives me this error message: pyperclip.PyperclipException: Pyperclip could not find a co...
How to repair an error "Pyperclip could not find a copy/paste mechanism in your device" in Python Kivy?
I am using Pyperclip library in Python in Kivy UI, and I want to be able to copy a text by pressing a button, but it gives me this error message: pyperclip.PyperclipException: Pyperclip could not find a copy/paste mechanism for your system. For more information, please visit https://pyperclip.readthedocs.io/...
[ "Thanks to the comments, I've found it. The .py:\nimport kivy\nfrom kivy.core.clipboard import Clipboard\nkivy.require(\"1.10.1\")\nfrom kivy.uix.screenmanager import ScreenManager, Screen\nfrom kivy.uix.button import Button\nfrom kivy.app import App\n\nclass Screen1(Screen):\n def copy_on_press(self): \n ...
[ 0 ]
[]
[]
[ "kivy", "kivy_language", "pyperclip", "python" ]
stackoverflow_0074247892_kivy_kivy_language_pyperclip_python.txt
Q: Django-Rest-Framework - nested serializers - Original exception text was: 'RelatedManager' object has no attribute 'field' I cannot find a proper solution to make class Colors many=false, I got below code that works: from django.conf import settings from django.db import models class Hall(models.Model): owner...
Django-Rest-Framework - nested serializers - Original exception text was: 'RelatedManager' object has no attribute 'field'
I cannot find a proper solution to make class Colors many=false, I got below code that works: from django.conf import settings from django.db import models class Hall(models.Model): owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) name = models.CharField(max_length=255) status...
[ "The easiest way is to add SerializerMethodField instead of adding directly as ColorsSerializer because colors is a related name for Hall.\nclass HallSerializer(serializers.ModelSerializer):\n owner = serializers.HiddenField(default=serializers.CurrentUserDefault())\n colors = ColorsSerializer(write_only=True...
[ 0 ]
[]
[]
[ "django_rest_framework", "python" ]
stackoverflow_0074248229_django_rest_framework_python.txt
Q: Current path didn't match the url patterns - Django I am unable to get the url redirected to one of the patterns defined in the url routing file. web.py from django.urls import path from django.contrib import admin from heyurl import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.i...
Current path didn't match the url patterns - Django
I am unable to get the url redirected to one of the patterns defined in the url routing file. web.py from django.urls import path from django.contrib import admin from heyurl import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name='index'), path('store', views.store, name=...
[ "I think you expect to get RQvw4 as url - so you should define path with parameter <url> like\npath('<url>/metrics/', ...)\n\nAnd then you should keep url in function\ndef get_month_metrics(request, url):\n\n\nEDIT:\nIf you hardcode\npath('RQvw4/metrics/',...)\n\nthen it doesn't know that you want to assign RQvw4 t...
[ 2, 0 ]
[]
[]
[ "django", "django_urls", "python", "python_3.x" ]
stackoverflow_0074248296_django_django_urls_python_python_3.x.txt
Q: IndexError: list index out of range despite code actually working I keep getting this error when trying to reference a nested list. I know I must be within the actual range of the list, yet i still get the error self = list() for index in points: if(index[0]==x or index[1]==y): ...
IndexError: list index out of range despite code actually working
I keep getting this error when trying to reference a nested list. I know I must be within the actual range of the list, yet i still get the error self = list() for index in points: if(index[0]==x or index[1]==y): self.append(index) Above is the assignment to self. Points (which is w...
[ "self (bad variable name) is probably no longer a nested list since you only append index.\nTry print(points[1][0]) or print(self[0])\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074248719_python.txt
Q: Python Django: ImportError: cannot import name '...' from partially initialized module '...' (most likely due to a circular import) (......) In a Django project, I need to import class-A from file-1 in file-2. and import class-B from file-2 in file-1. These classes have their unique methods, and I want to use thes...
Python Django: ImportError: cannot import name '...' from partially initialized module '...' (most likely due to a circular import) (......)
In a Django project, I need to import class-A from file-1 in file-2. and import class-B from file-2 in file-1. These classes have their unique methods, and I want to use these methods within another file (like description above). I'm working with: Python 3.8.10 (within a virtual environment) Windows 10 - 64 bit (lates...
[ "If in one of the modules you import a model only to make a relation to it, e.g.:\nfrom characters.models import Character\n\nclass Inventory(models.Model):\n character = models.OneToOneField(Character, on_delete=models.CASCADE, related_name='inventory')\n\nYou can do this and so remove the import at the beginni...
[ 1, 0, 0 ]
[]
[]
[ "django", "python", "python_3.x", "windows" ]
stackoverflow_0073433712_django_python_python_3.x_windows.txt
Q: QFontMetrics leave extra space between lines I'm trying to draw multiple paragraphs of text with PySide6's QPainter and QFontMetrics. I want to draw them with the same spacing as they would have if I drew them all in a single block of text, but the line spacing isn't quite right. In the following example, the font...
QFontMetrics leave extra space between lines
I'm trying to draw multiple paragraphs of text with PySide6's QPainter and QFontMetrics. I want to draw them with the same spacing as they would have if I drew them all in a single block of text, but the line spacing isn't quite right. In the following example, the font metrics say that the font's line spacing is 17. W...
[ "First of all, the height of a bounding rect of a font metrics doesn't depend on the characters used, but on the font specifications.\nTwo lines of text don't have the double of the height() of the bounding rect of a single line: instead, you have to consider the lineSpacing().\nIn practice, the height of a boundin...
[ 1 ]
[]
[]
[ "fonts", "pyside6", "python" ]
stackoverflow_0074246330_fonts_pyside6_python.txt
Q: How to fix this error "AttributeError: module 'socket' has no attribute 'gethostname'" I am trying to execute this script to get the hostname of my laptop I use Windows7 64bit and Python 3.6.4 I have tried this code in Python IDE and it worked . This error occurred in PyCharm import socket c = socket.gethostname()...
How to fix this error "AttributeError: module 'socket' has no attribute 'gethostname'"
I am trying to execute this script to get the hostname of my laptop I use Windows7 64bit and Python 3.6.4 I have tried this code in Python IDE and it worked . This error occurred in PyCharm import socket c = socket.gethostname() print(c) Do you have any solutions?
[ "It's very likely that your file is named as socket.py.\nThen when you import socket, it will import the current file instead of the python socket module.\nRename your file to another name and rm -rf socket.pyc (to remove the compiled bytecode generated by previous executions).\n", "When I was importing matplotli...
[ 1, 0, 0 ]
[]
[]
[ "pycharm", "python", "python_3.x", "sockets", "windows" ]
stackoverflow_0057493313_pycharm_python_python_3.x_sockets_windows.txt
Q: Python - Extract/access information from json via Kraken API I'm trying to understand how to work with the json returns I am getting from de Kraken API. This is my code: resp = kraken_request("/0/private/TradeBalance", { "nonce": str(int(10000*time.time())), "asset": "USD" }, api_key, api_sec) print("Trad...
Python - Extract/access information from json via Kraken API
I'm trying to understand how to work with the json returns I am getting from de Kraken API. This is my code: resp = kraken_request("/0/private/TradeBalance", { "nonce": str(int(10000*time.time())), "asset": "USD" }, api_key, api_sec) print("TradeBalance: " + str(resp.json())) resp = kraken_request("/0/private...
[ "You should use pandas. You can see all the data in a table. This is much easier than working with a json.\nimport pandas as pd\nimport numpy as np\nnull=np.nan\n\nreturned_json={\"error\":[],\"result\":{\"open\":{\"ABCDE-AWSCG-ABCDE\":{\"refid\":null,\"userref\":0,\"status\":\"open\",\"opentm\":1666683580.8848298,...
[ 1 ]
[]
[]
[ "api", "json", "kraken.com", "python" ]
stackoverflow_0074245774_api_json_kraken.com_python.txt
Q: "RuntimeError: Cannot close a running event loop" in Python I use loop.close() in test() to close the event loop as shown below: import asyncio async def test(loop): print("Test") loop.stop() # Stop the event loop loop.close() # Here loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop....
"RuntimeError: Cannot close a running event loop" in Python
I use loop.close() in test() to close the event loop as shown below: import asyncio async def test(loop): print("Test") loop.stop() # Stop the event loop loop.close() # Here loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.create_task(test(loop)) loop.run_forever() But, I got the error...
[]
[]
[ "You need to use loop.close() after loop.run_forever() with try: and finally: as shown below, then the error is solved:\nimport asyncio\n\nasync def test(loop):\n print(\"Test\")\n loop.stop()\n\nloop = asyncio.new_event_loop()\nasyncio.set_event_loop(loop)\n\nloop.create_task(test(loop))\n\ntry:\n loop.ru...
[ -1 ]
[ "asynchronous", "event_loop", "python", "python_3.x", "python_asyncio" ]
stackoverflow_0074248937_asynchronous_event_loop_python_python_3.x_python_asyncio.txt
Q: Python nested loop patterns - star with gaps in-between I'm new and I'm unable to replicate the following: * * ** ** *** *** ******** I'm using loops to create all kinds of triangles but I just can't figure out how to count for the spaces in the code. * * * * * * * * * * * * * * * * * * * * * Is t...
Python nested loop patterns - star with gaps in-between
I'm new and I'm unable to replicate the following: * * ** ** *** *** ******** I'm using loops to create all kinds of triangles but I just can't figure out how to count for the spaces in the code. * * * * * * * * * * * * * * * * * * * * * Is there a page/video that directly explains the loop?
[ "I don't have a page or video for you, but worked out a solution myself. So what we are trying to do here is to print 4 lines with an increasing number of stars for each line on both sides of some spaces. So all we have to is setup a loop that counts the number of stars and counts how many spaces we need to place b...
[ 0 ]
[]
[]
[ "loops", "nested", "python" ]
stackoverflow_0074248835_loops_nested_python.txt
Q: OpenMDAO: pyOptSparse building script So I am opening this new thread about how to build pyOptSparse and use it within the OpenMDAO framework. The OpenMDAO team released a scrip which should build pyOptSparse by integrating IPOPT as well: https://github.com/OpenMDAO/build_pyoptsparse I followed their instructions ...
OpenMDAO: pyOptSparse building script
So I am opening this new thread about how to build pyOptSparse and use it within the OpenMDAO framework. The OpenMDAO team released a scrip which should build pyOptSparse by integrating IPOPT as well: https://github.com/OpenMDAO/build_pyoptsparse I followed their instructions on a Ubuntu virtual machine. Unfortunately,...
[ "I ran into a similar issue when trying to install this package to use it with openmdao/dymos. I'm using Linux Mint with conda 22.9.0. These are the steps that I followed to fully set up my environment, answering yes to all prompts:\n#Create and activate new environment with python 3.10 and pip\nconda create -n py3...
[ 1, 0 ]
[]
[]
[ "openmdao", "python" ]
stackoverflow_0073875458_openmdao_python.txt
Q: combine itertools 2 product with specified amount of variables i am tryin to make a product that has 2 lists with 3 variables each combined into 1 list/product i am trying to combine 3 letters and 3 numbers so i am using string for those this is psuedo code ` product(string.ascii_lowercase, repeat=int(3)) + produc...
combine itertools 2 product with specified amount of variables
i am tryin to make a product that has 2 lists with 3 variables each combined into 1 list/product i am trying to combine 3 letters and 3 numbers so i am using string for those this is psuedo code ` product(string.ascii_lowercase, repeat=int(3)) + product(string.digits, repeat=int(3)) i have gotten thi working but this ...
[ "basically create two iterators like you are\nalphas = product(string.ascii_lowercase, repeat=int(3))\nnumerics = product(string.digits, repeat=int(3))\n\nturn it into lists instead of iterators\nalphas = list(alphas)\nnumerics = list(numerics)\n\nthen just get the product of those two\npotential_solutions = produc...
[ 0 ]
[]
[]
[ "list", "python", "python_itertools", "string" ]
stackoverflow_0074241745_list_python_python_itertools_string.txt
Q: Python for-loop repeatedly outputting the input() for every iteration of dictionary contact_emails(not what I want) contact_emails = { 'Sue Reyn' : 's.reyn@email.com', 'Mike Filt': 'mike.filt@bmail.com', 'Nate Arty': 'narty042@nmail.com' } new_contact = input()...
Python for-loop repeatedly outputting the input() for every iteration of dictionary contact_emails(not what I want)
contact_emails = { 'Sue Reyn' : 's.reyn@email.com', 'Mike Filt': 'mike.filt@bmail.com', 'Nate Arty': 'narty042@nmail.com' } new_contact = input() new_email = input() contact_emails[new_contact] = new_email for contact in contact_emails: ...
[ "\nfor contact in contact_emails:\n print(new_contact + ' is ' + new_email)\n\n\nYou are printing the new contact again and again. What you need to do is something like this:\nfor contact, email in contact_emails.items():\n print(email + ' is ' + contact)\n\nThis iterates all the key, value pairs of your dict...
[ 1, 0, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "dictionary", "for_loop", "iteration", "python" ]
stackoverflow_0060316377_dictionary_for_loop_iteration_python.txt
Q: Large Movie Review Dataset can anyone help me with an assignment? It's about doing linear regression from scratch on imdb reviews. the data is really heavy and also, I don't understand the assignment itself really well I did some of it but I have some major problem with implementing the logistic regression from sc...
Large Movie Review Dataset
can anyone help me with an assignment? It's about doing linear regression from scratch on imdb reviews. the data is really heavy and also, I don't understand the assignment itself really well I did some of it but I have some major problem with implementing the logistic regression from scratch on the data.
[ "IMDb seems to have an API https://developer.imdb.com/\nMaybe not what you are looking for exactly, but might lead you in the right direction\nI also found this datased on kaggle listing movie reviews, also from IMDb.\nhttps://www.kaggle.com/datasets/lakshmi25npathi/imdb-dataset-of-50k-movie-reviews\nSo IMDb might ...
[ 0 ]
[]
[]
[ "imdb", "jupyter_notebook", "logistic_regression", "nlp", "python" ]
stackoverflow_0074248981_imdb_jupyter_notebook_logistic_regression_nlp_python.txt
Q: Scraping a website with data that's dynamically generated I am trying to scrape the match table from this link: https://www.kayak-polo.info/kpmatchs.php?lang=en&event=0&Saison=2022&Group=CM&Compet=*&J=*&Round=*&Css=&navGroup=1 Unfortunately the data is dynamically generated and I cannot seem to figure out a way to...
Scraping a website with data that's dynamically generated
I am trying to scrape the match table from this link: https://www.kayak-polo.info/kpmatchs.php?lang=en&event=0&Saison=2022&Group=CM&Compet=*&J=*&Round=*&Css=&navGroup=1 Unfortunately the data is dynamically generated and I cannot seem to figure out a way to get it to work. It seems like the data is generated dynamicall...
[ "The desired table data isn't populated by JavaScript meaing data is in static HTML DOM and you can grab the table data using pandas DataFrame.\nimport pandas as pd\nimport requests\nheaders = {'user-agent':'Mozilla/5.0'}\nurl = 'https://www.kayak-polo.info/kpmatchs.php?lang=en&event=0&Saison=2022&Group=CM&Compet=*...
[ 0 ]
[]
[]
[ "python", "web_scraping" ]
stackoverflow_0074248920_python_web_scraping.txt
Q: Python Replace existing column value in df based on separate lookup Code/Value (df) KeyError on columns.get_loc ** Problem ** Replace existing column value in destination data frame based on separate lookup type operations to match Code/Value column in another separate source data frame, and update, e.g., replace ...
Python Replace existing column value in df based on separate lookup Code/Value (df) KeyError on columns.get_loc
** Problem ** Replace existing column value in destination data frame based on separate lookup type operations to match Code/Value column in another separate source data frame, and update, e.g., replace text in destination data frame column with Code/Value of source data. Basically replacing something like '10' with 'Y...
[ "Always hard without having the data.\nBut try:\nemployee['County.Code'].replace(countynames.set_index(\"CountyCode\")[\"Value\"].to_dict(), inplace=True)\n\n" ]
[ 0 ]
[]
[]
[ "apply", "dataframe", "lookup", "pandas", "python" ]
stackoverflow_0074248845_apply_dataframe_lookup_pandas_python.txt
Q: Counting Unique Values in a Column by each row in dataframe I have a dataframe (df) that has two columns (student number, values), one column (values) with multiple comma-separated values in each row. I want to count how many times a unique value occurs in that column by each row. The df looks like this: I want t...
Counting Unique Values in a Column by each row in dataframe
I have a dataframe (df) that has two columns (student number, values), one column (values) with multiple comma-separated values in each row. I want to count how many times a unique value occurs in that column by each row. The df looks like this: I want to know how many times each value (0 and 1) appears in the column ...
[ "Because in data column are not strings but arrays you can use Counter with dict.get for get 0 if no match:\nfrom collections import Counter\n\ndef f(x):\n d = Counter(x)\n return ((d.get(0, 0), d.get(1, 0)))\n\ndf['vector'] = df['values'].apply(f)\nprint (df)\n student value...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074248991_pandas_python.txt
Q: How to configure Pycharm to debug django I am trying to set up Pycharm3.0 to be able to debug the django project.. I cannot get it to work. Any help is greatly appreciated..! :-) I checked the django support is there: I then configured the Run/debug configuration settings as following: . sitee is the project fol...
How to configure Pycharm to debug django
I am trying to set up Pycharm3.0 to be able to debug the django project.. I cannot get it to work. Any help is greatly appreciated..! :-) I checked the django support is there: I then configured the Run/debug configuration settings as following: . sitee is the project folder. When I hit the debug button, I got error:...
[ "It looks as if you are trying to debug using the 'Python' Run/Debug configuration rather than the 'Django server'. Check your left hand column, the one that lists your Run/Debug configs and the defaults that PyCharm provides. Do you see \"Django server\"?\nIf so, clone that one and use it. You hardly need to ...
[ 1, 1, 0 ]
[]
[]
[ "django", "pycharm", "python" ]
stackoverflow_0021335142_django_pycharm_python.txt
Q: Is there a way to change specific "sets" of edges colors in my graph? Is there also a way to add a node with no edges? Networkx For each different set of graphs within the entire graph, I want the colors for the edges to be unique to the "set" within the graph. Here is my code: import networkx as nx import matplot...
Is there a way to change specific "sets" of edges colors in my graph? Is there also a way to add a node with no edges? Networkx
For each different set of graphs within the entire graph, I want the colors for the edges to be unique to the "set" within the graph. Here is my code: import networkx as nx import matplotlib.pyplot as plt G = nx.DiGraph() #Set 1 G.add_edges_from([('A','B'),('A','C'),('C','B')]) #Set 2 G.add_edges_from([('D','A'),('D'...
[ "IIUC, assign your edge groups to a variable then loop through the variable and use edge_colors parameter to change colors. Also, you can use add_node to add an unconnected node to the graph.\nimport networkx as nx\nimport matplotlib.pyplot as plt\n\nax=plt.subplots(figsize=(15,10))\n\nG = nx.DiGraph()\n\n#Set 1\n...
[ 1 ]
[]
[]
[ "data_structures", "graph", "networkx", "python", "python_3.x" ]
stackoverflow_0074248883_data_structures_graph_networkx_python_python_3.x.txt
Q: When passing a list to an api I get the following error code "json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)" So I have been working on creating a mini pokedex using the poke api and I am stuck in a step. This is what I have: import requests import json import pandas as pd pokemon_list = ...
When passing a list to an api I get the following error code "json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)"
So I have been working on creating a mini pokedex using the poke api and I am stuck in a step. This is what I have: import requests import json import pandas as pd pokemon_list = ["charizard", "gengar", "venusaur","golbat","gyarados","lapras", "dragonite", "infernape", "staraptor", "giratina"] # Create empty lists to ...
[ "It turns out res.text is 'Not Found' in the failing case. Don't try to read the JSON if the result fails. FYI, debug yourself by print(res.text) before the line that fails.\nimport requests\nimport json\nimport pandas as pd\n\npokemon_list = [\"charizard\", \"gengar\", \"venusaur\",\"golbat\",\"gyarados\",\"lapr...
[ 0 ]
[]
[]
[ "api", "json", "list", "pokeapi", "python" ]
stackoverflow_0074248870_api_json_list_pokeapi_python.txt
Q: Take product of a dictionary and a list to form multiple keys for a dictionary I've a dictionary, a list, want to combine and form a multiple keys dictionary. the value of the new dictionary is the same as old one. only the single key became multiple keys d = {'gfg' : 1, 'is' : 2, 'the' : 3, 'best' : 4} ls = ['n1'...
Take product of a dictionary and a list to form multiple keys for a dictionary
I've a dictionary, a list, want to combine and form a multiple keys dictionary. the value of the new dictionary is the same as old one. only the single key became multiple keys d = {'gfg' : 1, 'is' : 2, 'the' : 3, 'best' : 4} ls = ['n1', 'n2', 'n3','n4'] Desired output: {('gfg', 'n1'): 1, ('gfg', 'n2'): 2, ('gfg', '...
[ "zip the product with an infinite cyclic repeating sequence:\nfrom itertools import cycle, product\n\ndict(zip(product(d.keys(), ls), cycle(d.values())))\n\n" ]
[ 0 ]
[]
[]
[ "dictionary", "list", "python" ]
stackoverflow_0074249020_dictionary_list_python.txt
Q: How to get a cookie jar object from dict? For default Selenium get_cookies() method returns list of dicts e.g. current_cookies: [{'domain': '.domain.com', 'expiry': 1667110148, 'httpOnly': False, 'name': '_ym_isad', 'path':...
How to get a cookie jar object from dict?
For default Selenium get_cookies() method returns list of dicts e.g. current_cookies: [{'domain': '.domain.com', 'expiry': 1667110148, 'httpOnly': False, 'name': '_ym_isad', 'path': '/', 'sameSite': 'None'...
[ "https://docs.python.org/3/library/http.cookiejar.html\nAnd then something like:\nimport http.cookiejar as cookielib\n\ndef to_cookielib_cookie(selenium_cookie):\n return cookielib.Cookie(\n version=0,\n name=selenium_cookie['name'],\n value=selenium_cookie['value'],\n port='80',\n ...
[ 0 ]
[]
[]
[ "cookiejar", "cookies", "python", "python_3.x", "selenium" ]
stackoverflow_0074244501_cookiejar_cookies_python_python_3.x_selenium.txt
Q: Python with beautiful UI + glass effect I'm a new in Python. I would like to know can I create good interface on python, something like WPF? I didn't find any glass effect with PyQt. It's really important for my decision. Thanks. I'm sorry that I didn't give a lot of details. I need to port WPF app to python. The...
Python with beautiful UI + glass effect
I'm a new in Python. I would like to know can I create good interface on python, something like WPF? I didn't find any glass effect with PyQt. It's really important for my decision. Thanks. I'm sorry that I didn't give a lot of details. I need to port WPF app to python. The main goal I still need a good UI. Can I make...
[ "Glass effect is probably a Qt skin and has nothing to do with Python in particular. People say that there's a tutorial for Qt skinning. I failed to quickly google a ready-made glass-like skin, though.\n", "Also, in the new QT RC there is a new support system for GUI related stuff. QML it is called, and examples ...
[ 3, 2, 1, 0, 0 ]
[]
[]
[ "pyqt", "python" ]
stackoverflow_0005223234_pyqt_python.txt
Q: Creating python decimal with locale formatted string I am using the Python decimal module, I’ve set my locale to Germany such that locale.localeconv()["decimal_point"] is ",". When I try creating a decimal like decimal.Decimal("1,23"), I get a decimal conversion syntax error. When I do decimal.Decimal("1.23"), it ...
Creating python decimal with locale formatted string
I am using the Python decimal module, I’ve set my locale to Germany such that locale.localeconv()["decimal_point"] is ",". When I try creating a decimal like decimal.Decimal("1,23"), I get a decimal conversion syntax error. When I do decimal.Decimal("1.23"), it works. Does the Python decimal not respect locale settings...
[ "No, the decimal.Decimal constructor only accepts numeric strings according to the grammar shown, where . is the only decimal point supported.\n\ndecimal-part ::= digits '.' [digits] | ['.'] digits\n\n\nThe locale settings are only relevant for formatting a Decimal back to a string, see e.g. How can I locale-for...
[ 2 ]
[]
[]
[ "decimal", "python" ]
stackoverflow_0074249159_decimal_python.txt
Q: How to read columns and rows from an Exel file with python? I saved some data generated by a python code. They were saved in Exel format (.csv) using the commands with open(path + '/data_Sevol.csv', 'w', newline='') as csvfile: fieldnames = ['Sevol'] writer = csv.DictWriter(csvfile, fieldnames=fieldnames...
How to read columns and rows from an Exel file with python?
I saved some data generated by a python code. They were saved in Exel format (.csv) using the commands with open(path + '/data_Sevol.csv', 'w', newline='') as csvfile: fieldnames = ['Sevol'] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() for i in range(len(Sevol)): ...
[ "After loading the file, you can print the top 5 rows and see column name and row names:\ndata_Sevol.head()\n\nAfter that, if you want to access any row or column by its name you can make use of below code:\ndata_Sevol.loc[row_name, col_name]\n\nand in case you want to access it using row number or column number, m...
[ 0 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0074249174_csv_python.txt