content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: How to get Telegram user profile photo by user ID with aiogram v2? I trying to get Telegram user profile photo by user ID with aiogram v2. def get_photo(user_id): photo_data = bot.get_user_profile_photos(user_id, 1, 1) return photo_data @dp.message_handler(commands=['photo']) async def get_user_photo(): ...
How to get Telegram user profile photo by user ID with aiogram v2?
I trying to get Telegram user profile photo by user ID with aiogram v2. def get_photo(user_id): photo_data = bot.get_user_profile_photos(user_id, 1, 1) return photo_data @dp.message_handler(commands=['photo']) async def get_user_photo(): photo_data = get_photo(367928353) #logger.error(photo_data) a...
[ "first of all you need read the documentation, namely about handlers. Just your function get_phot is synchronous which used asynchronous method bot.get_user_profile_photos after then you create a handlers get_user_photo() but don't transmit parameters types.Message from aiogram. I rewrote your code and that's what...
[ 0 ]
[]
[]
[ "aiogram", "python" ]
stackoverflow_0074416222_aiogram_python.txt
Q: How to remove data selected by grouped day from dataframe A dataframe needs to get cleaned from certain days. The days to be removed are selected this way: df['_datetime'] = df.index exclude_holidays = df.groupby(df.index.floor('d'))._datetime.last() exclude_holidays.loc[exclude_holidays.dt.hour < 14] output excl...
How to remove data selected by grouped day from dataframe
A dataframe needs to get cleaned from certain days. The days to be removed are selected this way: df['_datetime'] = df.index exclude_holidays = df.groupby(df.index.floor('d'))._datetime.last() exclude_holidays.loc[exclude_holidays.dt.hour < 14] output exclude_holidays: datetime 2020-12-24 2020-12-24 12:07:12 2021-01...
[ "You can try like this:\nexclude_holidays = exclude_holidays.index.values\ndf = df[~df.index.isin(exclude_holidays)]\n\n" ]
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074420307_pandas_python.txt
Q: Python type hints: set kwagrs to TypedDict instead of dict in Pycharm I'm trying to declare a specific structure annotation for kwargs: class MyType(TypedDict): request: PydanticPayload args: Dict[str, Any] def handle_request(self, **kwargs: MyType) -> PydanticResponse: But Pycharm expects that kwargs wi...
Python type hints: set kwagrs to TypedDict instead of dict in Pycharm
I'm trying to declare a specific structure annotation for kwargs: class MyType(TypedDict): request: PydanticPayload args: Dict[str, Any] def handle_request(self, **kwargs: MyType) -> PydanticResponse: But Pycharm expects that kwargs will be Dict[str, MyType] instead of MyType. Is there any way to make Pychar...
[ "Since I couldn't find a way to support kwargs' specific type,\nSo I made sure I send only the specific arguments:\nOn the class that calls handle_request I did:\n self.function = handle_request # (HAPPENS DYNAMICALLY)\n\n\n\n args = flask_request.view_args\n query = flask_request.args\n ...
[ -1 ]
[]
[]
[ "pycharm", "python", "type_hinting" ]
stackoverflow_0074420267_pycharm_python_type_hinting.txt
Q: Pandas: Constructing a cross table from Pandas DataFrame I got a DataFrame generated from a CSV database with a list of districts in Buenos Aires Province (Argentina). The CSV has columns like population and surface of all of these districts. Also, it contains two columns with categorical variables. The first of t...
Pandas: Constructing a cross table from Pandas DataFrame
I got a DataFrame generated from a CSV database with a list of districts in Buenos Aires Province (Argentina). The CSV has columns like population and surface of all of these districts. Also, it contains two columns with categorical variables. The first of these one is called "REGION", and indicates if the district is ...
[ "Try pd.crosstab\npd.crosstab(municipios['REGION'], municipios['PERTENENCIA'])\n\n" ]
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074420299_pandas_python.txt
Q: How ToSetup a Python Flask Server in IONOS? I have an ionos server, and I am trying to run a python flask server on it. I connected to it via a Linux Terminal with ssh, however doing python3 main.py runs it locally: I am new to this, am I doing something wrong? I logged into the ssh with the username and password...
How ToSetup a Python Flask Server in IONOS?
I have an ionos server, and I am trying to run a python flask server on it. I connected to it via a Linux Terminal with ssh, however doing python3 main.py runs it locally: I am new to this, am I doing something wrong? I logged into the ssh with the username and password IONOS gave me in the Web Hosting Essential Page....
[ "You try to access it by using a web browser in your computer:\nhttp://your_server_ip:5000\nIf it can be accessed, everything is good. You can follow this tutorial to deploy it (you can choose a different version same with your version's sever near the top of the tutorial)\nIf it cannot be accessed, maybe your serv...
[ 1, 0 ]
[]
[]
[ "flask", "ionos", "python", "sftp", "ssh" ]
stackoverflow_0065514526_flask_ionos_python_sftp_ssh.txt
Q: Need to show result on the same page - Django I'm creating a password generator app. The app is working and stores the value on db. The problem is whenever I refresh, the form resubmits and takes the previous value and stores. Also, I want to show the email and password on the same page. Whenever I refresh, I want...
Need to show result on the same page - Django
I'm creating a password generator app. The app is working and stores the value on db. The problem is whenever I refresh, the form resubmits and takes the previous value and stores. Also, I want to show the email and password on the same page. Whenever I refresh, I want to show an empty form with empty fields. Views.py ...
[ "According to docs:\n\nyou should always return an HttpResponseRedirect after successfully dealing with POST data. This tip isn’t specific to Django; it’s good web development practice in general.\n\nSo you should make another page to show generated password, which will take submitted instance id of Item model crea...
[ 3 ]
[]
[]
[ "django", "django_forms", "django_urls", "django_views", "python" ]
stackoverflow_0074420199_django_django_forms_django_urls_django_views_python.txt
Q: How do I stop end="" after all the integers have been combined? I want end="" to stop after it has removed all the spaces between integers. The result I get is this: 106111104110word but I want to get this: 106111104110 word Code: name = 'john' for char in name: print(ord(char), end="") print("word") A: ...
How do I stop end="" after all the integers have been combined?
I want end="" to stop after it has removed all the spaces between integers. The result I get is this: 106111104110word but I want to get this: 106111104110 word Code: name = 'john' for char in name: print(ord(char), end="") print("word")
[ "store your answer in a variable, and then print. Other answers in this thread work too, but this way you can also use the result.\nname = 'john' \nresult = \"\"\n\nfor char in name:\n result += str(ord(char))\n\nprint(result)\nprint(\"word\")\n\n", "Add \\n in your code:\nname = 'john' \n\nfor char in name:\n...
[ 3, 1, 0, 0 ]
[]
[]
[ "ord", "python", "string" ]
stackoverflow_0074416758_ord_python_string.txt
Q: What's would be the best way of handling this data? I have a big chuck of data that I'm currently trying to sort into distinct fields. I've been able to get this into lists, structured like: lst = ['A','B','C'] I've been iterating through the resultant lists (10,000 or so), and appending them into dataframes: new...
What's would be the best way of handling this data?
I have a big chuck of data that I'm currently trying to sort into distinct fields. I've been able to get this into lists, structured like: lst = ['A','B','C'] I've been iterating through the resultant lists (10,000 or so), and appending them into dataframes: newdf = pd.DataFrame() df = pd.DataFrame(pd.Series(lst)).tra...
[ "Was able to solve it by creating dict\nif Data1:\n l = ['A','B','C']\n dictlist = ['A','B','C','D','E','F']\nelse Data2:\n l = ['C','D','E','F']\n dictlist = ['C','D','E','F']\nzippeddict = dict(zip(dictlist,l))\ndf = pd.DataFrame(zippeddict ,index=[0])\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074413056_dataframe_pandas_python.txt
Q: How do I get rid of NaTType does not support strftime error in Python? I have some empty rows in my 'Date' column. So when I try to use the code below to format my column, I get the error message "NaTType does not support strftime" How do I avoid this error? df['Date'] = df['Date'].apply(lambda x: pd.to_datetime...
How do I get rid of NaTType does not support strftime error in Python?
I have some empty rows in my 'Date' column. So when I try to use the code below to format my column, I get the error message "NaTType does not support strftime" How do I avoid this error? df['Date'] = df['Date'].apply(lambda x: pd.to_datetime(x).strftime('%Y/%m/%d'))
[ "Do not use apply in the first place. Use the dt accessor. It's more efficient and reliable in this case. Ex:\nimport pandas as pd\n\ndf = pd.DataFrame({\"Date\": [\"2022-11-11\", \"not-a-time\"]})\n\ndf[\"Date\"] = pd.to_datetime(df[\"Date\"], errors=\"coerce\")\n\ndf[\"Date_string\"] = df[\"Date\"].dt.strftime(\"...
[ 0 ]
[]
[]
[ "apply", "datetime", "lambda", "pandas", "python" ]
stackoverflow_0074417145_apply_datetime_lambda_pandas_python.txt
Q: How to get list of subelements that are only one level deep from Python3 xml.etree.Element? If I have a Python3 xml.etree.Element (doc), is it possible to get a list (or iterable, or whatever) of child elements to that Element, but only one level deep? If so, how can I do this? (Note: it appears the xml.etree.Elem...
How to get list of subelements that are only one level deep from Python3 xml.etree.Element?
If I have a Python3 xml.etree.Element (doc), is it possible to get a list (or iterable, or whatever) of child elements to that Element, but only one level deep? If so, how can I do this? (Note: it appears the xml.etree.Element library is essentially the same for the version of Python I'm using (3.6.8) and the latest ve...
[ "xml.etree.ElementTree has limited support for Xpath.\nUsing lxml instead\n>>> from lxml import etree\n>>> doc = etree.parse('tmp.xml')\n>>> parentName = doc.getroot().tag\n>>> level1 = doc.xpath(f'//*[parent::{parentName}]')\n>>> for e in level1:\n... print(e.tag)\n... \nname\nSomeLevel1Element\nSomeLevel1Elem...
[ 0, 0 ]
[]
[]
[ "elementtree", "python", "python_3.x", "xml" ]
stackoverflow_0074416693_elementtree_python_python_3.x_xml.txt
Q: Selenium detection problem in Python. Any suggestions or solutions? I used a selenium library for making my own Nike SNKRS Bot in python, which will work in Chrome browser. I chose one of popular webdriver to manage it by selenium. I got stuck on a Nike login page. Here is my code: import time from selenium import...
Selenium detection problem in Python. Any suggestions or solutions?
I used a selenium library for making my own Nike SNKRS Bot in python, which will work in Chrome browser. I chose one of popular webdriver to manage it by selenium. I got stuck on a Nike login page. Here is my code: import time from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium....
[ "in regards to other platforms you can use, you can try puppeteer, its very similar to selenium and they have a stealth plugin to avoid detection as well as a 2captcha plugin in which you link 2captcha account to solve captchas to further avoid detection.\n" ]
[ 0 ]
[]
[]
[ "browser_automation", "python", "selenium", "selenium_chromedriver" ]
stackoverflow_0074415045_browser_automation_python_selenium_selenium_chromedriver.txt
Q: How can I find a specific button on an Instagram page? What I thought would work isn't I am trying to click the save info button you get when you first log in to an Instagram account. I can't because I keep getting ElementNotFound errors. I tried this code and it gave this error: chrome.find_element(By.CLASS_NAME,...
How can I find a specific button on an Instagram page? What I thought would work isn't
I am trying to click the save info button you get when you first log in to an Instagram account. I can't because I keep getting ElementNotFound errors. I tried this code and it gave this error: chrome.find_element(By.CLASS_NAME, "_acan _acap _acas").click() Traceback (most recent call last): File "C:\Python310\lib\s...
[ "I can't reproduce that. But I see the problem in you approach. By.CLASS_NAME is searching by one class name but here you are trying to search by three names. class attribute in html store one or more class names. If there are more than one class name in the class attribute, class names are separated with spaces. S...
[ 1 ]
[]
[]
[ "findelement", "python", "selenium", "webdriver" ]
stackoverflow_0074417915_findelement_python_selenium_webdriver.txt
Q: Is there a way to retry a selenium loop after an element wasn't found in python I'm writing something in selenium to automate a courseware my school made, I have this infinite loop that goes through the pages of a page and answers the questions until its done, but when I try this I get "No element" then the whole ...
Is there a way to retry a selenium loop after an element wasn't found in python
I'm writing something in selenium to automate a courseware my school made, I have this infinite loop that goes through the pages of a page and answers the questions until its done, but when I try this I get "No element" then the whole program stops, I've tried try/except NoSuchElementException but there's no option to...
[ "You can do it by moving to a separate function the part that goes after opening next page. This gives you a possibility to call it whenever you want:\ndef handle_answers(driver):\n clickable = driver.find_element(by=By.XPATH, value='/html/body/div[2]/div[3]/div[3]/div[3]/div[2]/div[5]/button[3]').click() # sho...
[ 0 ]
[]
[]
[ "loops", "python", "selenium", "selenium_webdriver", "xpath" ]
stackoverflow_0074417220_loops_python_selenium_selenium_webdriver_xpath.txt
Q: Discord bot running locally but not on Azure I have started working on a discord bot which works fine if I run it on my machine, but when I push it to Azure it claims the app is running yet the bot is offline ` import discord bot = discord.Bot() @bot.command(name='whereami', help='print the current server name/i...
Discord bot running locally but not on Azure
I have started working on a discord bot which works fine if I run it on my machine, but when I push it to Azure it claims the app is running yet the bot is offline ` import discord bot = discord.Bot() @bot.command(name='whereami', help='print the current server name/id') async def whereami(ctx): await ctx.send(f...
[]
[]
[ "Im assuming that you already installed all required libraries in azure, if it runs on your machine perfectly fine it most likely would be on azure’s end, i would recommend you try repelit ive hosted plenty of discord bots there no problem and very cheap, you can also go the vps route but those tend to be a bit mor...
[ -1 ]
[ "azure", "discord", "discord.py", "pycord", "python" ]
stackoverflow_0074420557_azure_discord_discord.py_pycord_python.txt
Q: Mypy not displaying errors when target file has absolute path mypy seems to be ignoring at least some errors when called on a file using an absolute address. I had originally presumed this was an issue with my project but it's very easy for me to reproduce on a basic setup. If you have reason to believe this an is...
Mypy not displaying errors when target file has absolute path
mypy seems to be ignoring at least some errors when called on a file using an absolute address. I had originally presumed this was an issue with my project but it's very easy for me to reproduce on a basic setup. If you have reason to believe this an issue with my machine setup, I would love to know - I'm currently una...
[ "Leaving this up in case it helps anyone else but this is an issue with ~0.990 versions of mypy that is now resolved in the master branch with a patch coming out shortly.\nGithub issue: https://github.com/python/mypy/issues/14080\n" ]
[ 1 ]
[]
[]
[ "mypy", "pipenv", "python" ]
stackoverflow_0074420472_mypy_pipenv_python.txt
Q: Python: drop rows if condition is met I want to learn Python and have chosen a small private Football Data project for it. I have the following problem: I want to pull the data of the past 4 seasons. This works with the code below so far. But now I want to filter out the teams for each league, which were not in al...
Python: drop rows if condition is met
I want to learn Python and have chosen a small private Football Data project for it. I have the following problem: I want to pull the data of the past 4 seasons. This works with the code below so far. But now I want to filter out the teams for each league, which were not in all 4 seasons (the relegated teams should dis...
[ "Your code is almost ready. You only need to add a small for-loop filtering teams which played in more than one division:\nprint(df.shape)\n# (8264, 6)\nfor team in df.HomeTeam.unique():\n played_divs = df[df.HomeTeam==team].Div.unique()\n if len(played_divs) > 1:\n df = df[(df.HomeTeam != team)*(df.Aw...
[ 1 ]
[]
[]
[ "numpy", "pandas", "python" ]
stackoverflow_0074415963_numpy_pandas_python.txt
Q: Pandas: Not getting the desired transformation Name date leave marked_leave_bfr_days A 8/1/2021 1 3 A 8/2/2021 1 4 A 8/3/2021 1 5 A 8/4/2021 1 5 A 8/5/2021 ...
Pandas: Not getting the desired transformation
Name date leave marked_leave_bfr_days A 8/1/2021 1 3 A 8/2/2021 1 4 A 8/3/2021 1 5 A 8/4/2021 1 5 A 8/5/2021 1 6 A 8/6/2021 ...
[ "Just add a helper column to indicate same date bulk:\ndf['leave_applied'] = (df['date'] - df['marked_leave_bfr_days'].map(lambda x: pd.Timedelta(days=x))).dt.date\n\n# create helper\ndf['hlp_idx'] = (df.leave_applied != df.leave_applied.shift()).cumsum()\n\n# use helper column to create proper date groups \ndate_g...
[ 3, 1, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074383775_pandas_python.txt
Q: calling functions from array but each function wants different value similar topics have been opened, but I couldn't find exactly what I wanted and couldn't solve it myself. What I want is to call my functions from an array in a loop, but the values ​​that each function needs are different. Sending all values ​​to...
calling functions from array but each function wants different value
similar topics have been opened, but I couldn't find exactly what I wanted and couldn't solve it myself. What I want is to call my functions from an array in a loop, but the values ​​that each function needs are different. Sending all values ​​to all functions (they won't use what they don't need after all) or coding a...
[ "According to the comments, your actual situation is more complex.\nAssuming you have a_func taking one argument, b_func taking two arguments, and you have three variables a, b, c to main. You want to pass a to a_func, and b, c to b_func. I think you need to group arguments by functions before passing them to main,...
[ 2, 1, 1, 1 ]
[]
[]
[ "arrays", "python" ]
stackoverflow_0074420577_arrays_python.txt
Q: How to access parent class variables in child class? In the child class, how to access the parent class variable? In the child class method, I want to call the parent class variables. class Country: def __init__(self,name): self.name=name class City(Country): def __init__(self,city): super...
How to access parent class variables in child class?
In the child class, how to access the parent class variable? In the child class method, I want to call the parent class variables. class Country: def __init__(self,name): self.name=name class City(Country): def __init__(self,city): super().__init__() self.city=city def city...
[ "Since you are overriding the __init__ method of the parent class you need to pass all arguments for the super __init__ method\nclass Country:\n def __init__(self,name):\n self.name=name\n \n\n\nclass City(Country):\n def __init__(self, name, city):\n super().__init__(name)\n self....
[ 0 ]
[]
[]
[ "class", "inheritance", "python" ]
stackoverflow_0074420708_class_inheritance_python.txt
Q: Aligning entries/buttons with tkinter I've been trying to align the entries and buttons on this password manager I built for a while now but haven't been able to find a solution that works. I tried changing the width, columnspan, and coordinates but it doesn't seem to work. I want the password entry to be aligned ...
Aligning entries/buttons with tkinter
I've been trying to align the entries and buttons on this password manager I built for a while now but haven't been able to find a solution that works. I tried changing the width, columnspan, and coordinates but it doesn't seem to work. I want the password entry to be aligned just like the other two but with a lower wi...
[ "Grid\nWhen using grid to setup your widgets, the entire window is divided into individual cells based on the number of columns and rows you've specified. Although you can control the individual sizes of widgets, the overall size it can take will be limited by your choice of column- and rowwidth, as well as column-...
[ 1, 0 ]
[]
[]
[ "alignment", "button", "python", "tkinter" ]
stackoverflow_0074418639_alignment_button_python_tkinter.txt
Q: FileNotFoundError: [Errno 2] No such file or directory: 'frame0.png' but actually has I have a similar problem to many post about the path problem but I cannot find any solution to fix my problem So first, I have a function where I create a directory which will store all extracted frames from video def extract_fra...
FileNotFoundError: [Errno 2] No such file or directory: 'frame0.png' but actually has
I have a similar problem to many post about the path problem but I cannot find any solution to fix my problem So first, I have a function where I create a directory which will store all extracted frames from video def extract_frame(video,folder): os.mkdir(folder) vidcap = cv2.VideoCapture(video) success,im...
[ "I see that you are trying to use f directly from loop variable. But this will be just a file name rather than a path to file. You might have to do os.abspath(f) to get a complete path to your file and then run the required operation on it.\nfor f in os.listdir(pathOut):\n file_path = os.path.abspath(os.path.joi...
[ 3, 0, 0 ]
[]
[]
[ "file_not_found", "python", "python_imaging_library" ]
stackoverflow_0052417927_file_not_found_python_python_imaging_library.txt
Q: Arithmetic Sequence equation in Python In today's task i've got to implement the below equation, but im struggling with the final output. This is what I've made so far: import math def f(x, y): return ((x + y) / x)**2 summary = 0 sumw = 0 for j in range(1, 5): sumw = 0 for k in range(1, 8): ...
Arithmetic Sequence equation in Python
In today's task i've got to implement the below equation, but im struggling with the final output. This is what I've made so far: import math def f(x, y): return ((x + y) / x)**2 summary = 0 sumw = 0 for j in range(1, 5): sumw = 0 for k in range(1, 8): sumw += f(j, k) summary += sumw print(s...
[ "In the code, the main problem is that the squared operator has to include the entire sum over the k indexes. This is the correction version:\nsummary = 2\nfor j in range(1, 5):\n sumw = 0\n for k in range(1, 8):\n sumw += (j+k)/j\n summary += sumw**2\nprint(summary)\n# 2130.777777777778\n\nAltenati...
[ 2 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074420775_python_python_3.x.txt
Q: Access memory address in python My question is: How can I read the content of a memory address in python? example: ptr = id(7) I want to read the content of memory pointed by ptr. Thanks. A: Have a look at ctypes.string_at. Here's an example. It dumps the raw data structure of a CPython integer. from ctypes im...
Access memory address in python
My question is: How can I read the content of a memory address in python? example: ptr = id(7) I want to read the content of memory pointed by ptr. Thanks.
[ "Have a look at ctypes.string_at. Here's an example. It dumps the raw data structure of a CPython integer.\nfrom ctypes import string_at\nfrom sys import getsizeof\n\na = 0x7fff \nprint(string_at(id(a),getsizeof(a)).hex())\n\nOutput:\n0200000000000000d00fbeaafe7f00000100000000000000ff7f0000\n\nNote that this work...
[ 52, 10, 6, 1, 1, 0 ]
[]
[]
[ "ctypes", "memory", "memory_address", "python" ]
stackoverflow_0008250625_ctypes_memory_memory_address_python.txt
Q: A Classifier Network Seems to be "Forgetting" older samples This is a strange problem: Imagine a neural network classifier. It is a simple linear layer followed by a sigmoid activation that has an input size of 64, and an output size of 112. There also are 112 training samples, where I expect the output to be a on...
A Classifier Network Seems to be "Forgetting" older samples
This is a strange problem: Imagine a neural network classifier. It is a simple linear layer followed by a sigmoid activation that has an input size of 64, and an output size of 112. There also are 112 training samples, where I expect the output to be a one-hot vector. So the basic structure of a training loop is as fol...
[ "So this is very embarrassing, but the answer actually lies in how I process my data. This is a text-input project, so I used basic python lists to create blocks of messages, but when I did this, I ended up making it so that all of the inputs the net got were the same, but the output was different every time. I sol...
[ -1 ]
[]
[]
[ "machine_learning", "python", "pytorch" ]
stackoverflow_0074394144_machine_learning_python_pytorch.txt
Q: Passthrough is not supported, GL is disabled I tried crawling a specific site using selenium and webdriver_manager.chrome, and my code crawled elements of that site totally. But after crawling, the following error message appears in the console window. ERROR:gpu_init.cc(426) Passthrough is not supported, GL is dis...
Passthrough is not supported, GL is disabled
I tried crawling a specific site using selenium and webdriver_manager.chrome, and my code crawled elements of that site totally. But after crawling, the following error message appears in the console window. ERROR:gpu_init.cc(426) Passthrough is not supported, GL is disabled When I first found it, I unchecked Hardware ...
[ "Tested environment\nWindows OS, Chromedriver vesion 89, headless mode\nSolution\nI am not certain that this can be a solution for your question, since the error message is slightly different.\nAs I remember correctly, the error message Passthrough is not supported, GL is swiftshader has been shown after the Chrome...
[ 31, 16, 1, 1, 0 ]
[]
[]
[ "python", "selenium", "selenium_chromedriver", "selenium_webdriver" ]
stackoverflow_0067501093_python_selenium_selenium_chromedriver_selenium_webdriver.txt
Q: Passthrough is not supported, GL is swiftshader, ANGLE is When trying to run headless chrome with selenium I am getting this error: [1021/151706.155:ERROR:gpu_init.cc(453)] Passthrough is not supported, GL is swiftshader, ANGLE is my setup code: from selenium import webdriver import chromedriver_binary chrome_opt...
Passthrough is not supported, GL is swiftshader, ANGLE is
When trying to run headless chrome with selenium I am getting this error: [1021/151706.155:ERROR:gpu_init.cc(453)] Passthrough is not supported, GL is swiftshader, ANGLE is my setup code: from selenium import webdriver import chromedriver_binary chrome_options = webdriver.ChromeOptions() chrome_options.add_argument("-...
[ "I was getting the same error/warning message, but chromium was running just fine for me. I managed to get rid of this message by adding this option to the command line:\n--disable-features=DefaultPassthroughCommandDecoder\n\n" ]
[ 0 ]
[]
[]
[ "chrome_web_driver", "python", "selenium", "selenium_webdriver", "web_scraping" ]
stackoverflow_0069663948_chrome_web_driver_python_selenium_selenium_webdriver_web_scraping.txt
Q: Changing the word of a number to digit I have a series with the following kind of data: I have extracted this smaller subset from a column containing a much larger string. I want to convert wherever the word of a number is displayed to digit, for example: "two" should become 2. I've tried using the following code...
Changing the word of a number to digit
I have a series with the following kind of data: I have extracted this smaller subset from a column containing a much larger string. I want to convert wherever the word of a number is displayed to digit, for example: "two" should become 2. I've tried using the following code: help_dict = { 'one': '1', 'two': '...
[ "If you are running that line of code then you need to either use inplace=True or, overwrite the pandas Series for the changes to affect the former variable:\nyears_of_exp = years_of_exp.replace(help_dict,regex=True)\n\nOr, but don't use them exclusively:\nyears_of_exp.replace(help_dict,regex=True,inplace=True)\n\n...
[ 1 ]
[]
[]
[ "pandas", "python", "replace" ]
stackoverflow_0074420880_pandas_python_replace.txt
Q: Split links inside a list of values of a Python dictionary I have a dictionary like this: dict = { key1: <http://www.link1.org/abc/f><http://www.anotherlink.com/ght/y2>, key2: <http://www.link1.org/abc/f><http://www.anotherOneLink.en/ttta/6jk>, key3: <http://www.somenewlink.xxw/o192/ggh><http://www.lin...
Split links inside a list of values of a Python dictionary
I have a dictionary like this: dict = { key1: <http://www.link1.org/abc/f><http://www.anotherlink.com/ght/y2>, key2: <http://www.link1.org/abc/f><http://www.anotherOneLink.en/ttta/6jk>, key3: <http://www.somenewlink.xxw/o192/ggh><http://www.link4.com/jklu/wepdo9>, key4: <http://www.linkkk33.com/fgkjc><h...
[ "I tried your code but it didn't work on my side, so I changed it as follows :\ndict = {\n 'key1' : \"<http://www.link1.org/abc/f><http://www.anotherlink.com/ght/y2>\",\n 'key2': \"<http://www.link1.org/abc/f><http://www.anotherOneLink.en/ttta/6jk>\",\n 'key3' : \"<http://www.somenewlink.xxw/o192/ggh><http...
[ 0 ]
[]
[]
[ "dictionary", "key_value", "list", "python", "python_3.x" ]
stackoverflow_0074420691_dictionary_key_value_list_python_python_3.x.txt
Q: How can i return more then one string at once? i'm new to python and programming at all Was trying to make a code to give me all the factors of a number, but can't see where i'm lacking def divisores(numero): divisor = 0 while divisor < numero : divisor += 1 if numero % divisor == 0: return(divis...
How can i return more then one string at once?
i'm new to python and programming at all Was trying to make a code to give me all the factors of a number, but can't see where i'm lacking def divisores(numero): divisor = 0 while divisor < numero : divisor += 1 if numero % divisor == 0: return(divisor) divisores(50) all it shows is "1", that is ...
[ "Return a list:\ndef divisores(numero):\n divisor = 0\n divs = [] # empty list\n while divisor <= numero :\n divisor += 1\n if numero % divisor == 0:\n divs.append(divisor)\n return divs\n\nAlso, since you are counting 1 as an divisor, you likely want numero counting as a valid divisor as well. Hence...
[ 1, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074418687_python_python_3.x.txt
Q: How to import pandas and matplotlib on Python 3.5 IDLE I am running the following code: import pandas as pd import matplotlib.pyplot as plt from matplotlib import style style.use('ggplot') web_stats = {"Day":[1,2,3,4,5,6], "Visitors":[43,53,34,45,64,34], "Bounce_Rate":[65,72,62,64,54,66]} ...
How to import pandas and matplotlib on Python 3.5 IDLE
I am running the following code: import pandas as pd import matplotlib.pyplot as plt from matplotlib import style style.use('ggplot') web_stats = {"Day":[1,2,3,4,5,6], "Visitors":[43,53,34,45,64,34], "Bounce_Rate":[65,72,62,64,54,66]} df = pd.DataFrame(web_stats) print(df) It works just fine f...
[ "Have you actually installed pandas and matplotlib? \nYour best bet would be to install Anaconda, which automatically installs some useful Python libraries for you.\nIf you don't want to install so many unnecessary libraries, you can install pandas via pip: pip install pandas, and matplotlib by pip install matplotl...
[ 2, 2, 2, 0, 0 ]
[ "import os\ntry:\n import Pandas as pd\nexcept ImportError as e:\n e = str(e)[15:]\n e = e.strip().replace(\"'\", \"\")\n os.system('py -m pip install %s' % (e))\n\nTry above code. In window cmd you have to type py and they python code or module to run it from cmd.\n", "from matplotlib import pyplo...
[ -1, -1, -1, -1 ]
[ "matplotlib", "python", "python_idle" ]
stackoverflow_0045450464_matplotlib_python_python_idle.txt
Q: How to randomly choose and deploy between 3 types of rectangles in pygame I am trying to make a game in python. It is pretty much the same as the chrome dinosaur game but I have used rectangles instead of the cactus I have managed to make the player be able to jump and the enemy blocks to move in. There are three ...
How to randomly choose and deploy between 3 types of rectangles in pygame
I am trying to make a game in python. It is pretty much the same as the chrome dinosaur game but I have used rectangles instead of the cactus I have managed to make the player be able to jump and the enemy blocks to move in. There are three types of enemy blocks, normal, long and flying I want a function so that it cho...
[ "As I see it, you don't seem to be actually calling random.choice(self.enemy_list) anywhere in your code except the class constructor.\nTo fix this you could update the def random_enemy(self): function to include a randomised enemy, something like this:\n def random_enemy(self):\n if self.deploy == True:\...
[ 0 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0074420802_pygame_python.txt
Q: Sending a Jinja2 templated email doesn't use new lines My script accepts a variable from a Zabbix trigger (alert media). I'm trying to send that variable as an email but I don't see new lines in the email. The original output has ^M at the end of each line, so I replace them with /n and then send that to be render...
Sending a Jinja2 templated email doesn't use new lines
My script accepts a variable from a Zabbix trigger (alert media). I'm trying to send that variable as an email but I don't see new lines in the email. The original output has ^M at the end of each line, so I replace them with /n and then send that to be rendered in my Jinja2 template: alert_message = sys.argv[1] # This...
[ "Just wanted to post an update. Not sure if this will help anyone since this is a pretty janky solution, but overall:\nI get the message from Zabbix, parse it in my script, and send it in a templated email using Jinja.\nThe fuction:\ndef parseMessage(message):\n d = {}\n for line in message.splitlines():\n ...
[ 0 ]
[]
[]
[ "jinja2", "python", "zabbix" ]
stackoverflow_0073302427_jinja2_python_zabbix.txt
Q: How to get the start time, end time in seconds from YouTube timestamp using python? I'm having a list of timestamps of a YouTube video. Example: timestamps = ['0:02-0:35', '0:50-1:18', '2:53-3:08', '3:12-3:14', '3:16-3:22', '3:25-3:28', '1:09-1:35', '1:38-1:48', '2:04-2:14', '2:30-2:40', '2:45-2:50', '3:35-4:07', ...
How to get the start time, end time in seconds from YouTube timestamp using python?
I'm having a list of timestamps of a YouTube video. Example: timestamps = ['0:02-0:35', '0:50-1:18', '2:53-3:08', '3:12-3:14', '3:16-3:22', '3:25-3:28', '1:09-1:35', '1:38-1:48', '2:04-2:14', '2:30-2:40', '2:45-2:50', '3:35-4:07', '4:16-4:22', '4:48-4:54', '5:00-5:12', '5:34-5:54', '8:58-9:19', ''] Now I need to fetch...
[ "You can do it with regex, capturing the minutes (\\d{1,2}) and seconds(\\d{2}) from the source string.\nimport re\ninterval = '0:02-0:35'\nstart_min, start_sec, end_min, end_sec = map(int, re.findall('\\d{1,2}', interval))\n\nor split time by : and - via re.split.\nstart_min, start_sec, end_min, end_sec = map(int,...
[ 1 ]
[]
[]
[ "date", "extract", "python", "python_3.x" ]
stackoverflow_0074420822_date_extract_python_python_3.x.txt
Q: Python `ModuleNotFoundError` two dirs with same name My python sys.path looks like this (only the first 2 paths are of interest): (Pdb) pp sys.path ['/home/michael/project/src/dist', '/home/michael/project/src/core', '/home/michael/project/src', '/usr/lib/python39.zip', '/usr/lib/python3.9', '/usr/lib/python3...
Python `ModuleNotFoundError` two dirs with same name
My python sys.path looks like this (only the first 2 paths are of interest): (Pdb) pp sys.path ['/home/michael/project/src/dist', '/home/michael/project/src/core', '/home/michael/project/src', '/usr/lib/python39.zip', '/usr/lib/python3.9', '/usr/lib/python3.9/lib-dynload', '/home/michael/.venv/project/lib/python3...
[ "The solutions seems to be native-namespace-packages\nJust omit the __init__.py from both app dirs.\n" ]
[ 0 ]
[]
[]
[ "python", "python_3.x", "python_import", "python_importlib" ]
stackoverflow_0074420896_python_python_3.x_python_import_python_importlib.txt
Q: Multiprocessing issue in with python I am new to multiprocessing in python and have run into some issues with Pool: OS: Mac Monterey M1 chip Python 3.9.12 in module.py: I have tried def foo(x) ... return y pool = mp.Pool(8) results = pool.map_async(foo, args) also tried pathos: def foo(x) ... return y pool = Proc...
Multiprocessing issue in with python
I am new to multiprocessing in python and have run into some issues with Pool: OS: Mac Monterey M1 chip Python 3.9.12 in module.py: I have tried def foo(x) ... return y pool = mp.Pool(8) results = pool.map_async(foo, args) also tried pathos: def foo(x) ... return y pool = ProcessPool(8) results = pool.amap(foo, args) ...
[ "I'm the author of dill, pathos, and multiprocess. It looks like you have an object that won't serialize. Your question doesn't provide enough information for me to give you a solution that I know will work -- but I can give you some things to try.\n\nTry a different serialization variant in dill:\n\n Python 3....
[ 1 ]
[]
[]
[ "multiprocessing", "multithreading", "pathos", "python" ]
stackoverflow_0074416483_multiprocessing_multithreading_pathos_python.txt
Q: SettingWithCopyWarning even when using .loc[row_indexer,col_indexer] = value This is one of the lines in my code where I get the SettingWithCopyWarning: value1['Total Population']=value1['Total Population'].replace(to_replace='*', value=4) Which I then changed to : row_index= value1['Total Population']=='*' value...
SettingWithCopyWarning even when using .loc[row_indexer,col_indexer] = value
This is one of the lines in my code where I get the SettingWithCopyWarning: value1['Total Population']=value1['Total Population'].replace(to_replace='*', value=4) Which I then changed to : row_index= value1['Total Population']=='*' value1.loc[row_index,'Total Population'] = 4 This still gives the same warning. How do...
[ "If you use .loc[row, column] and still get the same error, it's probably because of copying another dataframe. You have to use .copy().\nThis is a step-by-step error reproduction:\nimport pandas as pd\n\nd = {'col1': [1, 2, 3, 4], 'col2': [3, 4, 5, 6]}\ndf = pd.DataFrame(data=d)\ndf\n# col1 col2\n#0 1 3\n#...
[ 38, 9, 2, 2, 1, 0, 0, 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0032573452_pandas_python.txt
Q: How to handle Pandas time series analysis, Daylight Savings time and conversion to other time zones I am pretty new to Panda's and am having trouble with Pandas/time series analysis and Daylight Savings time. I have a 1-minute frequency txt file with NY Daylight Savings Time data. When I use pytz to localize and c...
How to handle Pandas time series analysis, Daylight Savings time and conversion to other time zones
I am pretty new to Panda's and am having trouble with Pandas/time series analysis and Daylight Savings time. I have a 1-minute frequency txt file with NY Daylight Savings Time data. When I use pytz to localize and convert to UTC and then downsample to 2Hr, 4H, all data and times match for rows during DST, but do not ma...
[ "So if I understand correctly, the data is in Eastern Standard Time (GMT-5) without any daylight savings?\nThen the way I would solve it is to add 5:00:00 to the index across the board and then localise as UTC.\nix = df.index + pd.Timedelta(hours=5)\ndf_utc = df.set_index(ix).tz_localize(\"UTC\")\n\nYou can then tz...
[ 0 ]
[]
[]
[ "dataframe", "datetime", "dst", "pandas", "python" ]
stackoverflow_0074408211_dataframe_datetime_dst_pandas_python.txt
Q: By changing values in one array it automatically changes values in another array. How to avoid that happening? I have created a genetic algorithm to create children from parents. At the start of the algorithm a random workload(arrays of sub-arrays) is created. Workload L=2, population size N=30, InputsNumber=3 and...
By changing values in one array it automatically changes values in another array. How to avoid that happening?
I have created a genetic algorithm to create children from parents. At the start of the algorithm a random workload(arrays of sub-arrays) is created. Workload L=2, population size N=30, InputsNumber=3 and mutation rate m=0.05. Then I do some score calculations for the population to pick the 2 workloads(the parents) wit...
[ "Perhaps confusion of copy by address and by values ?\nDon't do direct affectation when working with arrays because they are linked.\n\"Using the copy() function is another way of copying an array in Python. In this case, a new array object is created from the original array and this type of copy is called deep cop...
[ 0, 0, 0 ]
[]
[]
[ "arrays", "python" ]
stackoverflow_0074420714_arrays_python.txt
Q: Parse html tables from emails to lists then convert to pandas dataframe I’m an absolute Beginner in Python , and I am trying to create a script which loops through an email folder and grabs a html table within the emails and convert to a pandas dataframe for export to excel. The code below loops through the folde...
Parse html tables from emails to lists then convert to pandas dataframe
I’m an absolute Beginner in Python , and I am trying to create a script which loops through an email folder and grabs a html table within the emails and convert to a pandas dataframe for export to excel. The code below loops through the folder and adds each table and its contents to a list [] # importing the libraries...
[ "If you had a list of dataframes (df) that looked like\n[ 0 1\n 0 Column1 Value1a\n 1 Column2 Value2a\n 2 Column3 Value3a\n 3 Column4 Value4a\n 4 Column5 Value5a\n 5 Column6 Value6a\n 6 Column7 Value7a\n 7 Column8 Value8a,\n 0 1\n 0 Column1 Value1b\n 1 Column2 Valu...
[ 1 ]
[]
[]
[ "beautifulsoup", "pandas", "python" ]
stackoverflow_0074407902_beautifulsoup_pandas_python.txt
Q: Issue with sorting in pandas column in ascending order I have the following code. I am trying to sort the values of the first column of the 'happydflist' dataframe in ascending order. However, the output this gives me includes some values such as '2','3' and '8' that do not fit in with the ascending order theme. h...
Issue with sorting in pandas column in ascending order
I have the following code. I am trying to sort the values of the first column of the 'happydflist' dataframe in ascending order. However, the output this gives me includes some values such as '2','3' and '8' that do not fit in with the ascending order theme. happydflist = happydflist[happydflist.columns[0]] happydflist...
[ "Maybe your dataframe's dtype of some is str so make that to int instead.\nhappydflist.astype('int').sort_values()\n\nif you need str dtype use astype 1more so:\nhappydflist.astype('int').sort_values().astype('str')\n\n", "I managed to resolve the issue by using the df.strip() function to remove 'white space' ar...
[ 0, 0 ]
[]
[]
[ "dataframe", "jupyter_notebook", "pandas", "python" ]
stackoverflow_0074420117_dataframe_jupyter_notebook_pandas_python.txt
Q: Implementation of Monte-Carlo method to find integration value in python I have found this code that can integrate a given function and give the answer using Monte-Carlo method. However, I wanted to implement it in python but I don't know how to make the "srand(time(Null))" and Rand_Max parts happen in python. Al...
Implementation of Monte-Carlo method to find integration value in python
I have found this code that can integrate a given function and give the answer using Monte-Carlo method. However, I wanted to implement it in python but I don't know how to make the "srand(time(Null))" and Rand_Max parts happen in python. Also I want to use the "func(x)" in such a way that I can input different functi...
[ "I think there is no default RAND_MAX equivalent in python so we will add a function calculating it.\nAnd for srand(time(None)) used in C++ it can be ignored in python.\nSo let's try the following code:\nimport math\nimport random\n\n\ndef func(x):\n return (1+math.cos(x))*math.sin(abs(2*x))/abs(1+math.sin(2 *x)...
[ 1 ]
[]
[]
[ "c++", "montecarlo", "python" ]
stackoverflow_0074401162_c++_montecarlo_python.txt
Q: find a way in python/pandas to cross information between couple of columns I have this database: id power_count power_name type second_power second_power_type 0 001 1 fire attack nan nan 1 001 1 fire attack nan nan 2 002 2 water ...
find a way in python/pandas to cross information between couple of columns
I have this database: id power_count power_name type second_power second_power_type 0 001 1 fire attack nan nan 1 001 1 fire attack nan nan 2 002 2 water defense nan nan 3 002 2 sand attack nan ...
[ "dict1 = {'water':'sand', 'sand':'water', 'defense':'attack', 'attack':'defense'}\ndf.loc[df['power_count'] == 2, ['second_power', 'second_power_type']] = df.loc[df['power_count'] == 2, ['power_name', 'type']].replace(dict1).to_numpy()\ndf\n\ndf\n id power_count power_name type second_power second_power_...
[ 0, 0 ]
[]
[]
[ "loops", "pandas", "python" ]
stackoverflow_0074419785_loops_pandas_python.txt
Q: Selenium Discord channel select last message I am trying select last message on discord channel with selenium I can't find xpath. xpath is changing every time for last message. I just want copy last message on the channel. Last message id changing. Please help me. This code is logging and goes rotate to chanel. im...
Selenium Discord channel select last message
I am trying select last message on discord channel with selenium I can't find xpath. xpath is changing every time for last message. I just want copy last message on the channel. Last message id changing. Please help me. This code is logging and goes rotate to chanel. import time from selenium import webdriver from se...
[ "You can use this xpath to find your element by xpath:\n//ol[@data-list-id=\"chat-messages\"]/li[last()]//div[contains(@class,'messageContent')]\n\nExplaining the xpath\n\n//ol[@data-list-id=\"chat-messages\"] --> An ol element with id chat-messages (Which is the list of messages)\n/li[last()] --> We get the last l...
[ 0 ]
[]
[]
[ "html", "python", "selenium" ]
stackoverflow_0074421153_html_python_selenium.txt
Q: Uppercase every other word in a string using split/join I have a string: string = "Hello World" That needs changing to: "hello WORLD" Using only split and join in Python. Any help? string = "Hello World" split_str = string.split() Can't then work out how to get first word to lowercase second word to upperca...
Uppercase every other word in a string using split/join
I have a string: string = "Hello World" That needs changing to: "hello WORLD" Using only split and join in Python. Any help? string = "Hello World" split_str = string.split() Can't then work out how to get first word to lowercase second word to uppercase and join
[ "OP's objective cannot be achieved just with split() and join(). Neither of those functions can be used to convert to upper- or lower-case.\nThe cycle class from the itertools module is ideal for this:\nfrom itertools import cycle\n\nwords = 'hello world'\n\nCYCLE = cycle((str.lower, str.upper))\n\nprint(*(next(CYC...
[ 2, -1 ]
[ "for many words:\nmake a list of words using split\nconnect everything with \" \" using join\ninside we run through the list using i up to the length of this list\nif this is an odd number, then upper otherwise lower (because the list is numbered from 0, and we need every second one)\nstring = \"Hello World! It is ...
[ -1 ]
[ "join", "lowercase", "python", "split", "uppercase" ]
stackoverflow_0074420927_join_lowercase_python_split_uppercase.txt
Q: How to steps differences reduce in Hadoop? How to steps differences reduce in Hadoop? I have a problem with understand Hadoop. I have two files and first I did a join between those files. One file is about countries and the other is about client in each country. Example, clients.csv: Bertram Pearcy ,bueno,SO Stev...
How to steps differences reduce in Hadoop?
How to steps differences reduce in Hadoop? I have a problem with understand Hadoop. I have two files and first I did a join between those files. One file is about countries and the other is about client in each country. Example, clients.csv: Bertram Pearcy ,bueno,SO Steven Ulman ,regular,ZA Countries.csv Name,Code ...
[ "Your reducer is getting 3 distinct keys, therefore you're finding the max of each, and values only has one element (try printing its length... ). Therefore, you get 3 results.\nYou need a third mapper that returns (None, f'{key}|{value}) for example, then all records will be sent to one reducer, where you can then...
[ 0 ]
[]
[]
[ "hadoop", "mapreduce", "mrjob", "python" ]
stackoverflow_0074415367_hadoop_mapreduce_mrjob_python.txt
Q: How to format dictionary with pprint library? I have this function: def total_fruit_per_sort(): number_found = re.findall(total_amount_fruit_regex(), verdi50) fruit_dict = {} for n, f in number_found: fruit_dict[f] = fruit_dict.get(f, 0) + int(n) return pprint.pprint(str( {valu...
How to format dictionary with pprint library?
I have this function: def total_fruit_per_sort(): number_found = re.findall(total_amount_fruit_regex(), verdi50) fruit_dict = {} for n, f in number_found: fruit_dict[f] = fruit_dict.get(f, 0) + int(n) return pprint.pprint(str( {value: key for value, key in fruit_dict.items() }).repl...
[ "You don't need pprint for this\nresult = '\\n'.join(f'{key}: {val}' for key, val in your_dict.items())\n\n", "In some ways, the issue is that you are passing a string to pprint which has already been formatted.\nMaybe add .replace(',' , '\\n') at the end of the string before printing?\n\nUsing pprint, I think th...
[ 2, 1 ]
[]
[]
[ "pprint", "python" ]
stackoverflow_0074421189_pprint_python.txt
Q: Convert List of numbers as string to a single Integer I'm trying to convert a list to a single integer using two methods: for loop works fine and gives me the integer >>> a_list = "123456789" >>> a_list = list(a_list) >>> b_int = "" >>> for num in a_list: ... b_int += num ... >>> print(int(b_int)) 1234567...
Convert List of numbers as string to a single Integer
I'm trying to convert a list to a single integer using two methods: for loop works fine and gives me the integer >>> a_list = "123456789" >>> a_list = list(a_list) >>> b_int = "" >>> for num in a_list: ... b_int += num ... >>> print(int(b_int)) 123456789 however join() returns a ValueError >>> a_list = "12345...
[ "The origin of the ValueError is that you are calling int to an empty string and not to the join one. String are immutables so you need always to re-assign the result.\na_list = \"123456789\"\nc_int = \"\"\nc_int = c_int.join(a_list) # <- \n\nprint(int(c_int)) \n\nBy the way int(a_list) does the same.\n", "As the...
[ 1, 0 ]
[]
[]
[ "concatenation", "for_loop", "join", "python" ]
stackoverflow_0074421230_concatenation_for_loop_join_python.txt
Q: Have problems with uploading files using selenium I'm trying to upload a CSV file to this website: https://maalaei97-test3.hf.space/?__theme=light using selenium. I tried to find elements by XPath and Partial_link_text but none of them worked. Here is the code I used: from selenium import webdriver from selenium.w...
Have problems with uploading files using selenium
I'm trying to upload a CSV file to this website: https://maalaei97-test3.hf.space/?__theme=light using selenium. I tried to find elements by XPath and Partial_link_text but none of them worked. Here is the code I used: from selenium import webdriver from selenium.webdriver.common.by import By driver = webdriver.Chrome...
[ "You need to wait for page to be loaded before trying uploading the file.\nThe best approach to do so is to use WebDriverWait expected_conditions explicit waits.\nThe following code worked properly for me:\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdrive...
[ 1, 0, 0 ]
[]
[]
[ "file_upload", "python", "selenium", "selenium_webdriver", "web_scraping" ]
stackoverflow_0074420379_file_upload_python_selenium_selenium_webdriver_web_scraping.txt
Q: How to create django project I’m not sure what commands should I write in CMD to create a Python django project. When I write django-admin startproject myproject, it does not create a config folder in my project. What am I missing? A: Try using "$ django-admin startproject myproject", the myproject should be th...
How to create django project
I’m not sure what commands should I write in CMD to create a Python django project. When I write django-admin startproject myproject, it does not create a config folder in my project. What am I missing?
[ "Try using \"$ django-admin startproject myproject\", the myproject should be the folder that contains your project.\nIf that doesn't work try checking this website: https://www.tutorialspoint.com/django/django_creating_project.htm\nAnd follow the steps.\n" ]
[ 0 ]
[]
[]
[ "cmd", "django", "python" ]
stackoverflow_0074421234_cmd_django_python.txt
Q: python numba: using nopython for a function receiving a function as argument Trying to use numba to jit my code using the nopython=True flag, I get an error for functions which receive a function as argument: import numba import numpy as np x = np.random.randn(10,10) f = lambda x : (x>0)*x @numba.jit...
python numba: using nopython for a function receiving a function as argument
Trying to use numba to jit my code using the nopython=True flag, I get an error for functions which receive a function as argument: import numba import numpy as np x = np.random.randn(10,10) f = lambda x : (x>0)*x @numba.jit(nopython=True) def a(x,f): return f(x)**2+x a(x,f) The error message received i...
[ "You cannot provide a pure-Python function which is not compiled with Numba to a Numba code executing it in nopython mode. If you really want to do that, you need to use the objmode switch which is experimental and inefficient (so it is not very useful except in very few special cases). The typical solution is simp...
[ 1 ]
[]
[]
[ "jit", "numba", "python" ]
stackoverflow_0074415978_jit_numba_python.txt
Q: How do I combine two dataframes on two columns? I have two df's: one has a date in the first column: all dates of the last three years and the second column are names of participants, other columns are information. In the second df, I have some dates on which we did tests in the first column, then second column th...
How do I combine two dataframes on two columns?
I have two df's: one has a date in the first column: all dates of the last three years and the second column are names of participants, other columns are information. In the second df, I have some dates on which we did tests in the first column, then second column the names again and more columns information. I would l...
[ "Please, I would be nice if you can provide and example. I would try this.\nimport pandas as pd\nnew_df = pd.merge(data,names_participants, on = ['Date'], how = 'left')\n\nI would validate if everything is right regarding the date format as well.\n", "With Python and Pandas, you can join on 2 variables by using s...
[ 0, 0, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074421250_dataframe_pandas_python.txt
Q: Turn upper case to lowercase, lowercase to upper, add +5 to all numbers modulo 10 I need to turn uppercase to lowercase, lowercase to uppercase and I need to add each number +5 modulo 10. It doesn't work so could you please help me? The sentence is "Hello World, 521" and the output should be "hELLO wORLD, 076". I ...
Turn upper case to lowercase, lowercase to upper, add +5 to all numbers modulo 10
I need to turn uppercase to lowercase, lowercase to uppercase and I need to add each number +5 modulo 10. It doesn't work so could you please help me? The sentence is "Hello World, 521" and the output should be "hELLO wORLD, 076". I need to use a function definition. I tried this: def fc1 (string): if string.upper ...
[ "use str.swapcase\n''.join(str((int(i)+5)%10) if i.isdigit() else i.swapcase() for i in 'hello world 521')\n\n", "So I decided to do this a little bit differently. I used \"Hello World, 521\", but in Czech, because I need it in Czech. I can't use i.swapcase because I didn't learn it yet.\n def fce1 (string):\n...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074389599_python.txt
Q: Python - Date and Time: AttributeError: 'module' object has no attribute 'month' This is my calendar code in Python and I have saved it to my folder as calendar.py. import calendar a = calendar.month(2016, 3) print (a) print ("The Calendar :") When I execute it, it raises an error : Traceback (most recent call la...
Python - Date and Time: AttributeError: 'module' object has no attribute 'month'
This is my calendar code in Python and I have saved it to my folder as calendar.py. import calendar a = calendar.month(2016, 3) print (a) print ("The Calendar :") When I execute it, it raises an error : Traceback (most recent call last): File "calendar.py", line 1, in <module> import calendar File "/opt/lampp/...
[ "The problem is that you used the name calendar.py for your file. Use any other name, and you will be able to import the python module calendar.\n", "Do not name the file as calendar.py and there should be no calendar.py file on the same path\n", "You might have given your file name as calendar.py. This is impo...
[ 10, 2, 1, 0, 0, 0, 0 ]
[]
[]
[ "date", "python" ]
stackoverflow_0035769871_date_python.txt
Q: Change a tuple within a list of tuples I am reading in data from multiple Excel files and writing them back to an aggregated Excel file. So I have this output, and it represents the relations of multiple entities within my company (enity-ID) with other companies (debitor-name): debitor_list = [ ("1", "X AG"), ...
Change a tuple within a list of tuples
I am reading in data from multiple Excel files and writing them back to an aggregated Excel file. So I have this output, and it represents the relations of multiple entities within my company (enity-ID) with other companies (debitor-name): debitor_list = [ ("1", "X AG"), ("1", "X AG"), ("1", "Z AG"), ("...
[ "Either you replace the whole list, or you replace the element in place with some simple logic, see the 2 options below.\nNote that tuples might be immutable, but the list itself is not...\nimport difflib as dif\n\ndebitor_list = [\n (\"1\", \"X AG\"),\n (\"1\", \"X AG\"),\n (\"1\", \"Z AG\"),\n (\"2\",...
[ 0 ]
[]
[]
[ "list", "python", "similarity", "string", "tuples" ]
stackoverflow_0074420904_list_python_similarity_string_tuples.txt
Q: Update imported variable from another file using function first.py: from third import * from second import * while running: off() second.py: from third import * def off(): running = False third.py: running = True The program still running and running variable is not accessed. I want to calling a funct...
Update imported variable from another file using function
first.py: from third import * from second import * while running: off() second.py: from third import * def off(): running = False third.py: running = True The program still running and running variable is not accessed. I want to calling a function which is in another file, the function change the boolean w...
[ "Your line: running = False doesn't do what you want it to do.\nThe key to remember with python is that imports create new variables in the module that does the import. This means for variables declared in another module, your module gets a new variable of the same name. The second thing to note is that assignment ...
[ 1, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074421199_python_python_3.x.txt
Q: Weighted resampling a numpy array I have a 50 x 4 numpy array and I'd like to repeat the rows to make it a 500 x 4 array. But the catch is, I cannot just repeat the rows along 0th axis. I'd like to have more smaller rows and lesser bigger rows in the expanded array. The input array has data that looks like this: [...
Weighted resampling a numpy array
I have a 50 x 4 numpy array and I'd like to repeat the rows to make it a 500 x 4 array. But the catch is, I cannot just repeat the rows along 0th axis. I'd like to have more smaller rows and lesser bigger rows in the expanded array. The input array has data that looks like this: [1, 1, 16, 5] [8, 10, 512, 10] ... [448,...
[ "You can using np.repeat so to repeat an arbitrary number of time a givent value in an array and then use that as an index for the input array (since np.repeat do not work directly on 2D arrays). Here is an example:\n# Example of random input\ninputArr = np.random.randint(0, 1000, (50, 4))\n\n# Example with [2, 3, ...
[ 1 ]
[]
[]
[ "arrays", "list", "numpy", "python", "repeat" ]
stackoverflow_0074410452_arrays_list_numpy_python_repeat.txt
Q: How to generate prime twins using python with basics? I need to generate prime twins in python but I can only use basics (if, elif, else, for, print. I cannot use while, def, return or break etc. I wrote this code but it only works under 100, If I want a range up to 1000 it doesn't work and I have no idea how to d...
How to generate prime twins using python with basics?
I need to generate prime twins in python but I can only use basics (if, elif, else, for, print. I cannot use while, def, return or break etc. I wrote this code but it only works under 100, If I want a range up to 1000 it doesn't work and I have no idea how to do it without putting there hundreds ifs'. Could you please ...
[ "Here you have an example implementation.\nFirst calculates all prime numbers under N using the sieve of Eratosthenes, and then it finds twin primes. It's probably not the most efficient implementation by I think is good enough for educational purposes.\nN = 1000\n\n##\n# Find primes using the sieve of Eratosthenes...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074219998_python.txt
Q: How to run multiple functions in prallel on same argument. Prettly much Pool but with multiple functions and one argument I have a few algorithms which I want to run in parallel. I need their return value and can not modify the functions themself. That made it hard to use from multiprocessing import Process becaus...
How to run multiple functions in prallel on same argument. Prettly much Pool but with multiple functions and one argument
I have a few algorithms which I want to run in parallel. I need their return value and can not modify the functions themself. That made it hard to use from multiprocessing import Process because that why I do not how to get the return value if I can not pass the function a pipe to work with or similar. Then I tried usi...
[ "I am assuming the error results from using a non-global function (because of your wrapper) on a platform that uses spawn to create new processes, such as Windows.\nBut your question is somewhat vague and I am not sure why you need a wrapper. Let's suppose you have 3 algorithms that take an int and return an int. T...
[ 0 ]
[]
[]
[ "multiprocessing", "python", "python_multiprocessing" ]
stackoverflow_0074412664_multiprocessing_python_python_multiprocessing.txt
Q: How can I test my function before storing my input into a database or json file? Perhaps someone here can help me. I am trying to create a habit-tracking app as a project and I have created a habit class along with a habit creation function that I defined. Eventually, I want to be able to use a sqlite database to ...
How can I test my function before storing my input into a database or json file?
Perhaps someone here can help me. I am trying to create a habit-tracking app as a project and I have created a habit class along with a habit creation function that I defined. Eventually, I want to be able to use a sqlite database to hold my data. I have not coded the database functionality yet, but I wanted to test my...
[ "The method, is an instance method, how could the code know initiate_habit is related to habit if you don't tell it\nShoule be\nhabit = Habit('Read', 'Read 15 pages daily')\nhabit.initiate_habit()\n\n" ]
[ 1 ]
[]
[]
[ "function", "python" ]
stackoverflow_0074421350_function_python.txt
Q: How to replace setup.py with a pyproject.toml for a native C build dependency? I came across this little project for creating a C-compiled version of the Black-Scholes function to be used in python. Although the example code seem to have been published in July this year, it seem that the use setup.py type of build...
How to replace setup.py with a pyproject.toml for a native C build dependency?
I came across this little project for creating a C-compiled version of the Black-Scholes function to be used in python. Although the example code seem to have been published in July this year, it seem that the use setup.py type of build has been deprecated beyond legacy builds. Any compilation fails, first complaining ...
[ "After having wasted 2 days on trying to circumvent the required Visual Studio C++ Build tools requirements, the only unfortunate option that would work, was to submit to the >7GB download in order to get my 20 line C-function to compile and install nicely on Py3.10. (Follow this.)\nUsing an external _custom_build....
[ 0 ]
[]
[]
[ "compilation", "pyproject.toml", "python", "setup.py" ]
stackoverflow_0074409966_compilation_pyproject.toml_python_setup.py.txt
Q: How to generate a string consisting of 16 digits but between every 4 numbers there is a hyphen(-)? What kind of technique would allow me to generate a string in Python similar to this output: 1234-1234-1234-1234 A: Python has a built in wrap function, made to split strings like this. In conjunction with string.j...
How to generate a string consisting of 16 digits but between every 4 numbers there is a hyphen(-)?
What kind of technique would allow me to generate a string in Python similar to this output: 1234-1234-1234-1234
[ "Python has a built in wrap function, made to split strings like this. In conjunction with string.join, you can rejoin the split string with your character of choice:\nfrom textwrap import wrap\n\ns = '1234567890abcdef'\nprint('-'.join(wrap(s, 4)))\n>>> 1234-5678-90ab-cdef\n\nThe wrap function takes your string, an...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074421373_python.txt
Q: Python help needed: how do I produce output from 2 txt files I have 2 simple .txt files. One file contains a person's name and pay. The second file contains a person's name and job title. Data from first file... John Doe $750.00 Jane Doe $450.00 Sammy Joe $350.00 Data from second file... John Doe (Sto...
Python help needed: how do I produce output from 2 txt files
I have 2 simple .txt files. One file contains a person's name and pay. The second file contains a person's name and job title. Data from first file... John Doe $750.00 Jane Doe $450.00 Sammy Joe $350.00 Data from second file... John Doe (Store Manager) Jane Doe (Asst Store Mngr) Sammy Joe (Shift Manag...
[ "filename = str(input(\"File Name : \")\nfile = open(f\"{filename}.txt\", \"w\")\nfilewrite = str(input(\"Write Content : \")\nfile.write(filewrite)\nsorry but i dont know int print its just str\n", "We could use the pd.merge function here I think\nimport pandas as pd\nfile_name_pay = pd.read_fwf('file1.txt')\nfi...
[ 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074421292_python.txt
Q: Why does this specific piece of code using random.random run slower in Python 3.11 than in Python 3.10.6? I'm just curious to hear other people's thoughts on why this specific piece of code might might run slower in Python 3.11 than in Python 3.10.6. Cross-posted from here. I'm new here - please kindly let me know...
Why does this specific piece of code using random.random run slower in Python 3.11 than in Python 3.10.6?
I'm just curious to hear other people's thoughts on why this specific piece of code might might run slower in Python 3.11 than in Python 3.10.6. Cross-posted from here. I'm new here - please kindly let me know if I'm doing something wrong. test.py script: import timeit from random import random def run(): for i i...
[ "This looks like it's probably the PEP 659 optimizations not paying off for random.random.\nPEP 659 is an effort to JIT-optimize many common operations. (Not JIT compilation, but definitely JIT optimization.) It pays off for most Python code, but I think random.random isn't covered.\nrandom.random is a method (of a...
[ 7 ]
[]
[]
[ "performance", "python", "python_3.10", "python_3.11" ]
stackoverflow_0074421106_performance_python_python_3.10_python_3.11.txt
Q: Pywebio Button to redirect to another url I want a button in my pywebio,which on click will redirect to localhost//:4200 . My pywebio runs in localhost:8080, i want to redirect it to a page in port:4200 A: To keep it simple, not much documentation for on click. But it looks for a function import webbrowser def ...
Pywebio Button to redirect to another url
I want a button in my pywebio,which on click will redirect to localhost//:4200 . My pywebio runs in localhost:8080, i want to redirect it to a page in port:4200
[ "To keep it simple, not much documentation for on click. But it looks for a function\nimport webbrowser\n\ndef my_function():\n webbrowser.open_new_tab('Your_URL')\n \nput_button(\"Button\", onclick=lambda: my_function())\n\n" ]
[ 0 ]
[]
[]
[ "button", "flask", "python", "redirect" ]
stackoverflow_0072740161_button_flask_python_redirect.txt
Q: Equivalent python for curl command I am new to Curl package and trying to find the equivalent python code for below curl commands: $cves holds the list of cves and I am trying to GET the search result from api for cve in $cves do score=$(curl https://www.cvedetails.com/cve/$cve 2>&1 | grep "cvssbox" | tr "</d...
Equivalent python for curl command
I am new to Curl package and trying to find the equivalent python code for below curl commands: $cves holds the list of cves and I am trying to GET the search result from api for cve in $cves do score=$(curl https://www.cvedetails.com/cve/$cve 2>&1 | grep "cvssbox" | tr "</div></td>" " "| rev | cut -b12-15 | rev) ...
[ "A solution that takes a list of CVEs and creates a dictionary that maps\neach CVE id to its severity score.\nimport requests\n\nbaseurl = \"https://www.cvedetails.com/cve\"\n\nbaron_samedit = \"CVE-2021-3156\"\ncves = [baron_samedit, \"CVE-2021-20612\", \"CVE-2021-39979\"] # for the sake of the example\n\nscores:...
[ 1 ]
[]
[]
[ "curl", "python" ]
stackoverflow_0074414924_curl_python.txt
Q: Why is one part of the code assuming that the list was expanded, while the other doesn't? I need to read the input from a .txt file and output to another. The 'create' command given by the user adds a patient to the list, and the 'remove' is supposed to delete them if such character exists. The 'list' function out...
Why is one part of the code assuming that the list was expanded, while the other doesn't?
I need to read the input from a .txt file and output to another. The 'create' command given by the user adds a patient to the list, and the 'remove' is supposed to delete them if such character exists. The 'list' function outputs all the characters saved. The issue is that the remove function always gives the result 'P...
[ "You are appending one array to the frameList but then you are trying to find a different array which has almost the same values.\nFor example: you are adding an array like this: [\"create\", \"Marcus\", ...]\nThen you are trying to find in frameList something like [\"remove\", \"Marcus\", ...].\nYou could try to a...
[ 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074421380_python_python_3.x.txt
Q: Pandas use time_between with apply lambda I need to create 3 new boolean columns, in a datetime indexed dataframe, the value of which is 1 if the time of the day of each row falls in the time range 8:30 - 15:00 for column "US_market" in the time range 2:00 - 8:30 for column "EU_market" in the time range 00:00 - 2...
Pandas use time_between with apply lambda
I need to create 3 new boolean columns, in a datetime indexed dataframe, the value of which is 1 if the time of the day of each row falls in the time range 8:30 - 15:00 for column "US_market" in the time range 2:00 - 8:30 for column "EU_market" in the time range 00:00 - 2:00 and 15:00 - 00:00 for "AS_market" I tried ...
[ "This is because apply would pass the entire column and you are trying to apply the between_time() logic to the full column instead of a value-by-value basis.\ndf_elaborated['US_market'] = np.where(df_elaborated.index.isin(df_elaborated.between_time('1:00','14:00').index),1,0)\n\n" ]
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074421527_dataframe_pandas_python.txt
Q: What is a normalized range of values? I'm studying k-anonymization and the mondrian algorithm proposed by LeFevre. In it, LeFevre says that at one point in his algorithm, we have to choose a feature in the Dataframe depending on which feature has the largest range of normalized values. For example, if I have the f...
What is a normalized range of values?
I'm studying k-anonymization and the mondrian algorithm proposed by LeFevre. In it, LeFevre says that at one point in his algorithm, we have to choose a feature in the Dataframe depending on which feature has the largest range of normalized values. For example, if I have the feature Age in my dataset with the values: [...
[ "It depends on a normalization technique but yes. If we use min max it will always be between [0,1]. What you can do is split that variable into segments and the normalized your data. However you use minx-max normalization, the minimum value of that feature gets transformed into a 0, and the maximum value gets a 1....
[ 0 ]
[]
[]
[ "anonymity", "python" ]
stackoverflow_0074420861_anonymity_python.txt
Q: Python/Pandas : Do a value_counts() for each value of a column sorry to bother you but I'm struggling with my code. What I've been trying to do is to determine the repartition of a column for each value of another column of my dataframe. I'm going to show an example with the iris dataset, it might be more clear. I...
Python/Pandas : Do a value_counts() for each value of a column
sorry to bother you but I'm struggling with my code. What I've been trying to do is to determine the repartition of a column for each value of another column of my dataframe. I'm going to show an example with the iris dataset, it might be more clear. I use this code : import sklearn.datasets data, target = sklearn.dat...
[ "If I understand you correctly, you want to group the dataframe by sepal length (cm) and find the number of occurrences in each group by the target column. If this is the case, you can try something like this:\ndata.groupby(['sepal length (cm)'])['target'].agg('count').reset_index()\n\nThis gives you an output like...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074420022_pandas_python.txt
Q: Risk game with python i am pretty much starting to learn code so my knowledge is limited. following scenario: there is this "risk" game where playerA rolls a dice three times and playerB two times. now the two highest results of playerA are compared to the two of player B. if the highest result of A is greater tha...
Risk game with python
i am pretty much starting to learn code so my knowledge is limited. following scenario: there is this "risk" game where playerA rolls a dice three times and playerB two times. now the two highest results of playerA are compared to the two of player B. if the highest result of A is greater than playerBs, player A gets a...
[ "Here is how I would do it:\n\nCreate a function that casts a given number of dice and sorts the results in descending order, and returns that list. For example cast_dice(3) could return [6, 4, 1]\n\nUse that function to produce a result for the red player and the blue player. Then zip those two lists (the third di...
[ 0 ]
[]
[]
[ "loops", "python" ]
stackoverflow_0074421396_loops_python.txt
Q: Groupby + mean function producing e numbers which don't look right I have the following code where I am trying to group the dataframe 'newdata' by the first column and then find the mean of the column '0_happy'. However, the output is producing me with e numbers, which seem too big/small to be mean values. I would...
Groupby + mean function producing e numbers which don't look right
I have the following code where I am trying to group the dataframe 'newdata' by the first column and then find the mean of the column '0_happy'. However, the output is producing me with e numbers, which seem too big/small to be mean values. I would be so grateful if anybody could point out where I may be going wrong? n...
[ "I tried to test your code on the first 10 entries. As expected it seems to work fine.\nI would suggest using it like with the column. Like this:\n# to make it easier for other folks trying to check this out\nNaN = np.nan\ndata = [[NaN,NaN,NaN],\n[NaN,NaN,NaN],\n[NaN,NaN,NaN],\n[NaN,NaN,NaN],\n[NaN,NaN,NaN],\n[\"fu...
[ 1, 0, 0 ]
[]
[]
[ "dataframe", "jupyter_notebook", "pandas", "python" ]
stackoverflow_0074417814_dataframe_jupyter_notebook_pandas_python.txt
Q: Django ManyToMany field has automatically all the Users in admin panel class Course(models.Model): students = models.ManyToManyField(User, verbose_name='Students', null=True, blank=True) I want to add course enrollment to model Course but my manytomanyfield already has all the users and I can't even remove an...
Django ManyToMany field has automatically all the Users in admin panel
class Course(models.Model): students = models.ManyToManyField(User, verbose_name='Students', null=True, blank=True) I want to add course enrollment to model Course but my manytomanyfield already has all the users and I can't even remove any of them. What should I do? I want "Students" to be a list of users who ta...
[ "No! The student named (references to the student objects) are listed there as options of a multiple select widget but they are not actually selected. To select students for the course you would hold down the control key and click and the appropriate student’s names (control key on windows) . You could also just c...
[ 1 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0074421549_django_django_models_python.txt
Q: create a list from class user input Create an employee class with the following members: name, age, id, salary setData() - should allow employee data to be set via user input getData()- should output employee data to the console create a list of 5 employees. You can create a list of objects in the following way, a...
create a list from class user input
Create an employee class with the following members: name, age, id, salary setData() - should allow employee data to be set via user input getData()- should output employee data to the console create a list of 5 employees. You can create a list of objects in the following way, appending the objects to the lists. em...
[ "Change the instance variable self.n ( in the setData method) to self.name to match the declaration your class init method ...and do the same for the self.a, self.i... variables .\n", "I beleive the problem is that you are not setting the parameters to the ones you want in the setData function.\nYou need to do th...
[ 1, 1, 0 ]
[]
[]
[ "append", "class", "list", "object", "python" ]
stackoverflow_0074421540_append_class_list_object_python.txt
Q: Python if...in.. statement. Check for vowel in word I'm trying to check if the user input contains a vowel or not. However, I've only found how to check for one vowel at a time, but not all. vowel = ("a") word = input("type a word: ") if vowel in word: print (f"There is the vowel {vowel} in your word") else: ...
Python if...in.. statement. Check for vowel in word
I'm trying to check if the user input contains a vowel or not. However, I've only found how to check for one vowel at a time, but not all. vowel = ("a") word = input("type a word: ") if vowel in word: print (f"There is the vowel {vowel} in your word") else: print ("There is no vowel in your word") This seems to w...
[ "If you do not need to know which vowels are present, you can use any as follows.\nvowels = (\"a\", \"e\", \"i\", \"o\", \"u\")\n\nword = input(\"type a word: \")\n\nif any(v in word for v in vowels):\n print(\"There is at least one vowel in your word.\")\nelse:\n print(\"There is no vowel in your word.\")\n\...
[ 2, 1, 1, 0, 0 ]
[ "you have to iterate over the list.\nvowels = [\"a\",\"e\",\"i\",\"o\",\"u\"]\n\nword = input(\"type a word: \")\n\nfor vowel in vowels:\n if vowel in word:\n print (f\"There is the vowel {vowel} in your word\")\n else:\n print (\"There is no vowel in your word\")\n\niteration is the proces where you go ...
[ -1 ]
[ "if_statement", "in_function", "list", "python", "user_input" ]
stackoverflow_0071103183_if_statement_in_function_list_python_user_input.txt
Q: Stop python script every 60 seconds and restart This script loops and even if it crashes it restarts. Now I want it to restart the script even if it has NOT CRASHED yet. while True: try: do_main_logic() except: pass I have the loop that restart on crash, but I want it to restart on 60 seco...
Stop python script every 60 seconds and restart
This script loops and even if it crashes it restarts. Now I want it to restart the script even if it has NOT CRASHED yet. while True: try: do_main_logic() except: pass I have the loop that restart on crash, but I want it to restart on 60 seconds.
[]
[]
[ "You can do this :\nfrom time import sleep\n while True:\n try:\n do_main_logic()\n except:\n sleep(60)\n pass\n\n", "It is pretty hard to understand what you are asking for but i can still show how if works:\nwhile True:\ntry:\n #Try to do something\nexcept:\n #if it failed\ne...
[ -1, -1 ]
[ "python" ]
stackoverflow_0074421617_python.txt
Q: Python class Attribute Error even though attribute is in __init__ I'm trying to run my program: from ursina import * from ursina.prefabs.first_person_controller import FirstPersonController app = Ursina() window.fullscreen = True class Voxel(Button): def __init__(self, colour, position = (0, 0, 0)): ...
Python class Attribute Error even though attribute is in __init__
I'm trying to run my program: from ursina import * from ursina.prefabs.first_person_controller import FirstPersonController app = Ursina() window.fullscreen = True class Voxel(Button): def __init__(self, colour, position = (0, 0, 0)): super().__init__( parent = scene, position = p...
[ "This code appears to be using both color and colour in multiple places.\nIt looks like the ursina library uses the color form.\nI would suggest using color everywhere in your code to stay consistent with the library you are using. It will be harder to maintain if you need to translate between spellings and rememb...
[ 2, 0 ]
[]
[]
[ "attributeerror", "class", "python", "python_3.10", "ursina" ]
stackoverflow_0074414778_attributeerror_class_python_python_3.10_ursina.txt
Q: Select export picture from HTML with selenium python I tried to export the generated chart to png file from the menu in this website. After I manage to enter a city name and Visualize Results with script, the website shows some information and chart where I can export to png, either with small or large option. How...
Select export picture from HTML with selenium python
I tried to export the generated chart to png file from the menu in this website. After I manage to enter a city name and Visualize Results with script, the website shows some information and chart where I can export to png, either with small or large option. However, I could not manage to export large png file (option ...
[ "First, before clicking this button you need to click the export button which opens the dropdown with the options. This code did the thing:\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.support import ...
[ 0, 0 ]
[]
[]
[ "python", "selenium", "selenium_webdriver", "webdriverwait" ]
stackoverflow_0074419493_python_selenium_selenium_webdriver_webdriverwait.txt
Q: Pandas .iloc[] not working with index range I have a dataframe df as below: Name Count [{‘text’: ‘Server1.com’}] [{‘text’: 1}] [{‘text’: ‘Server3.com’}] [{‘text’: 1}] [{‘text’: ‘Server2.com’}] [{‘text’: 22}] I want to transform this into: Name Co...
Pandas .iloc[] not working with index range
I have a dataframe df as below: Name Count [{‘text’: ‘Server1.com’}] [{‘text’: 1}] [{‘text’: ‘Server3.com’}] [{‘text’: 1}] [{‘text’: ‘Server2.com’}] [{‘text’: 22}] I want to transform this into: Name Count Server1.com 1 Server...
[ "An easy option is to use applymap:\nout = df.applymap(lambda x: x[0]['text'])\n\nAnother option:\nout = df.apply(lambda s: s.str[0].str['text'])\n\nOutput:\n Name Count\n0 Server1.com 1\n1 Server3.com 1\n2 Server2.com 22\n\nUsed input:\ndf = pd.DataFrame({'Name': [[{'text': 'Server1.com'...
[ 3 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074421793_dataframe_pandas_python.txt
Q: Web scrape using Python - Execution takes too long I am trying to webscrape the "Active Positions" table from the following website: https://www.nasdaq.com/market-activity/stocks/aapl/institutional-holdings My code is below: from bs4 import BeautifulSoup import requests html_text = requests.get('https://www.nasda...
Web scrape using Python - Execution takes too long
I am trying to webscrape the "Active Positions" table from the following website: https://www.nasdaq.com/market-activity/stocks/aapl/institutional-holdings My code is below: from bs4 import BeautifulSoup import requests html_text = requests.get('https://www.nasdaq.com/market-activity/stocks/aapl/institutional-holdings...
[ "Data is being hydrated in page via Javascript XHR calls. Here is a way of getting ActivePositions by scraping the API endpoint directly:\nimport requests\nimport pandas as pd\n\nurl = 'https://api.nasdaq.com/api/company/AAPL/institutional-holdings?limit=15&type=TOTAL&sortColumn=marketValue&sortOrder=DESC'\n\nheade...
[ 1 ]
[]
[]
[ "beautifulsoup", "python", "python_requests", "web_scraping" ]
stackoverflow_0074421785_beautifulsoup_python_python_requests_web_scraping.txt
Q: How can I fill two columns of a dataframe with "np.where"? I am trying to set 2 columns by a condition on a 3rd column. I can set 1 column conditions on another column, and I can set 2 columns on a single condition value, but when I try to set 2 columns by a condition on a column, it fails. Here is the code exampl...
How can I fill two columns of a dataframe with "np.where"?
I am trying to set 2 columns by a condition on a 3rd column. I can set 1 column conditions on another column, and I can set 2 columns on a single condition value, but when I try to set 2 columns by a condition on a column, it fails. Here is the code example: import pandas as pd import numpy as np AAA = {"column A": [1,...
[ "use loc indexer and give value\ndf.loc[df['column A'] == 2, ['column B', 'column C']] = [4, 8]\n\noutput(df):\n column A column B column C\n0 1 NaN NaN\n1 1 NaN NaN\n2 1 NaN NaN\n3 2 4.0 8.0\n4 2 4.0 8.0\n5...
[ 4, 1, 0, 0 ]
[]
[]
[ "array_broadcasting", "numpy", "pandas", "python", "where_clause" ]
stackoverflow_0074421538_array_broadcasting_numpy_pandas_python_where_clause.txt
Q: Error : psutil.NoSuchProcess: Process no longer exists (pid=23100) I have this code for getting PIDs for specific processes; the code is running well, but sometimes I get this error: psutil.NoSuchProcess: Process no longer exists (pid=xxxx) How can this problem be solved? And how can I restart the script if this ...
Error : psutil.NoSuchProcess: Process no longer exists (pid=23100)
I have this code for getting PIDs for specific processes; the code is running well, but sometimes I get this error: psutil.NoSuchProcess: Process no longer exists (pid=xxxx) How can this problem be solved? And how can I restart the script if this error or other errors happened? import psutil my_pid = None pids = psu...
[ "The problem is that between discovering the pid (process ID) of a given program and the loop getting to the point where it attempts to inspect it, that process has already stopped running.\nYou can work around it by using try / except:\nfor pid in pids:\n try:\n ps = psutil.Process(pid)\n name = p...
[ 1 ]
[]
[]
[ "python", "python_2.7", "python_3.x" ]
stackoverflow_0074420568_python_python_2.7_python_3.x.txt
Q: how to import geopandas in google Colab !apt install gdal-bin python-gdal python3-gdal !apt install python3-rtree !pip install git+git://github.com/geopandas/geopandas.git !pip install descartes I get a warning from line 4 onwards. Also, after running this code, if I run the "import geopandas as gpd" code, it th...
how to import geopandas in google Colab
!apt install gdal-bin python-gdal python3-gdal !apt install python3-rtree !pip install git+git://github.com/geopandas/geopandas.git !pip install descartes I get a warning from line 4 onwards. Also, after running this code, if I run the "import geopandas as gpd" code, it throws an error and the import is not possible....
[ "I replicate your situation on my colab and this line of code caused a problem\n!pip install git+git://github.com/geopandas/geopandas.git\n\nand rest of line of code working properly.\n!apt install gdal-bin python-gdal python3-gdal \n!apt install python3-rtree \n!pip install git+git://github.com/geopandas/geopandas...
[ 1 ]
[]
[]
[ "geopandas", "google_colaboratory", "python" ]
stackoverflow_0074419592_geopandas_google_colaboratory_python.txt
Q: Why is list comprehension slower than a for loop? Why is the for loop appending faster than list comprehension For Loop Time: 7.214778099999876 List Comprehension Time: 7.4003780000002735 Code 1: import timeit mycode = ''' new_list=[] x=[1,2,3,4,5] for obj in x: if obj %2==0: new_list.append(obj) ''' ...
Why is list comprehension slower than a for loop?
Why is the for loop appending faster than list comprehension For Loop Time: 7.214778099999876 List Comprehension Time: 7.4003780000002735 Code 1: import timeit mycode = ''' new_list=[] x=[1,2,3,4,5] for obj in x: if obj %2==0: new_list.append(obj) ''' print (timeit.timeit(stmt = mycode, ...
[ "This is because the list comprehension version has a bigger startup overhead. The bigger the list the faster the list comprehension is compared to the basic loop.\nIndeed, with x=list(range(15)) the list comprehension is 10% faster on my machine as opposed to 10% slower for the provided input. With x=list(range(10...
[ 1, 0 ]
[]
[]
[ "benchmarking", "for_loop", "list_comprehension", "performance", "python" ]
stackoverflow_0074419698_benchmarking_for_loop_list_comprehension_performance_python.txt
Q: Column name changes not saved in Jupyter Notebook I have loaded Data into a few Spark dataframes with a provided schema into a Jupyter Notebook. Now I want to add a prefix to the column names of all dataFrames. There are multiple post regarding this topic (e.g. Rename more than one column and the renaming itself d...
Column name changes not saved in Jupyter Notebook
I have loaded Data into a few Spark dataframes with a provided schema into a Jupyter Notebook. Now I want to add a prefix to the column names of all dataFrames. There are multiple post regarding this topic (e.g. Rename more than one column and the renaming itself does work using the previously mentioned answer code: df...
[ "Looks like this is an issue with how python references items when iterating over a list, see https://stackoverflow.com/a/55629813\nTry using another method,\nE.g.\ndef prefix_cols(df, pref):\n return df.select([f.col(c).alias(pref + c) for c in df.columns])\n\ndf_list = [prefix_cols(df, 'z_') for df in df_list]...
[ 0 ]
[]
[]
[ "jupyter_notebook", "pyspark", "python" ]
stackoverflow_0074421780_jupyter_notebook_pyspark_python.txt
Q: ERROR: Could not find a version that satisfies the requirement torch (from versions: none) Python version C:\Users\donhu>python --version Python 3.11.0 C:\Users\donhu> I try install PyTorch, but catch error ERROR: Could not find a version that satisfies the requirement torch (from versions: none) I also try wit...
ERROR: Could not find a version that satisfies the requirement torch (from versions: none)
Python version C:\Users\donhu>python --version Python 3.11.0 C:\Users\donhu> I try install PyTorch, but catch error ERROR: Could not find a version that satisfies the requirement torch (from versions: none) I also try with Jupyter lab, and other version of PyTorch (nightly build), but not success. How to fix it?
[ "From https://pytorch.org/get-started/locally/\n\nCurrently, PyTorch on Windows only supports Python 3.7-3.9\n\n" ]
[ 0 ]
[]
[]
[ "jupyter_lab", "pip", "python", "pytorch" ]
stackoverflow_0074420589_jupyter_lab_pip_python_pytorch.txt
Q: Quadratic Programming in Python using Numpy? I am in the process of translating some MATLAB code into Python. There is one line that is giving me a bit of trouble: [q,f_dummy,exitflag, output] = quadprog(H,f,-A,zeros(p*N,1),E,qm,[],[],q0,options); I looked up the documentation in MATLAB to find that the quadprog ...
Quadratic Programming in Python using Numpy?
I am in the process of translating some MATLAB code into Python. There is one line that is giving me a bit of trouble: [q,f_dummy,exitflag, output] = quadprog(H,f,-A,zeros(p*N,1),E,qm,[],[],q0,options); I looked up the documentation in MATLAB to find that the quadprog function is used for optimization (particularly mi...
[ "There is a library called CVXOPT that has quadratic programming in it.\ndef quadprog_solve_qp(P, q, G=None, h=None, A=None, b=None):\n qp_G = .5 * (P + P.T) # make sure P is symmetric\n qp_a = -q\n if A is not None:\n qp_C = -numpy.vstack([A, G]).T\n qp_b = -numpy.hstack([b, h])\n ...
[ 4, 4, 2, 0 ]
[]
[]
[ "matlab", "numpy", "optimization", "python", "quadratic_programming" ]
stackoverflow_0051161348_matlab_numpy_optimization_python_quadratic_programming.txt
Q: How can I order dictionary according to value size in python? I have a dictionary, example: my_dict = {key1: [X,Y,Z], key2: [X,X,X,Y,Z], key3: [X]} I want to create a list with the keys arranged from longest values to shortest. For this example the list should be ls = [key2, key1, key3] A: sortedList = sorted( ...
How can I order dictionary according to value size in python?
I have a dictionary, example: my_dict = {key1: [X,Y,Z], key2: [X,X,X,Y,Z], key3: [X]} I want to create a list with the keys arranged from longest values to shortest. For this example the list should be ls = [key2, key1, key3]
[ "sortedList = sorted(\n list(my_dict.keys()), \n key= lambda dictKey: len(my_dict[dictKey]), \n reverse= True\n)\n\nExplanation :\nThe first parameter is the list to be sorted. In your case, the dict's keys.\nThe second parameter is the sorting key: how does it compare two elements in the list? In your cas...
[ 0 ]
[]
[]
[ "dictionary", "list", "python", "sorting" ]
stackoverflow_0074421801_dictionary_list_python_sorting.txt
Q: Download and extract .tar files with multiprocessing I have a file containing a bunch of large .tar.bz2 files that I want to download and extract into a folder. I am trying to speed up the process with multithreading (for downloading) and multiprocessing (for extracting the files). The downloading works fine and f...
Download and extract .tar files with multiprocessing
I have a file containing a bunch of large .tar.bz2 files that I want to download and extract into a folder. I am trying to speed up the process with multithreading (for downloading) and multiprocessing (for extracting the files). The downloading works fine and fairly quickly, but the extraction never even begins. This ...
[ "The problem can arise when a new process is forked when the main process has threads other than the main thread. In this case the process can hang waiting for a lock to be released. This problem does not seem to occur when using the multiprocessing package for creating a pool.\nUnless the number of URLs being retr...
[ 0 ]
[]
[]
[ "download", "multiprocessing", "python", "tarfile" ]
stackoverflow_0074415061_download_multiprocessing_python_tarfile.txt
Q: Django. Increment views count of object without affecting its updated_at field I have the following model: class Announcement(models.Model): ... created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) views = models.PositiveIntegerField(default=0, edita...
Django. Increment views count of object without affecting its updated_at field
I have the following model: class Announcement(models.Model): ... created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) views = models.PositiveIntegerField(default=0, editable=False) my view: class AnnouncementDetailView(DetailView): model = Announcem...
[ "An easy way to do this, might be to specify update_fields in the .save(…) method [Django-doc]:\nclass AnnouncementDetailView(DetailView):\n model = Announcement\n context_object_name = 'announcement'\n template_name = 'web/index.html'\n\n def get(self, *args, **kwargs):\n try:\n retur...
[ 1 ]
[]
[]
[ "database", "django", "django_models", "python" ]
stackoverflow_0074421959_database_django_django_models_python.txt
Q: external URL not working for streamlit app deployed using docker I deployed my Streamlit app using docker, and when I run the container on a GCP VM where I did the docker build, it displays a network url and external url but when I try opening the external url, it doesn’t load. It doesn’t seem to be a firewall iss...
external URL not working for streamlit app deployed using docker
I deployed my Streamlit app using docker, and when I run the container on a GCP VM where I did the docker build, it displays a network url and external url but when I try opening the external url, it doesn’t load. It doesn’t seem to be a firewall issue either. What should I do if I want to use my external url to share ...
[ "So this completely depends on whatever hardware and network you're hosting this on.\nWhat the docker run -p 8501:8501 <docker_image_id> does, is that it binds the port 8501 on the host running docker to the port 8501 on the docker container.\nBut that does not mean that it becomes accessible on the wider internet....
[ 0 ]
[]
[]
[ "deployment", "docker", "python", "streamlit", "webapp2" ]
stackoverflow_0074420818_deployment_docker_python_streamlit_webapp2.txt
Q: Split csv file into 2 list depending upon column name using python I want to split csv file into 2 lists using column name CSV file: Molecule Name,SMILES ZINC53 (Aspirin),CC(=O)Oc1ccccc1C(=O)O ZINC7460 (Vatalanib),Clc1ccc(Nc2nnc(Cc3ccncc3)c3ccccc23)cc1 ZINC1493878 (Sorafenib),CNC(=O)c1cc(Oc2ccc(NC(=O)Nc3ccc(Cl)c(C...
Split csv file into 2 list depending upon column name using python
I want to split csv file into 2 lists using column name CSV file: Molecule Name,SMILES ZINC53 (Aspirin),CC(=O)Oc1ccccc1C(=O)O ZINC7460 (Vatalanib),Clc1ccc(Nc2nnc(Cc3ccncc3)c3ccccc23)cc1 ZINC1493878 (Sorafenib),CNC(=O)c1cc(Oc2ccc(NC(=O)Nc3ccc(Cl)c(C(F)(F)F)c3)cc2)ccn1 Code: namelist = list() smileslist = list() wit...
[ "With pandas library you can do it as easily as :\n\nimport pandas as pd\n\n\ndf = pd.read_csv(\"./file.csv\")\nnamelist = df[\"Molecule Name\"].tolist()\nsmileslist = df[\"SMILES\"].tolist()\n\nprint(namelist)\nprint(smileslist)\n\nOr if you prefer using the csv reader you can do it as follow :\nimport csv\n\n\nna...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074421669_dataframe_pandas_python.txt
Q: Create a dynamic graph with DyNetx from dataframe I am trying to create a dynamic graph with DyNetx, however, I am having trouble adding nodes. When I try to add a sender, receiver and timestamp with my real data the result is [None, None, None] When I tried my code with some sample data, I get the error TypeError...
Create a dynamic graph with DyNetx from dataframe
I am trying to create a dynamic graph with DyNetx, however, I am having trouble adding nodes. When I try to add a sender, receiver and timestamp with my real data the result is [None, None, None] When I tried my code with some sample data, I get the error TypeError: Addition/subtraction of integers and integer-arrays w...
[ "Your error message suggests that timestamps in the date format are no longer supported. I would suggest converting your timestamps to seconds and using those in g.add_interaction. You can do this conversion by using:df['sec']=[pd.Timestamp(df['time'][i]).timestamp() for i in range(len(df))]. More examples of this ...
[ 1 ]
[]
[]
[ "dataframe", "networkx", "python" ]
stackoverflow_0074417001_dataframe_networkx_python.txt
Q: Extract from (a word) to (another word) in a string using REGEX I'm trying to extract an entire piece of text using a REGEX expression, but i can't find the right syntax. For Example this can be my string (that comes from .read): Here there are some stuff that can be whatever Run: 55 / 100 Here there are some ...
Extract from (a word) to (another word) in a string using REGEX
I'm trying to extract an entire piece of text using a REGEX expression, but i can't find the right syntax. For Example this can be my string (that comes from .read): Here there are some stuff that can be whatever Run: 55 / 100 Here there are some stuff that can be whatever DOCKED: ENDMDL Here there are some stuff...
[ "You can use re.findall method by providing the pattern to match your case for finding the substring between two strings, then it will return list of all matches in a string:\nimport re\nstr = \"Here there are some stuff that can be whatever1\\\nRun: 55 / 100\\\nHere there are some stuff that can be whatever2\\\n...
[ 1 ]
[]
[]
[ "parsing", "python", "regex" ]
stackoverflow_0074421286_parsing_python_regex.txt
Q: How to read a line while reading a file in Python Imagine that another filename in the same directory is inside the txt file we're currently in: For example, let file A be the following: B.txt computer science How would it be possible to read the other lines and go into B.txt after we're done reading? ...
How to read a line while reading a file in Python
Imagine that another filename in the same directory is inside the txt file we're currently in: For example, let file A be the following: B.txt computer science How would it be possible to read the other lines and go into B.txt after we're done reading?
[ "If you want to read first line separately, you can do it with readline(). Loop then proceeds to read the file from the second line to the end of file:\nimport os\n\n\ndef read_files_to_list(wordlist, file):\n with open(file, \"r\") as f:\n newfile = f.readline()\n newfile = newfile.strip() # rem...
[ 1 ]
[]
[]
[ "arrays", "list", "python", "string" ]
stackoverflow_0074421663_arrays_list_python_string.txt
Q: Skip errors and continue loop when url provides no file I am using Tabula-py to download and extract tables from PDFs via a list of URLs. The URLs are created based on rules and everything is working fine except when Tabula tries to process a PDF from a link with no page/file (specifically weekends as PDFs aren't ...
Skip errors and continue loop when url provides no file
I am using Tabula-py to download and extract tables from PDFs via a list of URLs. The URLs are created based on rules and everything is working fine except when Tabula tries to process a PDF from a link with no page/file (specifically weekends as PDFs aren't published on weekends). Full Python script below. I want the ...
[ "You can write separate try/catches for each independent functions so the others will continue:\ntry:\n foo = func1()\n foo.func2()\nexcept Exception:\n print(\"this failed\")\n\ntry:\n mom = func3()\nexcept Exception:\n print(\"this failed\")\n\ntry:\n func4()\nexcept Exception:\n print(\"this failed\")\n\n...
[ 0 ]
[]
[]
[ "python", "tabula_py" ]
stackoverflow_0074422033_python_tabula_py.txt
Q: Math domain error in function with undefined variable I want to plot two functions and find their intersections. The problem is that I have a variable b that is not defined because it is the solution of the problem. My program is the following. import math import numpy as np import matplotlib.pyplot as plt ...
Math domain error in function with undefined variable
I want to plot two functions and find their intersections. The problem is that I have a variable b that is not defined because it is the solution of the problem. My program is the following. import math import numpy as np import matplotlib.pyplot as plt n1 = 1 n2 = 2.6 n3 = 2.4 ko = 2 * math.pi / (350 * pow(1...
[ "k is negative value in your case. which is -322272796770264.7.\nimport math\nprint(math.sqrt(-322272796770264.7))\n\nGives\nline 2, in <module>\n print(math.sqrt(-322272796770264.7))\nValueError: math domain error\n\nThis is beacuse you can't find square root of negative number using mat. numpy instead. sqrt of...
[ 1 ]
[]
[]
[ "math", "python" ]
stackoverflow_0074421950_math_python.txt
Q: get error when want POST something to api{detail: "CSRF Failed: CSRF token missing."} when i want to POST some thing to API , i get this error : CSRF TOKEN , but i don't have CSRF Token in django , i want POST without CSRF token i can POST with Postman but when i want post it by js , i get error that i said in fi...
get error when want POST something to api{detail: "CSRF Failed: CSRF token missing."}
when i want to POST some thing to API , i get this error : CSRF TOKEN , but i don't have CSRF Token in django , i want POST without CSRF token i can POST with Postman but when i want post it by js , i get error that i said in first how can i do? let edit_data = { user_id: "1", company: "rahaaaa", ...
[ "Let your post-view method know, that you don't want to validate the CSRF token.\nYou can use the following decorator if you are using function-based views.\nfrom django.views.decorators.csrf import csrf_exempt\n@csrf_exempt\ndef my_view(request):\n return HttpResponse('Hello world')\n\nIf you are using class-ba...
[ 0 ]
[]
[]
[ "django", "javascript", "python" ]
stackoverflow_0074422046_django_javascript_python.txt
Q: How to show all the tags related to a publication in a list of publications filtered by a tag in Django? Consider following models: # models.py from django.db import models class Tag(models.Model): name = models.CharField(max_length=40) number_of_publications = models.PositiveIntegerField(default=0) ...
How to show all the tags related to a publication in a list of publications filtered by a tag in Django?
Consider following models: # models.py from django.db import models class Tag(models.Model): name = models.CharField(max_length=40) number_of_publications = models.PositiveIntegerField(default=0) def __str__(self): return self.name class Publication(models.Model): name = models.CharField(max...
[ "You can add a property to your Publication model to render tags as a list of strings, so:\nclass Publication(models.Model):\n text = models.TextField()\n tags = models.ManyToManyField(Tag)\n\n @property\n def tags_list(self):\n # renders as [\"django\", \"python\", ...]\n return list(self...
[ 1, 0 ]
[]
[]
[ "django", "many_to_many", "orm", "python" ]
stackoverflow_0074417904_django_many_to_many_orm_python.txt
Q: function that returns which team has the most wins How can I write a function that takes a two-dimensional sequence as an argument and returns which team earned the most wins? when multiple teams earn the same amount of wins, it should return the first team's serial number. It should return something like this: wh...
function that returns which team has the most wins
How can I write a function that takes a two-dimensional sequence as an argument and returns which team earned the most wins? when multiple teams earn the same amount of wins, it should return the first team's serial number. It should return something like this: who_won([['W', 'W', 'W'], ['L', 'L', 'L'], ['W', 'W', 'L']...
[ "You can call the max operator, sorting rows by their number of wins, and using their i-index position matrix[i] as a secondary parameter (to decide in case of draws).\ndef who_won(matrix):\n return 1 + max(range(len(matrix)), key = lambda i: [matrix[i].count('W'),-i])\n\n# print(who_won([['W', 'W', 'W'], ['L', ...
[ 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074422009_python.txt
Q: Is there any quadratic programming function that can have both lower and upper bounds - Python Normally I have been using GNU Octave to solve quadratic programming problems. I solve problems like x = 1/2x'Qx + c'x With subject to A*x <= b lb <= x <= ub Where lb and ub are lower bounds and upper bounds, e.g limit...
Is there any quadratic programming function that can have both lower and upper bounds - Python
Normally I have been using GNU Octave to solve quadratic programming problems. I solve problems like x = 1/2x'Qx + c'x With subject to A*x <= b lb <= x <= ub Where lb and ub are lower bounds and upper bounds, e.g limits for x My Octave code looks like this when I solve. Just one simple line U = quadprog(Q, c, A, b, [...
[ "You can write your own solver based scipy.optimize, here is a small example on how to code your custom python quadprog():\n# python3\nimport numpy as np\nfrom scipy import optimize\n\nclass quadprog(object):\n\n def __init__(self, H, f, A, b, x0, lb, ub):\n self.H = H\n self.f = f\n ...
[ 4, 2, 1 ]
[]
[]
[ "numpy", "python", "quadratic_programming", "scipy", "scipy_optimize" ]
stackoverflow_0055800584_numpy_python_quadratic_programming_scipy_scipy_optimize.txt