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 can we convert a nested XML to CSV in Python Dynamically, Nested XML may contain array of values as well? Sharing Sample XML file. Need to convert this fie to CSV, even if extra tags are added in this file. {without using tag names}. And XML file tag names should be used as column names while converting it to ...
How can we convert a nested XML to CSV in Python Dynamically, Nested XML may contain array of values as well?
Sharing Sample XML file. Need to convert this fie to CSV, even if extra tags are added in this file. {without using tag names}. And XML file tag names should be used as column names while converting it to CSV} Example Data: <?xml version="1.0" encoding="UTF-8"?> <Food> <Info> <Msg>Food Store items.</Msg> ...
[ "ElementTree is not really the best tool for what I believe you're trying to do. Since you have well-formed, relatively simple xml, try using pandas:\nimport pandas as pd\n\n#from here, it's just a one liner\npd.read_xml('input.xml',xpath='.//store').to_csv('output.csv',sep=',', index = None, header=True)\n\nand th...
[ 1, 1 ]
[]
[]
[ "python", "xml", "xmltocsv" ]
stackoverflow_0074194876_python_xml_xmltocsv.txt
Q: Unable to get page source of the page generated by JavaScript import scrapy from scrapy import Spider from scrapy.http import TextResponse from selenium import webdriver from selenium.webdriver.chrome.service import Service as ChromeService from webdriver_manager.chrome import ChromeDriverManager class Ext...
Unable to get page source of the page generated by JavaScript
import scrapy from scrapy import Spider from scrapy.http import TextResponse from selenium import webdriver from selenium.webdriver.chrome.service import Service as ChromeService from webdriver_manager.chrome import ChromeDriverManager class ExtractSpider(Spider): name = "extract" # handle_httpstatus...
[ "I am not familiar with scrapy but the line res = response.replace(body=self.browser.page_source) tells that it receives page source as a text in the body parameter.\nYou can wait until the page is loaded and then get all the content on the html tag as text. And before passing it to scrapy add <html> tags back. So ...
[ 0 ]
[]
[]
[ "python", "scrapy", "selenium" ]
stackoverflow_0074261456_python_scrapy_selenium.txt
Q: Creating new column based on specific part of a string using pandas I have the table below with codes. I would like to create two new columns. 1 that identifies any code with the letters YYY and another that identifies the letters WWW as seen in the intermediate table. After that, I would like to aggregate these a...
Creating new column based on specific part of a string using pandas
I have the table below with codes. I would like to create two new columns. 1 that identifies any code with the letters YYY and another that identifies the letters WWW as seen in the intermediate table. After that, I would like to aggregate these and have a ID's columns with all the YYY codes and WWW codes and their tot...
[ "# assuming the string of interest is the last under the code column\n\ndf['id'] = df['Code'].str.rsplit(',', n=1, expand=True)[1]\n\n# create columns with 1 or 0 if string exists in the Code\ndf['Location_Y'] = df['id'].eq('YYY').astype(int)\ndf['Location_W'] = df['id'].eq('WWW').astype(int)\n\n\n# groupby to get ...
[ 1, 1, 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074281481_pandas_python.txt
Q: Airflow webserver gives cron error for dags with None as schedule interval I'm running Airflow 1.9.0 with LocalExecutor and PostgreSQL database in a Linux AMI. I want to manually trigger DAGs, but whenever I create a DAG that has schedule_interval set to None or to @once, the webserver tree view crashes with the f...
Airflow webserver gives cron error for dags with None as schedule interval
I'm running Airflow 1.9.0 with LocalExecutor and PostgreSQL database in a Linux AMI. I want to manually trigger DAGs, but whenever I create a DAG that has schedule_interval set to None or to @once, the webserver tree view crashes with the following error (I only show the last call): File "/usr/local/lib/python2.7/site-...
[ "Try this:\n\nSet your schedule_interval to None without the '', or simply do not specify schedule_interval in your DAG. It is set to None as a default. More information on that here: airflow docs -- search for schedule_interval\nSet orchestration for your tasks at the bottom of the dag.\n\nLike so:\nimport datetim...
[ 21, 0 ]
[]
[]
[ "airflow", "airflow_scheduler", "python" ]
stackoverflow_0051520767_airflow_airflow_scheduler_python.txt
Q: Why do I get error "ValueError: parameters are of unsupported type"? I get the error: ValueError: parameters are of unsupported type The code : async def add(ctx, el: str, email: str, password: str): con= sqlite3.connect("db.sqlite") c = con.cursor() c.execute("SELECT type FROM accounts WHERE type=?"...
Why do I get error "ValueError: parameters are of unsupported type"?
I get the error: ValueError: parameters are of unsupported type The code : async def add(ctx, el: str, email: str, password: str): con= sqlite3.connect("db.sqlite") c = con.cursor() c.execute("SELECT type FROM accounts WHERE type=?", (el,)) results = c.fetchall() if len(results) == 0: awai...
[ "I feel so dumb right now I really wanna cry\nthe problem is that i did after the c.execute(\"UPDATE accounts SET type = ?, email = ?, password = ? ;\")\nI putted a {el, email, password} instead of (el, email, password)...\n" ]
[ 0 ]
[]
[]
[ "discord.py", "pycord", "python", "sqlite" ]
stackoverflow_0074280688_discord.py_pycord_python_sqlite.txt
Q: Finding NaN values in a data frame using column names located in a dictionary I am trying to find all the nan values in certain columns and then print a statement saying that it found nan entries in those columns. import pandas as pd import numpy as np data=[[np.nan, 'Indiana','test@gmail.com']] df=pd.DataFrame(d...
Finding NaN values in a data frame using column names located in a dictionary
I am trying to find all the nan values in certain columns and then print a statement saying that it found nan entries in those columns. import pandas as pd import numpy as np data=[[np.nan, 'Indiana','test@gmail.com']] df=pd.DataFrame(data,columns=['Name','State','Email']) req_dict={"Name","Email"} here is the sampl...
[ "Try using .isna() + .any():\nfor c in req_dict:\n if df[c].isna().any():\n print(\"a blank was found in\", c)\n\nPrints:\na blank was found in Name\n\n\nComplete example:\ndata = [[np.nan, \"Indiana\", \"test@gmail.com\"]]\ndf = pd.DataFrame(data, columns=[\"Name\", \"State\", \"Email\"])\n\nreq_dict = {...
[ 0 ]
[]
[]
[ "dataframe", "dictionary", "pandas", "python" ]
stackoverflow_0074281779_dataframe_dictionary_pandas_python.txt
Q: How can I add only months together in python? I understand using relativedelta for exact month calculation taking into account the number of days in each month. Are there any streamlined libraries for adding just month ints together? ie. December is 12. Adding 2 months is 14 which is 2 == February? I am hoping to ...
How can I add only months together in python?
I understand using relativedelta for exact month calculation taking into account the number of days in each month. Are there any streamlined libraries for adding just month ints together? ie. December is 12. Adding 2 months is 14 which is 2 == February? I am hoping to solve all edge cases surrounding the problem with a...
[ "This formula should work for you\n>>> current_month = 12\n>>> delta = 2\n>>> (((current_month - 1) + delta) % 12) + 1\n2\n\n" ]
[ 0 ]
[]
[]
[ "datetime", "python", "time" ]
stackoverflow_0074281837_datetime_python_time.txt
Q: How do I add a column with a repeating series of values to a dataframe such that each member of list is repeated before the next memeber? I will like to create a column in a dataframe named continent to my existing dataframe df such that the output has each member of my list 7 time before going to the next member ...
How do I add a column with a repeating series of values to a dataframe such that each member of list is repeated before the next memeber?
I will like to create a column in a dataframe named continent to my existing dataframe df such that the output has each member of my list 7 time before going to the next member I tried this import numpy as np frames = [] for file in files: df=wrangle(file) frames.append(df) continent = ["Central and South A...
[ "You can transform your list of continents repeating each element required number of times before creating a new column out of the list.\ncontinent = [\n c for c in continent\n for _ in range(7)\n]\n\ndf['continent'] = continent\n\n" ]
[ 1 ]
[]
[]
[ "numpy", "pandas", "python" ]
stackoverflow_0074281807_numpy_pandas_python.txt
Q: Virtualenvs in Sublime Text 4 I have the different virtualenv's and to be able to specify which virtualenv to use with each project I used package Virtualenv (https://packagecontrol.io/packages/Virtualenv) in Sublime Text 3. That was so to the day when through the update I became the owner of the Sublime Text 4. T...
Virtualenvs in Sublime Text 4
I have the different virtualenv's and to be able to specify which virtualenv to use with each project I used package Virtualenv (https://packagecontrol.io/packages/Virtualenv) in Sublime Text 3. That was so to the day when through the update I became the owner of the Sublime Text 4. The package Virtualenv stopped worki...
[ "There is a package Virtualenv for ST3, you can downgrade. Currently it doesn't work with ST4 (issue).\nYou can specify build system per project:\n\nCreate sublime project or add existing directory to sublime project\nGoto Project -> Edit Project\nAdd this and save in root of you project:\n\n{\n \"build_systems\...
[ 1, 0 ]
[]
[]
[ "python", "sublimetext3", "sublimetext4", "virtualenv" ]
stackoverflow_0068652617_python_sublimetext3_sublimetext4_virtualenv.txt
Q: Using Python to parse and render Kinesis Video Streams and get an image representation of the input frame I have set up a pipeline in which, I live stream the video to Kinesis Video Stream (KVS), which sends the frames to Amazon Rekognition for face recognition, which further sends them to Kinesis Data Stream (KDS...
Using Python to parse and render Kinesis Video Streams and get an image representation of the input frame
I have set up a pipeline in which, I live stream the video to Kinesis Video Stream (KVS), which sends the frames to Amazon Rekognition for face recognition, which further sends them to Kinesis Data Stream (KDS). Finally, KDS sends the results to a lambda. For a frame on which face recognition has been conducted, I get...
[ "The response from GetMedia is the stream which is in MKV packaging format. First, you would need to use some Python library that extracts the frames from the MKV format (https://github.com/vi/mkvparse or alike). Next, your stream is likely to be encoded. For example H264. You will also need to decode the frame in ...
[ 2, 1, 0, 0, 0 ]
[]
[]
[ "amazon_kinesis", "amazon_web_services", "parsing", "payload", "python" ]
stackoverflow_0060912980_amazon_kinesis_amazon_web_services_parsing_payload_python.txt
Q: How to auto-activate python virtual environment in Visual Studio terminal? I am using Visual Studio (not Visual Studio Code) for the development of a Python application. Is there a way to make the Visual Studio's Developer PowerShell auto-activate the virtual environment, as is possible in PyCharm or in VS-Code? R...
How to auto-activate python virtual environment in Visual Studio terminal?
I am using Visual Studio (not Visual Studio Code) for the development of a Python application. Is there a way to make the Visual Studio's Developer PowerShell auto-activate the virtual environment, as is possible in PyCharm or in VS-Code? Right now, I have to explicitly run the command .\env\Scripts\activate in the Ter...
[ "I found a key in setting up PowerShell startup arguments.\nGo to the Visual Studio 2022 Parameters -> Environment -> Terminal.\nIn \"Profiles\" window click on PowerShell for developers (Default), then Arguments and follow next steps:\n\nAdd -ExecutionPolicy RemoteSigned in the very beginning.\nFind -Command \"&{ ...
[ 1 ]
[]
[]
[ "python", "python_venv", "virtualenv", "visual_studio", "visual_studio_2022" ]
stackoverflow_0072599551_python_python_venv_virtualenv_visual_studio_visual_studio_2022.txt
Q: Kivy custom widget instanciated twice I'm trying to build a simple Kivy custom widget containing two sliders. When the screen is rendered I get two pairs of sliders instead of one. What am I doing wrong ? Main.kv: ScreenManagement: MainScreen: <Button>: size_hint: .2, .1 font_size: 20 <Mixer>: or...
Kivy custom widget instanciated twice
I'm trying to build a simple Kivy custom widget containing two sliders. When the screen is rendered I get two pairs of sliders instead of one. What am I doing wrong ? Main.kv: ScreenManagement: MainScreen: <Button>: size_hint: .2, .1 font_size: 20 <Mixer>: orientation:'vertical' Slider: mi...
[ "You should rename the kv file to main.kv, and delete the explicit load of it in build method. It is going to load itself automatically. The bug is weird, maybe worth a ticket.\n", "This happens because of Kivy automatically searches and loads kv filename equal to your class name, excluding App postfix (if exists...
[ 3, 0 ]
[]
[]
[ "kivy", "python", "user_interface" ]
stackoverflow_0039681281_kivy_python_user_interface.txt
Q: Expecting delimiter in .bin file I'm currently working with several .bin files generated by an oscilloscopes' software. These .bin files consist of header and 1.5k points on the screen. A part of a program I wrote to work with those .bin files extracts header and converts it to JSON format. The bytes from the file...
Expecting delimiter in .bin file
I'm currently working with several .bin files generated by an oscilloscopes' software. These .bin files consist of header and 1.5k points on the screen. A part of a program I wrote to work with those .bin files extracts header and converts it to JSON format. The bytes from the files are stored as good_bytes and bad_byt...
[ "I have taken a look at the data and I think there is a more efficient way to do this that doesn't give an error.\nThe first 6 bytes appear to be some kind of preamble. The next four bytes appear to the the length of the JSON header information. This allows the JSON data to be extracted and passed to Python's json ...
[ 0 ]
[]
[]
[ "file", "io", "python" ]
stackoverflow_0074278143_file_io_python.txt
Q: Django heroku app successfully deployed but still showing an internal server error, Log files show the build is successful I am trying to deploy my Django application on Heroku but although the logs show that the build is successful and despite successful deployment the application still shows an internal server e...
Django heroku app successfully deployed but still showing an internal server error, Log files show the build is successful
I am trying to deploy my Django application on Heroku but although the logs show that the build is successful and despite successful deployment the application still shows an internal server error; and this is true with debug set to either true or false. Here are the files that I think are important( also I am using th...
[ "I finally figured out the issue, I had connected my heroku app to a github repository where one of my apps folder was missing some folder and files; so if by any chance you run into any problem of this kind in the future and your build is successful please try to check if you have any missing files and also rememb...
[ 1, 0 ]
[]
[]
[ "django", "heroku", "python" ]
stackoverflow_0074272716_django_heroku_python.txt
Q: MacOS VSCode Python Setup When I run anything other than your print("Hello, World") the terminal prints the following: Traceback (most recent call last): File "/usr/local/Cellar/python@3.10/3.10.8/Frameworks/Python.framework/Versions/3.10/lib/python3.10/runpy.py", line 196, in _run_module_as_main return _run...
MacOS VSCode Python Setup
When I run anything other than your print("Hello, World") the terminal prints the following: Traceback (most recent call last): File "/usr/local/Cellar/python@3.10/3.10.8/Frameworks/Python.framework/Versions/3.10/lib/python3.10/runpy.py", line 196, in _run_module_as_main return _run_code(code, main_globals, None,...
[ "A couple of problems\n\nYour if block needs to be indented to be inside the function.\nYour inputs need to be converted to numeric since you can't do math on string types.\n\nInstead:\nimport math\n#The quadratic is luckily solved for all coefficients a,b,c except for a=0: this diqualifies the equation as quadrati...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074281643_python.txt
Q: How can I make a variable n zeros? So I want to create something like myvariable = n * 0 but I want zeros to repeat N times back to back (not on different lines) the thing i need to do: 00000 How can I do this? A: >>> n = 5 >>> myvariable = n * '0' >>> print(myvariable) 00000 A: if you use multiply operator wi...
How can I make a variable n zeros?
So I want to create something like myvariable = n * 0 but I want zeros to repeat N times back to back (not on different lines) the thing i need to do: 00000 How can I do this?
[ ">>> n = 5\n>>> myvariable = n * '0'\n>>> print(myvariable)\n00000\n\n", "if you use multiply operator with a string in python, It repeats your string n times.\nFor example :\nN = 3\nyourString = \"python\"\n\nwhen you use this code:\nprint(N * yourString)\n\nit will return \"python\" three times:\nOutput: python...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074281872_python.txt
Q: Convert fasta file (.fasta) to count file (.cf) I am trying to convert a fasta file (.fasta) to a count file (.cf) to be able to upload it to IQTREE for use in phylogenetic analysis. The fasta file is a merged file of an alignment and a mapping of the individuals sequenced into one of 5 populations. A sample of th...
Convert fasta file (.fasta) to count file (.cf)
I am trying to convert a fasta file (.fasta) to a count file (.cf) to be able to upload it to IQTREE for use in phylogenetic analysis. The fasta file is a merged file of an alignment and a mapping of the individuals sequenced into one of 5 populations. A sample of this file has been attached. I have tried both R and py...
[]
[]
[ "Take a look at PoMo. Specifically, they publish some scripts for converting files\n\nCountsToFasta.py: Convert a counts file to a fasta file.\nFastaToCounts.py: Convert a fasta file to counts format.\nFastaToVCF.py: Convert a fasta file to variant call format.\nFastaVCFToCounts.py: Convert a fasta reference with V...
[ -1 ]
[ "converters", "fasta", "python" ]
stackoverflow_0074279888_converters_fasta_python.txt
Q: If I do not explicitly specify a whitespace char in my Python regex, why is it still finding a correct match? [Edited] Question: How does the code in the example Option 2 (bottom of page) match an input string with whitespace chars., without explicitly defining the whitespace chars in the regex (I assume it must b...
If I do not explicitly specify a whitespace char in my Python regex, why is it still finding a correct match?
[Edited] Question: How does the code in the example Option 2 (bottom of page) match an input string with whitespace chars., without explicitly defining the whitespace chars in the regex (I assume it must be doing so somehow, or else it would not find a match, and produce the correct output - I just don't know what it i...
[ "I think you have a slight misunderstanding of exactly how both are working, but let's start with 2 as answering how that works provides some illumination on how 1 works.\nWhy does Option 2 work?\nThe following regex (B):\n(?:<iframe[=\\w\\\"]*src=)?\\\"(?:https?://)(?:www\\.)?youtube\\.com/embed/(\\w*)\\\"([\\w=\\...
[ 0 ]
[]
[]
[ "python", "python_re", "regex" ]
stackoverflow_0074256870_python_python_re_regex.txt
Q: Function in python to search for specific word in a text I would like to get know if the person studied maybe at another university. I just gave a random website from bs4 import BeautifulSoup import requests url = 'https://www.liverpool.ac.uk/environmentalsciences/staff/daniel-arribas-bel/' r = requests.get(ur...
Function in python to search for specific word in a text
I would like to get know if the person studied maybe at another university. I just gave a random website from bs4 import BeautifulSoup import requests url = 'https://www.liverpool.ac.uk/environmentalsciences/staff/daniel-arribas-bel/' r = requests.get(url) soup = BeautifulSoup(r.content,'lxml') print(soup.find(tex...
[ "Getting 404 for your url, think you have to be logged in\n\nSimply check if university is in the scraped text:\nif 'university' in soup.find(text='About').find_next('div').get_text(strip=True):\n print(True)\nelse:\n print(False)\n\nAlternative:\nif soup.find(text='About').find_next('div').get_text(strip=Tru...
[ 0 ]
[]
[]
[ "beautifulsoup", "python", "web_scraping" ]
stackoverflow_0074281865_beautifulsoup_python_web_scraping.txt
Q: Convert PySpark dataframe into a list of values I have a PySpark dataframe as shown below. I need to collapse the dataframe rows into a Python dictionary containing column:value pairs. Finally, convert the dictionary into a Python list of tuples as shown below. I am using Spark 2.4. DataFrame: >>> myDF.show() +--...
Convert PySpark dataframe into a list of values
I have a PySpark dataframe as shown below. I need to collapse the dataframe rows into a Python dictionary containing column:value pairs. Finally, convert the dictionary into a Python list of tuples as shown below. I am using Spark 2.4. DataFrame: >>> myDF.show() +------+---+---------+----------+ |fname |age|location |...
[ "For some reason I was unable to use collect() in Spark 2.4. So here are two options, close to what you wanted.\nInputs:\nfrom pyspark.sql import functions as F\ndf = spark.createDataFrame(\n [('John', 45, 'USA', '1985/01/05'),\n ('David', 33, 'England', '2003/05/19'),\n ('Travis', 56, 'Japan', '1976/08/...
[ 1 ]
[]
[]
[ "apache_spark", "dataframe", "list", "pyspark", "python" ]
stackoverflow_0074281389_apache_spark_dataframe_list_pyspark_python.txt
Q: How to add a string to a paragraph after a particular word Python I am trying to insert a string after a specific word in a paragraph. For example: If the word I am looking at is King in the paragraph, I want to add Arthur right after it so it will be like: King Arthur went on a mission for all the lines that has...
How to add a string to a paragraph after a particular word Python
I am trying to insert a string after a specific word in a paragraph. For example: If the word I am looking at is King in the paragraph, I want to add Arthur right after it so it will be like: King Arthur went on a mission for all the lines that has King instead of King went on a mission
[ "This example uses re.sub to substitute King (not followed by Arthur) with King Arthur):\nimport re\n\ns = \"King went on a mission\"\n\ns = re.sub(r\"\\bKing\\b(?!\\s*Arthur)\", \"King Arthur\", s)\nprint(s)\n\nPrints:\nKing Arthur went on a mission\n\n" ]
[ 2 ]
[]
[]
[ "python", "python_re", "string" ]
stackoverflow_0074282041_python_python_re_string.txt
Q: How to make a custom torchvision transform? I have a function that changes image pixels with 20% chance, but not sure how to make it work in transforms.Compose([]). Please help! def random_t(img): im = Image.open(img) pixelMap = im.load() pixelMap_list = [] for i in range(im.size[0]): for ...
How to make a custom torchvision transform?
I have a function that changes image pixels with 20% chance, but not sure how to make it work in transforms.Compose([]). Please help! def random_t(img): im = Image.open(img) pixelMap = im.load() pixelMap_list = [] for i in range(im.size[0]): for j in range(im.size[1]): randNum = ran...
[ "You need to do your operations on img and then return it. For a good example of how to create custom transforms just check out how the normal torchvision transforms are created like over here:\nThis is the github where torchvision.transforms like transforms.Resize(), transforms.ToTensor(), transforms.RandomHorizon...
[ 1, 0 ]
[]
[]
[ "python", "pytorch", "torchvision" ]
stackoverflow_0068415926_python_pytorch_torchvision.txt
Q: Make all line graphs grey using grey scale, apart from one coloured line in Seaborn I need to colour all line graphs in a different grey, using one of Seaborn's greyscale, like binary. One line (2022), however, needs to be orange. This is what I currently have: This is what my code looks like, I have not been abl...
Make all line graphs grey using grey scale, apart from one coloured line in Seaborn
I need to colour all line graphs in a different grey, using one of Seaborn's greyscale, like binary. One line (2022), however, needs to be orange. This is what I currently have: This is what my code looks like, I have not been able to get a grey colour palette to work in there: palette = {year:'orange' if year == 2022...
[ "Maybe something like this:\nyears = sorted(df[\"year\"].unique())\ngreys = iter(sns.color_palette(\"Greys\", len(years)))\npalette = {year: 'orange' if year == 2022 else next(greys) for year in years}\n\n" ]
[ 2 ]
[]
[]
[ "linegraph", "python", "seaborn", "visualization" ]
stackoverflow_0074278515_linegraph_python_seaborn_visualization.txt
Q: Django unit tests. Post data with duplicate keys I'm writing a Django unit test against an app I inherited. In the context of a unit test I am doing something like: data = {'foo':'bar','color':'blue'} self.client.post(url,data=data) However, the app expects muiltiple form data for "color" in the same key in the H...
Django unit tests. Post data with duplicate keys
I'm writing a Django unit test against an app I inherited. In the context of a unit test I am doing something like: data = {'foo':'bar','color':'blue'} self.client.post(url,data=data) However, the app expects muiltiple form data for "color" in the same key in the HTTP request, such as: foo: bar color: orange color: bl...
[ "I hate to answer my own question here, but as soon as I asked I got it to work without using any extra python stuff.\nApparently the Django client post understands will take the following input:\ndata = {'foo':'bar','color':['orange','blue']}\nself.client.post(url,data=data)\n\ninto the desired output.\n" ]
[ 1 ]
[]
[]
[ "dictionary", "django", "python", "testing" ]
stackoverflow_0074281431_dictionary_django_python_testing.txt
Q: cloning git repo from python src = user/my.git dest = /home/git_name ver = 1.1 def run p = subprocess.run(cmd, stdout=PIPE, stderr=PIPE) I am calling this run with the following cmds 1. self.run(['mkdir', '-p', dest]) 2. self.run(['git', 'clone', '--no-checkout',src, dest]) 3. self.run(['cd', dest, ';'...
cloning git repo from python
src = user/my.git dest = /home/git_name ver = 1.1 def run p = subprocess.run(cmd, stdout=PIPE, stderr=PIPE) I am calling this run with the following cmds 1. self.run(['mkdir', '-p', dest]) 2. self.run(['git', 'clone', '--no-checkout',src, dest]) 3. self.run(['cd', dest, ';', 'git', 'checkout', '--detach', v...
[ "I would use sh. Excellent for this kind of stuff.\n>>> import sh\n>>> sh.git.clone(git_repo_url, \"destination\")\n\nIf you want to do fancy stuff like changing into a repo and run commands, you also have cd available as a context manager:\nwith sh.cd(git_repo):\n # do git commands\n\nAlso read this note about...
[ 2, 1, 1 ]
[]
[]
[ "git", "python", "subprocess" ]
stackoverflow_0074146442_git_python_subprocess.txt
Q: How to make "movie_list" function be defined *For my code I have three options: View a list of movies, Add to the list, or delete from the list. My problem is I don't know how to define my movie_list function. Down below you can see what I have written down so far. The menu works but for whenever I type list I kee...
How to make "movie_list" function be defined
*For my code I have three options: View a list of movies, Add to the list, or delete from the list. My problem is I don't know how to define my movie_list function. Down below you can see what I have written down so far. The menu works but for whenever I type list I keep getting an error my_list function is not defined...
[ "list() is already a function in python. When you code calls list(movie_list) it is accessing a list called movie_list then does nothing because you are not doing anything with it. The next thing you will want to do its move your functions to the top of your code. Python runs one line at a time, and your functions ...
[ 0 ]
[]
[]
[ "function", "list", "python" ]
stackoverflow_0074281878_function_list_python.txt
Q: customtkinter - create frame with other class than the main frame but then assign it to the main frame i am trying to create parts of my customtkinter-app in other classes so i can then assign them to the App class. But i must do something wrong. As you can see the goal is to place the labeltext from "self.label" ...
customtkinter - create frame with other class than the main frame but then assign it to the main frame
i am trying to create parts of my customtkinter-app in other classes so i can then assign them to the App class. But i must do something wrong. As you can see the goal is to place the labeltext from "self.label" to the middle of the frame "self.frame_rot" Please check my code: import tkinter import customtkinter as ct...
[ "try this:\nimport tkinter\nimport customtkinter as ctk\n\n \nclass App(ctk.CTk):\n def __init__(self):\n super().__init__()\n \n self.geometry('500x500')\n self.title('TestApp')\n \n self.frame = Frame1(self)\n\nclass Frame1(ctk.CTkFrame):\n def __init__(self,...
[ 0 ]
[]
[]
[ "class", "customtkinter", "inheritance", "python", "tkinter" ]
stackoverflow_0074249432_class_customtkinter_inheritance_python_tkinter.txt
Q: If remove duplicate is clicked yes then pd.dataframe drop_duplicates else keep old pd.dataframe? I'm stuck with this expression: If "deleteDup" is True then execute pd.dataframe drop_duplicates else keep old pd.dataframe? Here is my code and it didn't work: df = df.drop_duplicates() if deleteDup else df = df (dele...
If remove duplicate is clicked yes then pd.dataframe drop_duplicates else keep old pd.dataframe?
I'm stuck with this expression: If "deleteDup" is True then execute pd.dataframe drop_duplicates else keep old pd.dataframe? Here is my code and it didn't work: df = df.drop_duplicates() if deleteDup else df = df (deleteDup is a button that will return True or False.) error when running this code: df = df.drop_duplica...
[ "In else clause you should leave df as is, not explicitly assign it to df:\ndf = df.drop_duplicates() if deleteDup else df\n" ]
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074281564_dataframe_pandas_python.txt
Q: I wanted to understand what this yield does I wanted to understand what this yield does. In the examples I find, I always see this type of code, but I don't understand what it differs from a normal instance def get_db(): db = SessionLocal() try: yield db finally: db.close() This example is in the Fa...
I wanted to understand what this yield does
I wanted to understand what this yield does. In the examples I find, I always see this type of code, but I don't understand what it differs from a normal instance def get_db(): db = SessionLocal() try: yield db finally: db.close() This example is in the FastAPI documentation: https://fastapi.tiangolo.com...
[ "yield is a keyword that is used like return, except the function will return a generator.\nquick example:\ndef fun(num):\n for i in range(num):\n yield i\nx = fun(5)\nprint(x)\n# <generator object create_generator at 0xb7555c34>\nfor object in x:\n print(object)\n\n\"\"\"\nexpected output:\n 0\...
[ 0 ]
[]
[]
[ "fastapi", "generator", "python", "sqlalchemy", "yield" ]
stackoverflow_0073171306_fastapi_generator_python_sqlalchemy_yield.txt
Q: how to code in polars python with the following tidyverse R code? I want migrate my application from R using tidyvers to Python Polars, what equivalent of this code in python polars? new_table <- table1 %>% mutate(no = row_number()) %>% mutate_at(vars(c, d), ~ifelse(no %in% c(2,5,7), replace_na(., 0), .)) %>% ...
how to code in polars python with the following tidyverse R code?
I want migrate my application from R using tidyvers to Python Polars, what equivalent of this code in python polars? new_table <- table1 %>% mutate(no = row_number()) %>% mutate_at(vars(c, d), ~ifelse(no %in% c(2,5,7), replace_na(., 0), .)) %>% mutate(e = table2$value[match(a, table2$id)], f = ifelse(no ...
[ "I expressed the assignment from the other tables as a join (actually I would have done this in tidyverse as well). Otherwise the translation is straight forward. You need:\n\nwith_row_count for the row numbers\nwith_columns to mutate columns\npl.col to reference columns\npl.when.then.otherwise for conditional expr...
[ 3 ]
[]
[]
[ "dplyr", "python", "python_polars", "r", "tidyverse" ]
stackoverflow_0074244440_dplyr_python_python_polars_r_tidyverse.txt
Q: find row positions and column names of cells contanining inf in pandas dataframe How can I retrieve the column names and the rows of all the cells that contain inf in a multicolumns panda datarame df? I have tried inds = np.where(np.isinf(df)==True) but I dont have the expected result A: row positions: df.inde...
find row positions and column names of cells contanining inf in pandas dataframe
How can I retrieve the column names and the rows of all the cells that contain inf in a multicolumns panda datarame df? I have tried inds = np.where(np.isinf(df)==True) but I dont have the expected result
[ "row positions:\ndf.index[np.isinf(df).any(1)]\n\ncolumn names:\ndf.columns.to_series()[np.isinf(df).any()]\n\nDemo:\nIn [163]: df\nOut[163]:\nminor AAPL GS\n Adj Close Volume Adj Close Volume\nDate\n2017-03-01 139.789993 3.627240e+07 252.710007 521830...
[ 29, 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0042790542_dataframe_pandas_python.txt
Q: Loop through all nested dictionary values? for k, v in d.iteritems(): if type(v) is dict: for t, c in v.iteritems(): print "{0} : {1}".format(t, c) I'm trying to loop through a dictionary and print out all key value pairs where the value is not a nested dictionary. If the value is a dictio...
Loop through all nested dictionary values?
for k, v in d.iteritems(): if type(v) is dict: for t, c in v.iteritems(): print "{0} : {1}".format(t, c) I'm trying to loop through a dictionary and print out all key value pairs where the value is not a nested dictionary. If the value is a dictionary I want to go into it and print out its key ...
[ "As said by Niklas, you need recursion, i.e. you want to define a function to print your dict, and if the value is a dict, you want to call your print function using this new dict.\nSomething like :\ndef myprint(d):\n for k, v in d.items():\n if isinstance(v, dict):\n myprint(v)\n else:\...
[ 212, 66, 44, 30, 16, 8, 7, 4, 4, 2, 1, 1, 1, 1, 0, 0, 0, 0 ]
[]
[]
[ "dictionary", "python", "recursion" ]
stackoverflow_0010756427_dictionary_python_recursion.txt
Q: str.cat ignores `na_rep` parameter? The parameter na_rep doesn't have expected effect. It's ignored, actually. My MRE: import pandas as pd import numpy as np df = pd.DataFrame({'x': ['', 'b', 1, 2, 3, 'a'], 'y': [1, 4, 2, np.nan, 4, 7], 'z': [3, 4, 55, 3, 2, 4]}) df['y'].ast...
str.cat ignores `na_rep` parameter?
The parameter na_rep doesn't have expected effect. It's ignored, actually. My MRE: import pandas as pd import numpy as np df = pd.DataFrame({'x': ['', 'b', 1, 2, 3, 'a'], 'y': [1, 4, 2, np.nan, 4, 7], 'z': [3, 4, 55, 3, 2, 4]}) df['y'].astype(str).str.cat(df['x'].astype(str), sep...
[ "The problem seems to be that when converting y to string, NaN basically becomes nan, which is a string representation of NaN and not NaN itself.\nTherefore, na_rep does not work, because it is supposed to operate on actual NaN values and not on its string representation!\nSo, you should ideally convert to string w...
[ 2 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074281827_pandas_python.txt
Q: discord bot sending multiple messages my scheduled message bot code is working but I have no idea how to prevent from sending multiple messages at the same time @Bot.event async def on_ready(): print("Bot is ready") while True: time = datetime.datetime.today() if time.hour == 2: if...
discord bot sending multiple messages
my scheduled message bot code is working but I have no idea how to prevent from sending multiple messages at the same time @Bot.event async def on_ready(): print("Bot is ready") while True: time = datetime.datetime.today() if time.hour == 2: if time.minute == 39: await Bot.ge...
[ "You can use a boolean variable that indicates whether you have already sent the message at 2:39 am.\n@Bot.event\nasync def on_ready():\n print(\"Bot is ready\")\n sent = False\n while True:\n time = datetime.datetime.today()\n if time.hour == 2:\n if time.minute == 39:\n if...
[ 0 ]
[]
[]
[ "discord", "discord.py", "python" ]
stackoverflow_0074282229_discord_discord.py_python.txt
Q: how to convert dictionary where values are stored in a list to df I have a dictionary that I want to convert into DataFrame, the problem I'm having is my dictionary is in the following format: sample_dict = {'test':['test string',['feature1','feature2', 'feature3']]} When trying to convert using something like d...
how to convert dictionary where values are stored in a list to df
I have a dictionary that I want to convert into DataFrame, the problem I'm having is my dictionary is in the following format: sample_dict = {'test':['test string',['feature1','feature2', 'feature3']]} When trying to convert using something like df = pd.DataFrame.from_dict([sample_dict]) I get: What I'm trying to ...
[ "Add orient\nout = pd.DataFrame.from_dict(sample_dict, orient='index')\nOut[287]: \n 0 1\ntest test string [feature1, feature2, feature3]\n\n", "Can use from_records as well.\ndf = pd.DataFrame.from_records(d).T\n\n\n 0 1\...
[ 1, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074282226_pandas_python.txt
Q: PySpark DataFrame writing empty (zero bytes) files I'm working with PySpark DataFrame API with Spark version 3.1.1 on a local setup. After reading in data, performing some transformations etc. I save the DataFrame to disk. Output directories get created, along with part-0000* file and there is _SUCCESS file presen...
PySpark DataFrame writing empty (zero bytes) files
I'm working with PySpark DataFrame API with Spark version 3.1.1 on a local setup. After reading in data, performing some transformations etc. I save the DataFrame to disk. Output directories get created, along with part-0000* file and there is _SUCCESS file present in the output directory as well. However, my part-0000...
[ "So I ran into a similar issue with pyspark and one thing I also noticed is that when I tried to set the mode to overwrite it was also failing. The issue with the overwrite was that it was failing to write while it was in the middle of the write, so it would create the file, fail, retry and the retry would fail wit...
[ 0 ]
[]
[]
[ "apache_spark", "pyspark", "python" ]
stackoverflow_0072202062_apache_spark_pyspark_python.txt
Q: How can I check if two segments intersect? How can I check if 2 segments intersect? I've the following data: Segment1 [ {x1,y1}, {x2,y2} ] Segment2 [ {x1,y1}, {x2,y2} ] I need to write a small algorithm in Python to detect if the 2 lines are intersecting. A: User @i_4_got points to this page with a very effice...
How can I check if two segments intersect?
How can I check if 2 segments intersect? I've the following data: Segment1 [ {x1,y1}, {x2,y2} ] Segment2 [ {x1,y1}, {x2,y2} ] I need to write a small algorithm in Python to detect if the 2 lines are intersecting.
[ "User @i_4_got points to this page with a very efficent solution in Python. I reproduce it here for convenience (since it would have made me happy to have it here):\ndef ccw(A,B,C):\n return (C.y-A.y) * (B.x-A.x) > (B.y-A.y) * (C.x-A.x)\n\n# Return true if line segments AB and CD intersect\ndef intersect(A,B,C,D...
[ 133, 88, 40, 17, 16, 16, 7, 7, 5, 4, 3, 2, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0 ]
[ "Implemented in JAVA. However It seems that it does not work for co-linear lines (aka line segments that exist within each other L1(0,0)(10,10) L2(1,1)(2,2)\npublic class TestCode\n{\n\n public class Point\n {\n public double x = 0;\n public double y = 0;\n public Point(){}\n }\n\n public class Line\n...
[ -1, -2 ]
[ "geometry", "math", "python" ]
stackoverflow_0003838329_geometry_math_python.txt
Q: How Call a Python Websocket from a NFC Scanned on the phone(straight from the phone like with a URL) Ok, no code here, more trying to get some directions. I'm working on my home automation using tuya objects. Till now I was able to create a websocket (using python websockets and asyncio) that gets a message and tu...
How Call a Python Websocket from a NFC Scanned on the phone(straight from the phone like with a URL)
Ok, no code here, more trying to get some directions. I'm working on my home automation using tuya objects. Till now I was able to create a websocket (using python websockets and asyncio) that gets a message and turn on my devices. I created a flask website to configure passwords, keys etc. Now what I'm trying to achie...
[ "The right direction is to write your own NFC app for your phone.\nIn OS has a basic limited (fallback) idea of how to process the different type of Ndef record types, but it mostly relies on App's registering that they are capable for processing a certain record type.\nSo the OS can process various URL formats and...
[ 0, 0 ]
[]
[]
[ "flask", "mobile", "nfc", "python", "websocket" ]
stackoverflow_0074275501_flask_mobile_nfc_python_websocket.txt
Q: How do I run a bash command (in this instance, python running a script) when a specific file changes its name in linux? I have this .AppImage that, when it updates itself, changes its name to match its version. I also have a python script to update a .desktop shortcut with the new file name. Is there any way to de...
How do I run a bash command (in this instance, python running a script) when a specific file changes its name in linux?
I have this .AppImage that, when it updates itself, changes its name to match its version. I also have a python script to update a .desktop shortcut with the new file name. Is there any way to detect the AppImages' name change, then run the python script? I've tried to find a bash command that detects a file's name cha...
[ "I think watchdog is what you're looking for: https://github.com/gorakhargosh/watchdog\nHere's an example from the readme that checks every second for file changes.\nimport sys\nimport time\nimport logging\nfrom watchdog.observers import Observer\nfrom watchdog.events import LoggingEventHandler\n\nif __name__ == \"...
[ 0, 0 ]
[]
[]
[ "bash", "python" ]
stackoverflow_0074281124_bash_python.txt
Q: Requests don't return all of the information I am trying to get data from the products on this site: https://www.blocket.se/annonser/hela_sverige?q=dunjacka When I try to scrape the website using beautifulsoup and requests I only recieve parts of the html code on the website. The sections containing the data about...
Requests don't return all of the information
I am trying to get data from the products on this site: https://www.blocket.se/annonser/hela_sverige?q=dunjacka When I try to scrape the website using beautifulsoup and requests I only recieve parts of the html code on the website. The sections containing the data about the products is not extracted. My code is this, i...
[ "The data you see on the page is loaded from external URL via Javascript. You can simulate it via requests/json modules:\nimport re\nimport json\nimport requests\n\nurl = \"https://api.blocket.se/search_bff/v2/content\"\n\nparams = {\n \"lim\": \"40\",\n \"q\": \"dunjacka\",\n \"st\": \"s\",\n \"status\...
[ 0 ]
[]
[]
[ "beautifulsoup", "html", "python", "python_requests", "web_scraping" ]
stackoverflow_0074282327_beautifulsoup_html_python_python_requests_web_scraping.txt
Q: Using datetime and getting " at 0x7f1463aeec80>" I am coding a web scraper and and my code keeps printing <generator object at 0x7f1463aeec80> dates_with_monthname = re.findall( r'((?:January|February|March|April|May|June|July|August|September|October|November|December)\s\d{1,2})', str(text) ) while i<le...
Using datetime and getting " at 0x7f1463aeec80>"
I am coding a web scraper and and my code keeps printing <generator object at 0x7f1463aeec80> dates_with_monthname = re.findall( r'((?:January|February|March|April|May|June|July|August|September|October|November|December)\s\d{1,2})', str(text) ) while i<len(dates_with_monthname): i=i+1 Date_List = (datet...
[ "try appending\nprint(list(Date_List))\n" ]
[ 0 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0074282351_datetime_python.txt
Q: Reading from a pipe and buffer contains only one byte after read when it should contain more I am trying to read from a pipe. I successfully opened the pipe and wrote to it, but for some reason, I am having trouble reading from it. There are no errors, but the bytes_read object indicates that 368 bytes were read, ...
Reading from a pipe and buffer contains only one byte after read when it should contain more
I am trying to read from a pipe. I successfully opened the pipe and wrote to it, but for some reason, I am having trouble reading from it. There are no errors, but the bytes_read object indicates that 368 bytes were read, while the buffer only contains one byte. I took a look at other examples using the function in Pyt...
[ "Use .raw instead of .value when reading a byte buffer. .value only reads a null-terminated string. You're seeing one byte because the next byte is a null. Here's a fix:\ndef read_file(handle, size):\n buf = ct.create_string_buffer(size) # also works\n bytes_read = DWORD() # 0 is the default...
[ 1 ]
[]
[]
[ "ctypes", "python", "winapi" ]
stackoverflow_0074272422_ctypes_python_winapi.txt
Q: Looking for a very specific regex, between two dashes, after a dash I am trying to find a regex that will pull out information between two dashes, but after a dash has already existed. I will list a few examples: a = BRAND NAME - 34953 Some Information, PPF - 00003 - (3.355pz.) 300% b = 893535 - MX LMESJFG - 0100...
Looking for a very specific regex, between two dashes, after a dash
I am trying to find a regex that will pull out information between two dashes, but after a dash has already existed. I will list a few examples: a = BRAND NAME - 34953 Some Information, PPF - 00003 - (3.355pz.) 300% b = 893535 - MX LMESJFG - 01001 - ST2 | ls.33.dg - OK c = 4539883 - AB05 - AG03J238B - | D.87.yes.4/3 -...
[ "We can stick to the base string functions here and use split() and strip():\na = \"BRAND NAME - 34953 Some Information, PPF - 00003 - (3.355pz.) 300%\"\nmatch = a.split(\"-\")[2].strip()\nprint(match) # 00003\n\n", "Little late to the party, but the following python regular expression should find all occurrence...
[ 3, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0074270901_python_regex.txt
Q: Python - How to compare strings to ensure they do not contain a double character, then save them to a file I am trying to make it so that if there are 2 words that have double letters in the loop, it will simply pass over them, or vice versa. def initalizeData(): try: words = open('words.txt', 'r') ...
Python - How to compare strings to ensure they do not contain a double character, then save them to a file
I am trying to make it so that if there are 2 words that have double letters in the loop, it will simply pass over them, or vice versa. def initalizeData(): try: words = open('words.txt', 'r') except FileNotFoundError: print("Check the file name or path.") else: list = open('final.tx...
[ "You can iterate through the letters of the word using the pattern below. This will check that all pairs of letters are different in the word. And I also changed the file name to word_list to avoid the name collision with list.\ndef initalizeData():\n try:\n words = open('words.txt', 'r')\n except Fi...
[ 0 ]
[]
[]
[ "python", "replit" ]
stackoverflow_0074282241_python_replit.txt
Q: Dynamically define the (keyword) arguments to a function? Is it possible to define the keyword arguments to a function dynamically? Normally you have something like this: def f(a=None, b=None): return locals() What I want is to define a function with the keyword args from a dict; so this would give the same f...
Dynamically define the (keyword) arguments to a function?
Is it possible to define the keyword arguments to a function dynamically? Normally you have something like this: def f(a=None, b=None): return locals() What I want is to define a function with the keyword args from a dict; so this would give the same function as above: dyn_args = {'a': None, 'b': None} def f(?magi...
[ "It seems fastcore's use_kwargs decorator does just what you're asking for:\nhttps://fastcore.fast.ai/meta.html#use_kwargs\nTo see how this is implemented, you can just have a look at its code in github:\nhttps://github.com/fastai/fastcore/blob/master/fastcore/meta.py#L95\nThere is also a similar decorator, use_kwa...
[ 0 ]
[]
[]
[ "function", "metaprogramming", "python" ]
stackoverflow_0033158051_function_metaprogramming_python.txt
Q: When I use sympy.solve I get the error "IndexError: list index out of range" in Python I want to get an expression i.t.o B but I get the given error, everything else works fine. Don't really know whats happening if you guys could help I would really apreciate. Literaly everything works until the last line of code....
When I use sympy.solve I get the error "IndexError: list index out of range" in Python
I want to get an expression i.t.o B but I get the given error, everything else works fine. Don't really know whats happening if you guys could help I would really apreciate. Literaly everything works until the last line of code. So you can like ignore the whole big batch of code you can just look at the last few lines....
[ "Your equation has no solutions for almost all possible values of the parameters. Here it is:\nIn [10]: Equation\nOut[10]: \n 4 ⎛ 2 ⎞\n P⋅a 3 ⎛L⋅P P⋅a⎞ ⎜ L⋅P⋅a 3⎟\n-B⋅a + ──── - a ⋅⎜─── - ───⎟ + a⋅⎜B + ────── - P⋅a ⎟\n 6 ⎝ 6 6 ⎠ ...
[ 1 ]
[]
[]
[ "python", "solver", "sympy" ]
stackoverflow_0074280701_python_solver_sympy.txt
Q: Problems with modifying lines in TXT with regex I'm having problems in "evolving" a script to clean lines of a TXT, attached example of TXT: Fri Oct 14 22:27:49.100 EDT Interface Status Protocol Description -------------------------------------------------------------------------------- Lo0 ...
Problems with modifying lines in TXT with regex
I'm having problems in "evolving" a script to clean lines of a TXT, attached example of TXT: Fri Oct 14 22:27:49.100 EDT Interface Status Protocol Description -------------------------------------------------------------------------------- Lo0 up up Loopback0 interface...
[ "I don't think regular expressions really make a difference here, except maybe to parse the headings so you can know at which index the data for a given column will start:\nspans = []\nresult = []\nwith open(txt, \"r\") as f:\n it = iter(f.readlines()) \n # Skip lines until headings are found\n for line...
[ 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0074267519_python_regex.txt
Q: Comparison of two numbers I'm trying to make a program that will check if two numbers have the same digits but in different order. For example, 232 and 223 will print "true" but 123 and 223 will print "false". Now I have no mistakes but the answer should be "true" and it's not: my code: a=322 b=223 list_a = list...
Comparison of two numbers
I'm trying to make a program that will check if two numbers have the same digits but in different order. For example, 232 and 223 will print "true" but 123 and 223 will print "false". Now I have no mistakes but the answer should be "true" and it's not: my code: a=322 b=223 list_a = list(str(a)) list_b = list(str(b)) ...
[ "Something like this seems like an obvious way:\n#!/usr/bin/python\n\ndef same_digits(a, b):\n if sorted(str(a)) == sorted(str(b)):\n print \"{0} and {1} contain the same digits\".format(a, b)\n else:\n print \"{0} and {1} do not contain the same digits\".format(a, b)\n\nsame_digits(232, 232)\ns...
[ 6, 1, 0, 0, 0 ]
[ "I think it helps\n a = 323\n b = 233\n\n al = [c for c in str(a)]\n bl = [c for c in str(b)]\n\n print sorted(al) == sorted(bl)\n\n" ]
[ -1 ]
[ "python", "string_comparison" ]
stackoverflow_0019607329_python_string_comparison.txt
Q: How to send several messages by the same socket? I want to send several independent messages from a client to a server, depending on a variable that changes. To simulate the scenario I have created a loop to send several numbers, but only the first iteration is working. In the second iteration (which would be, the...
How to send several messages by the same socket?
I want to send several independent messages from a client to a server, depending on a variable that changes. To simulate the scenario I have created a loop to send several numbers, but only the first iteration is working. In the second iteration (which would be, the second message in real) I am getting this error in th...
[ "If you want to send bytes to a socket, you must have a socket open (server) and be connected to it (client) from the start (your most likely first loop iteration) until the end of whatever you are trying to send (end of loop/array/bytes). Afterwards you are free to decommission the resources be it closing the conn...
[ 0, 0 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0074281888_python_sockets.txt
Q: Setting same axis in all subplots I want that all 6 subplots of my data have the same values on the y-axis (for better comparison): I have the following code: fig, axs = plt.subplots(2, 3, figsize=(15,15)) axs[0,0].plot(drawdown[['Monthly Return Q1']] ) axs[0,0].set_title('Monthly Return Q1') axs[0,0].set_ylabel...
Setting same axis in all subplots
I want that all 6 subplots of my data have the same values on the y-axis (for better comparison): I have the following code: fig, axs = plt.subplots(2, 3, figsize=(15,15)) axs[0,0].plot(drawdown[['Monthly Return Q1']] ) axs[0,0].set_title('Monthly Return Q1') axs[0,0].set_ylabel("percentage") axs[0,0].grid() axs[0,0...
[ "you just need to modify the ylim of each axes, you can do it separately for each one.\naxs[0,0].set_ylim(custom_ylim)\n\nor in a for loop.\nfor item in axs.flatten():\n item.set_ylim(custom_ylim)\n\n" ]
[ 0 ]
[]
[]
[ "analysis", "matplotlib", "numpy", "plot", "python" ]
stackoverflow_0074282544_analysis_matplotlib_numpy_plot_python.txt
Q: How to prevent 2 python turtles in "movement" from flickering when coliding For a school projet that wants us to use python turtle but no external libraries (that you have to install from command line), I firstly made a car that can move following a few tutorials. The car worked perfectly. I then tried to add mult...
How to prevent 2 python turtles in "movement" from flickering when coliding
For a school projet that wants us to use python turtle but no external libraries (that you have to install from command line), I firstly made a car that can move following a few tutorials. The car worked perfectly. I then tried to add multiple cars. Because I couldn't use multi threading libraries, I succesfully used t...
[ "Usage of exec() in Python should be avoided and as replacement of several numbered variables you use in Python a list of Python objects which can be then indexed by an integer number from a given range().\nThe turtle modules Turtle() is capable of showing the turtle in a form of a square, so using this instead of...
[ 0, 0 ]
[]
[]
[ "collision", "python", "python_3.x", "python_turtle", "turtle_graphics" ]
stackoverflow_0074281263_collision_python_python_3.x_python_turtle_turtle_graphics.txt
Q: How to define a matrix before creating it? how can I define this matrix prior to or after it's been created so that I can then perform other operations on it? The problem is that the matrix is created after the user input so I can't just type it in myself. the n is asking user for a number that is then used to cre...
How to define a matrix before creating it?
how can I define this matrix prior to or after it's been created so that I can then perform other operations on it? The problem is that the matrix is created after the user input so I can't just type it in myself. the n is asking user for a number that is then used to create a matrix of n x n dimensions. n = int(input(...
[ "import numpy as np\n\nn = int(input(\"number: \"))\na = np.zeros((n, n), int)\nnp.fill_diagonal(a, 1)\nprint(a)\n\nEDIT\nAs @Reinderien said in a comment section it's easier to do this with np.eye() function\nimport numpy as np\n\nn = int(input(\"number: \"))\na = np.eye(n)\nprint(a)\n\n" ]
[ 0 ]
[]
[]
[ "input", "matrix", "numpy", "python" ]
stackoverflow_0074282444_input_matrix_numpy_python.txt
Q: Read specified amount of lines compute a total then continue reading How do i get a function to read a certain amount of lines and then compute a total by adding up the numbers from those lines printing it then looping to read the next lines etc. The function opens up a file that has hundreds of lines with numbers...
Read specified amount of lines compute a total then continue reading
How do i get a function to read a certain amount of lines and then compute a total by adding up the numbers from those lines printing it then looping to read the next lines etc. The function opens up a file that has hundreds of lines with numbers on them. Example: def open_input_file(): while True: name_of_...
[ "import sys\n\n\ndef open_input_file():\n\nfile_wanted = None\nwhile file_wanted is None:\n name_of_file = input(\"Enter the name of the input file: \")\n try:\n file_wanted = open(name_of_file, 'r', encoding=\"utf-8\")\n return file_wanted\n except FileNotFoundError:\n print(f\"The fi...
[ 1, 0 ]
[]
[]
[ "list", "loops", "python" ]
stackoverflow_0074188737_list_loops_python.txt
Q: Python return the row length for first record I have code that will go through a text file and determine different types of rows based on category and in one case type field in that specific row. Next, for each category (i.e. paying customers), I want to return the row length for just the first row. Currently the ...
Python return the row length for first record
I have code that will go through a text file and determine different types of rows based on category and in one case type field in that specific row. Next, for each category (i.e. paying customers), I want to return the row length for just the first row. Currently the code is reading through all the rows that meets thi...
[ "I would do like this: break once both vars are true\nfile = \"testfile.txt\"\n\n\nread_row_paying_c, read_row_terminated_c = False, False\nwith open(file) as f:\n for line in f:\n if read_row_paying_c and read_row_terminated_c:\n break\n new_line = line.rstrip()\n category = line...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074282578_python.txt
Q: Pandas: get a value from previous year for the same day of the year I'm looking for a way how to get a value from the previous year for the same day. F.e. we have a value for 2014-01-01 and I want to create a new column with the value for this day but from one year ago. a sample of the table, and I want to get t...
Pandas: get a value from previous year for the same day of the year
I'm looking for a way how to get a value from the previous year for the same day. F.e. we have a value for 2014-01-01 and I want to create a new column with the value for this day but from one year ago. a sample of the table, and I want to get the Previos_Year column. Date Ticks Previos_Year 2013-01-01 0 ...
[ "You can groupby month and day, then shift i.e \ndf['Previous'] = df.groupby([df['Date'].dt.month,df['Date'].dt.day])['Value'].shift()\n\nSample Output :\n Date Ticks Value Previous\n0 2013-01-01 0 99 NaN\n1 2013-01-02 1 0 NaN\n2 2013-01-03 2 5 NaN\n3 2014-01...
[ 11, 1 ]
[]
[]
[ "pandas", "python", "time_series" ]
stackoverflow_0047531300_pandas_python_time_series.txt
Q: Poetry configuration is invalid - Additional properties are not allowed ('group' was unexpected) Recently, I faced this issue with Poetry. All my commands using poetry were failing with the following error. RuntimeError The Poetry configuration is invalid: - Additional properties are not allowed ('group' wa...
Poetry configuration is invalid - Additional properties are not allowed ('group' was unexpected)
Recently, I faced this issue with Poetry. All my commands using poetry were failing with the following error. RuntimeError The Poetry configuration is invalid: - Additional properties are not allowed ('group' was unexpected)
[ "I figured out the following issue.\n\nThe code owners had updated the poetry core requirement to requires = [\"poetry-core>=1.2.0\"]\nMy current poetry version was 1.1.12\n\nI did the following to fix my issue.\n# remove the current poetry installation\nrm -rf /Users/myusername/.poetry\n\n# upgrade poetry version\...
[ 9, 3 ]
[]
[]
[ "python", "python_poetry" ]
stackoverflow_0073876790_python_python_poetry.txt
Q: Find the closest value of each value in a column compared to another column in the same PySpark dataframe with exclusion criteria I have two pyspark dataframes like shown below: dfamr = spark.read.csv("/C:/Sushant Workspace/Tech/Self/pyspark datasets/amrrates.csv", header="true") dfexclusion = spark.read.csv("/C:...
Find the closest value of each value in a column compared to another column in the same PySpark dataframe with exclusion criteria
I have two pyspark dataframes like shown below: dfamr = spark.read.csv("/C:/Sushant Workspace/Tech/Self/pyspark datasets/amrrates.csv", header="true") dfexclusion = spark.read.csv("/C:/Sushant Workspace/Tech/Self/pyspark datasets/exclusionrates.csv", header="true") dfamr.show() dfexclusion.show() The task is to f...
[ "Input dataframes:\nfrom pyspark.sql import functions as F, Window as W\ndfamr = spark.createDataFrame(\n [( 'R1', 4.0, 3.60, 3.2),\n ( 'R2', 4.5, 4.05, 3.6),\n ( 'R3', 5.0, 4.50, 4.0),\n ( 'R4', 5.5, 4.95, 4.4),\n ( 'R5', 6.0, 5.40, 4.8),\n ( 'R6', 6.5, 5.85, 5.2),\n ( 'R7', 7.0, 6.30, 5...
[ 0 ]
[]
[]
[ "apache_spark", "closest", "dataframe", "pyspark", "python" ]
stackoverflow_0074282008_apache_spark_closest_dataframe_pyspark_python.txt
Q: Add new column based on values of another column in python I have a dataset like these Name Position Simon Chef David Assistant Chef Philipp Collegial Chef Rafael Assistant Chef Gregory Collegial Chef Dani Assistant Fellow Diego Collegial Fellow Patrick Assistant Fellow Robert Collegial Fellow Glen Chef...
Add new column based on values of another column in python
I have a dataset like these Name Position Simon Chef David Assistant Chef Philipp Collegial Chef Rafael Assistant Chef Gregory Collegial Chef Dani Assistant Fellow Diego Collegial Fellow Patrick Assistant Fellow Robert Collegial Fellow Glen Chef Michael Assistant Chef William Collegial Che...
[ "Option 1\nUse Series.str.split with expand parameter set to True. Select the first column from the result and chain Series.replace to replace \"Chef\" with \"One\".\nimport pandas as pd\n\ndata = {'Name': {0: 'Simon', 1: 'David', 2: 'Philipp', 3: 'Rafael', \n 4: 'Gregory', 5: 'Dani', 6: 'Diego', 7:...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074282562_pandas_python.txt
Q: Remove text between () and [] I have a very long string of text with () and [] in it. I'm trying to remove the characters between the parentheses and brackets but I cannot figure out how. The list is similar to this: x = "This is a sentence. (once a day) [twice a day]" This list isn't what I'm working with but is...
Remove text between () and []
I have a very long string of text with () and [] in it. I'm trying to remove the characters between the parentheses and brackets but I cannot figure out how. The list is similar to this: x = "This is a sentence. (once a day) [twice a day]" This list isn't what I'm working with but is very similar and a lot shorter.
[ "You can use re.sub function.\n>>> import re \n>>> x = \"This is a sentence. (once a day) [twice a day]\"\n>>> re.sub(\"([\\(\\[]).*?([\\)\\]])\", \"\\g<1>\\g<2>\", x)\n'This is a sentence. () []'\n\nIf you want to remove the [] and the () you can use this code:\n>>> import re \n>>> x = \"This is a sentence. (once ...
[ 143, 27, 19, 13, 5, 2, 0, 0 ]
[]
[]
[ "python", "python_2.7" ]
stackoverflow_0014596884_python_python_2.7.txt
Q: app.callback won't update component in dash This is a link to a github repo with the full code, I will only include here the pieces of code that are relevant. If you would like to test the web app, I have included a csv file in the repo which you should use when uploading a file. The app.callback won't update the ...
app.callback won't update component in dash
This is a link to a github repo with the full code, I will only include here the pieces of code that are relevant. If you would like to test the web app, I have included a csv file in the repo which you should use when uploading a file. The app.callback won't update the dash_split_pane and I'm not sure why. Any help wo...
[ "I just needed to make a simple change to how I structured children. See below.\n@app.callback(Output('splitter', 'children'), # change layout to output-plot\n Input('upload-data', 'contents'),\n State('upload-data', 'filename'),\n State('table-container_3', 'data'), prevent_i...
[ 0 ]
[]
[]
[ "plotly_dash", "python" ]
stackoverflow_0074280566_plotly_dash_python.txt
Q: All pairwise means between elements of 2 lists Is there a function to all pairwise means (or sums, etc) of 2 lists in python? I can write a nested loop to do this: import numpy as np A = [1,2,3] B = [8,12,11] C = np.empty((len(A),len(B))) for i, x in enumerate(A): for j, y in enumerate(B): C[i][j] = ...
All pairwise means between elements of 2 lists
Is there a function to all pairwise means (or sums, etc) of 2 lists in python? I can write a nested loop to do this: import numpy as np A = [1,2,3] B = [8,12,11] C = np.empty((len(A),len(B))) for i, x in enumerate(A): for j, y in enumerate(B): C[i][j] = np.mean([x,y]) result: array([[4.5, 6.5, 6. ], ...
[ "Are you using numpy? If so, you can broadcast your arrays and acheive this in one line.\nimport numpy as np\n\nA = [1,2,3]\nB = [8,12,11]\n\nC = (np.reshape(A, (-1, 1)) + B) / 2 # Here B will be implicitly converted to a numpy array. Thanks to @Jérôme Richard.\n\n", "A = [1, 2, 3]\nB = [8, 12, 11]\nC = np.add.ou...
[ 3, 3, 1, 1 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074278168_numpy_python.txt
Q: How to handle dictionary in JSON file to txt file I have sample.json file which includes code in the c lang dataset represented as a dictionary { "0_0": "int curl_mvsprintf ( char * buffer , const char * format , va_list ap_save ) {\n int retcode ;\n retcode = dprintf_formatf ( & buffer , storebuffer , format ,...
How to handle dictionary in JSON file to txt file
I have sample.json file which includes code in the c lang dataset represented as a dictionary { "0_0": "int curl_mvsprintf ( char * buffer , const char * format , va_list ap_save ) {\n int retcode ;\n retcode = dprintf_formatf ( & buffer , storebuffer , format , ap_save ) ;\n * buffer = 0 ;\n return retcode ;\n }", ...
[ "like this?\nimport json\n\nwith open(\"sample.json\", \"r\") as f:\n sample_dict = json.load(f)\n\noutput_str = \"\"\n\nfor key, val in sample_dict.items():\n if key.endswith(\"0\"):\n output_str += \"label1\\t\"\n else:\n output_str += \"label2\\t\"\n \n output_str += val + \"\\n\"\n\...
[ 1 ]
[]
[]
[ "json", "pandas", "python" ]
stackoverflow_0074282368_json_pandas_python.txt
Q: Test if function or method is normal or asynchronous How can I find out if a function or method is a normal function or an async function? I would like my code to automatically support normal or async callbacks and need a way to test what type of function is passed. async def exampleAsyncCb(): pass def exampl...
Test if function or method is normal or asynchronous
How can I find out if a function or method is a normal function or an async function? I would like my code to automatically support normal or async callbacks and need a way to test what type of function is passed. async def exampleAsyncCb(): pass def exampleNomralCb(): pass def isAsync(someFunc): #do cool...
[ "Use the inspect module of Python.\ninspect.iscoroutinefunction(object)\n\nReturn true if the object is a coroutine function (a function defined with an async def syntax).\n\nThis function is available since Python 3.5.\nThe module is available for Python 2 with lesser functionalities and certainly without the one ...
[ 73, 54, 43, 26, 2, 1, 0, 0 ]
[]
[]
[ "asynchronous", "coroutine", "python", "python_3.5", "python_3.x" ]
stackoverflow_0036076619_asynchronous_coroutine_python_python_3.5_python_3.x.txt
Q: Calculating Average True Range (ATR) on OHLC data with Python The ATR is the average of the True Range for a given period. True Range is (High-Low) meaning I have computed this with the following: df['High'].subtract(df['Low']).rolling(distance).mean() However if a short period (or 'distance' in the example above...
Calculating Average True Range (ATR) on OHLC data with Python
The ATR is the average of the True Range for a given period. True Range is (High-Low) meaning I have computed this with the following: df['High'].subtract(df['Low']).rolling(distance).mean() However if a short period (or 'distance' in the example above) is required the ATR can be very jumpy, i.e. with large sporadic g...
[ "For anyone else looking on how to do this, here is my answer.\ndef wwma(values, n):\n \"\"\"\n J. Welles Wilder's EMA \n \"\"\"\n return values.ewm(alpha=1/n, adjust=False).mean()\n\ndef atr(df, n=14):\n data = df.copy()\n high = data[HIGH]\n low = data[LOW]\n close = data[CLOSE]\n data...
[ 41, 12, 0, 0 ]
[ "Just a disclaimer about TR calculation: it actualy is the biggest value of those 3 options:\n\nPresent High - Present Low;\nabs(Present High - Last Close);\nabs(Present Low - Last Close);\n\nYou can get it several ways in python, here I present the way I coded:\ndf['TR'] = [max(tup) for tup in list(zip(df['High']...
[ -1 ]
[ "dataframe", "pandas", "python" ]
stackoverflow_0040256338_dataframe_pandas_python.txt
Q: docker client and server containers connection refused I want to connect client image and server image. So I tried to use --link, docker-compose.yml, but I failed. However, when I tried to connect local client code and server container, it succeed. I think it may be a problem of Dockerfile, but I can't fix it.. th...
docker client and server containers connection refused
I want to connect client image and server image. So I tried to use --link, docker-compose.yml, but I failed. However, when I tried to connect local client code and server container, it succeed. I think it may be a problem of Dockerfile, but I can't fix it.. these are my code: ---server import socket HOST = socket.geth...
[ "Your code works for me.\nYou don't include the commands that you tried. These would be helpful additions to your question.\nBuild both containers. I using different Dockerfile names to disambiguate between the two.\nQ=\"74282751\"\n\ndocker build \\\n--tag=${Q}:server \\\n--file=./Dockerfile.server \\\n${PWD}\n\nd...
[ 0 ]
[]
[]
[ "docker", "python", "sockets" ]
stackoverflow_0074282751_docker_python_sockets.txt
Q: Writing code for main function in order to find sum of digits in a number I need to write a short program that asks for positive integer, reads the number and then prints results of operations by both functions. I've already written both fuctions which look like this: def sumdigits(n): sum = 0 while (...
Writing code for main function in order to find sum of digits in a number
I need to write a short program that asks for positive integer, reads the number and then prints results of operations by both functions. I've already written both fuctions which look like this: def sumdigits(n): sum = 0 while (n != 0): sum = sum + (n % 10) n = n//10 ret...
[ "One option is to use inner functions. For example:\ndef sumdigits(n):\n def loop(n):\n sum = 0\n while (n != 0):\n sum = sum + (n % 10)\n n = n//10\n return sum\n def recurse(n):\n return 0 if n == 0 else int(n % 10) + recurse(int(n / 10)) \n return loop(n...
[ 1 ]
[]
[]
[ "geany", "python" ]
stackoverflow_0074282736_geany_python.txt
Q: Count visitor with same id but different name and show it I have a dataframe: df1 = pd.DataFrame({'id': ['1','2','2','3','3','4','4'], 'name': ['James','Jim','jimy','Daniel','Dane','Ash','Ash'], 'event': ['Basket','Soccer','Soccer','Basket','Soccer','Basket','Soccer']}) I w...
Count visitor with same id but different name and show it
I have a dataframe: df1 = pd.DataFrame({'id': ['1','2','2','3','3','4','4'], 'name': ['James','Jim','jimy','Daniel','Dane','Ash','Ash'], 'event': ['Basket','Soccer','Soccer','Basket','Soccer','Basket','Soccer']}) I want to count unique values of id but with the name, the result ...
[ "You could try:\ndf1.groupby('id').agg(\n name=('name', lambda x: ', '.join(x.unique())),\n count=('name', 'count')\n)\n\nWe are basically grouping by id and then joining the unique names to a comma separated list!\n", "Here is a solution:\ngroups = df1[[\"id\", \"name\"]].groupby(\"id\")\na = groups.agg(la...
[ 3, 2 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074282628_dataframe_pandas_python.txt
Q: Pandas iterate over a DataFrame to get the values from columns according to conditions and put them in a new DataFrame here are some lines from my DataFrame composed as follows : Index ['TimeStamp'] ['ThreadID'] ['Start|End'] ['StepIdentifier'] 1017 18:44:22,997 [12] Start FetchMasterData 1018 18:44:22,997 [12] St...
Pandas iterate over a DataFrame to get the values from columns according to conditions and put them in a new DataFrame
here are some lines from my DataFrame composed as follows : Index ['TimeStamp'] ['ThreadID'] ['Start|End'] ['StepIdentifier'] 1017 18:44:22,997 [12] Start FetchMasterData 1018 18:44:22,997 [12] Start GetSmrCalculatedMeterData 1020 18:44:22,997 [12] End GetSmrCalculatedMeterData 1021 18:44:22,997 [12] Start GetSmrPhysic...
[ "If you'd like to have the same StepIdentifier for the same ThreadID, then you could try something like this:\n# sorting to make sure that the start and end time of the same process that took place on the same thread are one below the other\ndf = df.sort_values(by=['ThreadID', 'StepIdentifier', 'Timestamp'])\n\n# a...
[ 2, 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074282411_dataframe_pandas_python.txt
Q: How to use a custom scoring function in GridSearchCV for unsupervised learning I want to grid search over a set of hyper parameters to tune a clustering model. GridSearchCV offers a bunch of scoring functions for unsupervised learning but I want to use a function that's not in there, e.g. silhouette score. The doc...
How to use a custom scoring function in GridSearchCV for unsupervised learning
I want to grid search over a set of hyper parameters to tune a clustering model. GridSearchCV offers a bunch of scoring functions for unsupervised learning but I want to use a function that's not in there, e.g. silhouette score. The documentation on how to implement my custom function is unclear on how we should define...
[ "Your model must have a .fit_predict() method to get the labels (using .labels_ won't work). Then your scorer function must return a single value where greater value is better1. All clustering algorithms on scikit-learn implement .fit_predict(), so no problem on that front.\nFor example, to implement silhouette sco...
[ 0 ]
[]
[]
[ "cluster_analysis", "grid_search", "machine_learning", "python", "scikit_learn" ]
stackoverflow_0074282892_cluster_analysis_grid_search_machine_learning_python_scikit_learn.txt
Q: my x and y values ' have different dimensions.' how to solve? i am trying to graph a function using the following code in python, for my class's homework assignment: %matplotlib inline import nbconvert import matplotlib.pyplot as plt import numpy as np import math from math import exp Eg=1.1 # eV Bandgap ...
my x and y values ' have different dimensions.' how to solve?
i am trying to graph a function using the following code in python, for my class's homework assignment: %matplotlib inline import nbconvert import matplotlib.pyplot as plt import numpy as np import math from math import exp Eg=1.1 # eV Bandgap of Silicon\n", er=11.9 # relative permitivity of Si\n", eo=8...
[ "Welcome to StackOverflow!!\nFound the mistake: on Line45 (return of the function), you wrote \"return J,\". Apparently, that messed up the value returned.\nYou wrote:\n#----------------------Your code--------------------------------\ndef J(V): # This defines your function (equation) for calculating J vs V\\n\",...
[ 0 ]
[]
[]
[ "graph", "python" ]
stackoverflow_0074282839_graph_python.txt
Q: Django return JsonResponse and continue I have this function in Django and I want that when ever the return JsonResponse(payload) is executed, Django should continue to execute the rest of the code but the rest of the code is rather not def paytes(request): payload ={ "USERID": code_id, ...
Django return JsonResponse and continue
I have this function in Django and I want that when ever the return JsonResponse(payload) is executed, Django should continue to execute the rest of the code but the rest of the code is rather not def paytes(request): payload ={ "USERID": code_id, "MSISDN": serviceCode, ...
[ "All the code after the first return statement is executed won't be executed, so if you want to return both of those variables then put them inside the same dictionary and return that:\nreturn_val = {}\nreturn_val['payload'] = payload\nreturn_val['response'] = res\nreturn JsonResponse(return_val)\n\n" ]
[ 0 ]
[]
[]
[ "django", "django_forms", "django_views", "python" ]
stackoverflow_0074282721_django_django_forms_django_views_python.txt
Q: Assign random numbers in a grid with no duplicates in Python I have 16 variables arranged in a 4 by 4 grid. My goal is to make a function that can assigns a random number between 0 and 4 to every variables, with no duplicates in each column and each row - like a sudoku. Each method I've tried results in duplicates...
Assign random numbers in a grid with no duplicates in Python
I have 16 variables arranged in a 4 by 4 grid. My goal is to make a function that can assigns a random number between 0 and 4 to every variables, with no duplicates in each column and each row - like a sudoku. Each method I've tried results in duplicates. For example: column_A = [A1, A2, A3, A4] column_B = [B1, B2, B3,...
[ "You just need to create a \"baseline\" grid, where no two rows or columns are the same. For example, for a grid of size 4x4, the baseline would be:\n[[1, 2, 3, 4],\n [4, 1, 2, 3],\n [3, 4, 1, 2],\n [2, 3, 4, 1]]\n\nThen shuffle the rows, then shuffle the columns.\nPure python:\nrandom.shuffle only shuffles the ele...
[ 3, 1, 0 ]
[]
[]
[ "duplicates", "python", "random" ]
stackoverflow_0074282738_duplicates_python_random.txt
Q: Changing a column value in pandas if value in other column matches string So, I'm a beginner to Pandas and I'm having a little trouble getting something to work. My task is that I was given a dataframe as follows: AnimalID Pet Name Pet Type 1 Whiskers Cat 2 Charlie Dog 3 Spot Dog 4 Honey Cat What I'm attempt...
Changing a column value in pandas if value in other column matches string
So, I'm a beginner to Pandas and I'm having a little trouble getting something to work. My task is that I was given a dataframe as follows: AnimalID Pet Name Pet Type 1 Whiskers Cat 2 Charlie Dog 3 Spot Dog 4 Honey Cat What I'm attempting to do is add a '+' symbol to the end of the ID if the pet type ...
[ "You can apply Series.where to column AnimalID. Its values will be replaced where the condition is False, so we will need to check Series.ne to add + for each row where this column equals Dog.\ndf['AnimalID'] = df['AnimalID'].where(df['Pet Type'].ne('Dog'), \n df['AnimalID'].ast...
[ 2, 2 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074282875_dataframe_pandas_python.txt
Q: Django how to hyperlink to images in static folder by ticker symbol? I have a table of ETF tickers, ETF names, and their Index names. I want each entry in the table to be clickable and linked to their associated images in the static/images folder. Each image is named after each ETF's index ticker. So when a user c...
Django how to hyperlink to images in static folder by ticker symbol?
I have a table of ETF tickers, ETF names, and their Index names. I want each entry in the table to be clickable and linked to their associated images in the static/images folder. Each image is named after each ETF's index ticker. So when a user clicks on, for example, the first entry ETF ticker "PSCD" links to 'static/...
[ "Create your url in the following manner:\n<a href=\"{% static '/myapp/images/sample_regression_'|add:i.index_ticker|add:'.jpg' %}\" target=\"_blank\">{{i.etf_name}}</a>\n\nI've broken your url into 3 parts. The first and last parts are simple strings. The middle part contains your ticker. The | is used to denote t...
[ 1 ]
[]
[]
[ "django", "html", "python" ]
stackoverflow_0074281610_django_html_python.txt
Q: Getting AttributeError: 'Picture' object has no attribute 'getFrameColour' while trying to access the array file The program stores pictures as objects. It stores the dimension, frame colour, and description of the picture. The program needs to input its requirements for a picture. The user will enter colour, widt...
Getting AttributeError: 'Picture' object has no attribute 'getFrameColour' while trying to access the array file
The program stores pictures as objects. It stores the dimension, frame colour, and description of the picture. The program needs to input its requirements for a picture. The user will enter colour, width, and height. Then the program will search the array and output the picture description if any picture meets the requ...
[ "Your __init__ method is correctly indented inside the Picture class. However, the other \"methods\" are not indented at all, so they're not actually part of the class; they're simply top-level functions. So when you create an instance of Picture, it does not have a getFrameColour method.\nYou want something more l...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074282866_python.txt
Q: Where is the tesseract executable file located on MacOS, and how to define it in Python? I have made a code using pytesseract and whenever I run it, I get this error: TesseractNotFoundError: tesseract is not installed or it's not in your path I have installed tesseract using HomeBrew and also pip installed it. A...
Where is the tesseract executable file located on MacOS, and how to define it in Python?
I have made a code using pytesseract and whenever I run it, I get this error: TesseractNotFoundError: tesseract is not installed or it's not in your path I have installed tesseract using HomeBrew and also pip installed it.
[ "If installed with Homebrew, it will be located in /usr/local/bin/tesseract by default. To verify this, run which tesseract in the terminal as Dmitrrii Z. mentioned.\nIf it's there, you can set it up in your python environment by adding the following line to your python script, after importing the library:\npytesse...
[ 2, 0 ]
[]
[]
[ "macos", "python", "python_3.x", "python_tesseract", "tesseract" ]
stackoverflow_0055235369_macos_python_python_3.x_python_tesseract_tesseract.txt
Q: pyautogui scroll and dragto are inconsistent depending on the size of the scrollbar Problem: PyAutoGUI scrolls a different amount depending on the size of the scrollbar. I would like to scroll the same amount of pixels, no matter the size of the scrollbar This window has 27 boxes total. As you can see, scrolling ...
pyautogui scroll and dragto are inconsistent depending on the size of the scrollbar
Problem: PyAutoGUI scrolls a different amount depending on the size of the scrollbar. I would like to scroll the same amount of pixels, no matter the size of the scrollbar This window has 27 boxes total. As you can see, scrolling a total of 90 pixels moves us passed 5 boxes and perfectly lines the top of the 6th box w...
[ "This is because the scrollbar's length depends on the size of the content being scrolled and on the size of scrollview itself.\nIn your example, you only have 30ish boxes in your scrollview. Now, let's think about how it would be if you had 1000 boxes:\nScrolling by exactly 90 pixels will scroll way more than 5 bo...
[ 1 ]
[]
[]
[ "automation", "pyautogui", "python", "python_3.x", "scroll" ]
stackoverflow_0074282908_automation_pyautogui_python_python_3.x_scroll.txt
Q: How To Keep Trying New Inputs in Try and Except Format I am coding a guessing game where the user inputs an integer between 1 and 100 to try and guess the correct number (26). I have to count the number of guesses the user takes to get the correct number. I want to use try and except blocks to allow the user to ke...
How To Keep Trying New Inputs in Try and Except Format
I am coding a guessing game where the user inputs an integer between 1 and 100 to try and guess the correct number (26). I have to count the number of guesses the user takes to get the correct number. I want to use try and except blocks to allow the user to keep trying until they guess it right. Right now, my code only...
[ "Instead of making try_exp like that, you can use a while loop that will first ask for input, and if the input is valid, then it will break out of the while loop. This is one way to implement it:\ndef try_exp():\n first_input = True\n while True:\n try:\n if first_input:\n n =...
[ 0 ]
[]
[]
[ "exception", "loops", "python", "try_catch" ]
stackoverflow_0074282951_exception_loops_python_try_catch.txt
Q: Extract values from nested dictionary How to extract values from nested dictionary to a new output? I have books season_n, ch_number_n, ch_name_n and pages_n: text = { 1: { 1: {"ch.name": "The Boy Who Lived", "pages": "146"}, 2: {"ch.name": "The Vanishing Glass", "pages": "126"}, }, 2: ...
Extract values from nested dictionary
How to extract values from nested dictionary to a new output? I have books season_n, ch_number_n, ch_name_n and pages_n: text = { 1: { 1: {"ch.name": "The Boy Who Lived", "pages": "146"}, 2: {"ch.name": "The Vanishing Glass", "pages": "126"}, }, 2: { 1: {"ch.name": "The Worst Birthda...
[ "text = {\n 1:{\n 1:{'ch.name' : 'The Boy Who Lived', 'pages' : '146'},\n 2:{'ch.name' : 'The Vanishing Glass' , 'pages' : '126'}\n },\n 2:{\n 1:{'ch.name' : 'The Worst Birthday', 'pages' : '129'},\n 2:{'ch.name' : \"Dobby's Warning\" , 'pages': '125'}\n ...
[ 1 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0074282867_dictionary_python.txt
Q: Why won't the elements in the last row of 2 columns in my DF change? I have letter ratings that I need to rank against each other and then pull the minimum ranking and median rating in a specific format. I've converted the minimum ranking and median rating to the correct specific format EXCEPT for the very last ro...
Why won't the elements in the last row of 2 columns in my DF change?
I have letter ratings that I need to rank against each other and then pull the minimum ranking and median rating in a specific format. I've converted the minimum ranking and median rating to the correct specific format EXCEPT for the very last row in those columns. Could someone help me troubleshoot why my last row doe...
[ "In the present case you can simply use:\ndf = df.replace(rating1_rank)\n\nprint(df)\n\n rating1 rating2 rating3 Medium_Rating Minimum_Rating\n0 D Dd c D D\n1 C Bb A B C\n2 B Bb b B B\n\nTo...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python", "replace" ]
stackoverflow_0074282921_dataframe_pandas_python_replace.txt
Q: Calculate Bollinger Band using Pandas Given a series, I want to calculate its Bollinger Band using Pandas. There exists a prior question, an answer to which discusses only the std aspect of the calculation, but not the entire calculation. Given a variable series of type pandas.Series with dtype float64, to compute...
Calculate Bollinger Band using Pandas
Given a series, I want to calculate its Bollinger Band using Pandas. There exists a prior question, an answer to which discusses only the std aspect of the calculation, but not the entire calculation. Given a variable series of type pandas.Series with dtype float64, to compute a band having a length of 20 and a standar...
[ "Consider this function. Its output matches that of TradingView. To calculate a lower band, specify a negative num_std, e.g. -2.\nimport pandas as pd\n\n\ndef bollinger_band(series: pd.Series, length: int = 20, *, num_std: int = 2) -> pd.Series:\n # Ref: https://stackoverflow.com/a/74283044/\n rolling = serie...
[ 2 ]
[]
[]
[ "pandas", "python", "technical_indicator" ]
stackoverflow_0074283043_pandas_python_technical_indicator.txt
Q: What happens when a variable is read and AT THE SAME TIME another thread MODIFIES IT? If the reading happens BEFORE or AFTER the update the behavior is obvious, it is not difficult to see, but what if it happens at the same time? Assuming there is nothing else (no synchronization, just a simple variable read and a...
What happens when a variable is read and AT THE SAME TIME another thread MODIFIES IT?
If the reading happens BEFORE or AFTER the update the behavior is obvious, it is not difficult to see, but what if it happens at the same time? Assuming there is nothing else (no synchronization, just a simple variable read and assignment). from threading import Thread import threading value = 0 def thread1(): g...
[ "Computer hardware and computer languages are intentionally designed so that we never have to answer the question \"what if X and Y happen at the same time?\"* In order to be able to make sense of any computer program—in order to predict how it will behave—we have to be able to assume that the outcome of the progra...
[ 1 ]
[]
[]
[ "concurrency", "multithreading", "python", "race_condition", "thread_safety" ]
stackoverflow_0074282567_concurrency_multithreading_python_race_condition_thread_safety.txt
Q: Insert data in data format from "google.type.date" protocol buffers I have this messsage in probuf: message Date { uint32 year = 1; MONTH month = 2; uint32 day = 3; } message Professor{ uint32 id = 1; string name = 2; Date birth_date = 3; string phone = 4; string address = 5; } I...
Insert data in data format from "google.type.date" protocol buffers
I have this messsage in probuf: message Date { uint32 year = 1; MONTH month = 2; uint32 day = 3; } message Professor{ uint32 id = 1; string name = 2; Date birth_date = 3; string phone = 4; string address = 5; } I have this code in python to insert data: def School() -> proto_exp_pb2.S...
[ "Your question is not easily reproducible. Your proto and code don't match; there's no School, MONTH (nor Student) message.\nThe field birth_date is a type Date that you define to have fields of uint32 and the undefined message type MONTH.\nPython is a little awkward for sub-messages but, once you've created the ro...
[ 0 ]
[]
[]
[ "protocol_buffers", "python" ]
stackoverflow_0074282645_protocol_buffers_python.txt
Q: Not Printing anything on screen def even_number_list(even_list): for i in even_list: if i % 2 == 0: return True else: pass even_number_list([1,3,5,6,9]) This code is not printing anything on the screen, I believe that it should print True, please help a beginne...
Not Printing anything on screen
def even_number_list(even_list): for i in even_list: if i % 2 == 0: return True else: pass even_number_list([1,3,5,6,9]) This code is not printing anything on the screen, I believe that it should print True, please help a beginner. Thanks, I think I'll get an output...
[ "Your function, as you expect, should return True. But when you call it, you don't use the return value. If you want to print the return value, you need to call even_number_list() inside of a print() function to print the output or assign the function call to a variable.\ndef even_number_list(even_list):\n for i...
[ 0 ]
[]
[]
[ "function", "printing", "python" ]
stackoverflow_0074282997_function_printing_python.txt
Q: python filter nested dictionary keys of second nested dict key with function rule IN ONE LINER I have a dictionary in this form: example ={'2020_01': {'PM0001': 1088, 'CA00006': 33, 'X00002': 125, 'J00009': 119, 'A0000S': 524}, '2020_02': {'F00067': 3, 'P00001': 1104, 'X00002': 98, 'J0009': 36, 'A0000S': 539}, '...
python filter nested dictionary keys of second nested dict key with function rule IN ONE LINER
I have a dictionary in this form: example ={'2020_01': {'PM0001': 1088, 'CA00006': 33, 'X00002': 125, 'J00009': 119, 'A0000S': 524}, '2020_02': {'F00067': 3, 'P00001': 1104, 'X00002': 98, 'J0009': 36, 'A0000S': 539}, '2020_03': {'P00001': 1200, 'Z78800': 45,'X00000': 84,'NK0000': 4,'A0000S': 577,'V000000':11}} I wou...
[ "Try:\nnew_dict = {\n k: {\n kk: vv\n for kk, vv in v.items()\n if kk.startswith((\"P\", \"X\")) and kk[1] == \"0\"\n }\n for k, v in example.items()\n}\n\nprint(new_dict)\n\nPrints:\n{'2020_01': {'X00002': 125}, '2020_02': {'P00001': 1104, 'X00002': 98}, '2020_03': {'P00001': 1200, 'X...
[ 0, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0074282905_dictionary_python.txt
Q: python iterate loop and change values in dictionary I'm trying to iterate over the loop to change the value of the dictionary. lines have a different baseball teams in each line . When I print the years, it prints out the keys correctly, but the value is all changed to the last element of the lines. For example, 1...
python iterate loop and change values in dictionary
I'm trying to iterate over the loop to change the value of the dictionary. lines have a different baseball teams in each line . When I print the years, it prints out the keys correctly, but the value is all changed to the last element of the lines. For example, 1903: 'NY Yankees', 1905: 'NY Yankees' ... 2021: 'NY Yank...
[ "Dictionary keys are unique: for j in lines: years.update({i:j}) will update years[i] several times, keeping only the latest value, which will be the last line!\nTo fix that, iterate simultaneously on years' keys and on the lines like this:\nNote the you must unindent this to pull it out of your else: bloc .\nHere'...
[ 0 ]
[]
[]
[ "dictionary", "loops", "python" ]
stackoverflow_0074283013_dictionary_loops_python.txt
Q: In my data frame I have Time column, I need to convert my HH:MM:SS.SS to seconds. How can I do that in python? Time volts 0 15:15:10.951 368 1 15:15:11.950 373 2 15:15:12.950 368 3 15:15:13.949 316 4 15:15:14.949 368 ... ... ... 2141 15:50:54.087 337 2142 15:50:55.0...
In my data frame I have Time column, I need to convert my HH:MM:SS.SS to seconds. How can I do that in python?
Time volts 0 15:15:10.951 368 1 15:15:11.950 373 2 15:15:12.950 368 3 15:15:13.949 316 4 15:15:14.949 368 ... ... ... 2141 15:50:54.087 337 2142 15:50:55.069 343 2143 15:50:56.085 344 2144 15:50:57.081 339 2145 15:50:58.090 347 def time_convert(x): ...
[ "I can only surmise what is in your dataframe. And anyway, iterating (even with apply) rows, is generally speaking a bad idea (very slow).\nBut, as for why it doesn't work, it lies in your conversion function\ndef time_convert(x):\n h,m,s = map(int,x.split(':'))\n return int(h) * 3600 + int(m) * 60 + int(s)\n\nyo...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074283060_dataframe_pandas_python.txt
Q: Ignore all syntax errors after exit() or quit() I noticed in prototyping some code that (a script that is analogous to) the following works a = 1 exit() for i in range(2): some # undefined variable but this does not a = 1 exit() some # undefined variable The latter results in IndentationError: unexpecte...
Ignore all syntax errors after exit() or quit()
I noticed in prototyping some code that (a script that is analogous to) the following works a = 1 exit() for i in range(2): some # undefined variable but this does not a = 1 exit() some # undefined variable The latter results in IndentationError: unexpected indent. Whilst not essential to work, in quickly pr...
[ "Python compiles your code to an intermediate representation. Your question is fair: there are languages that don't do this. For instance, this is a perfectly runnable Tcl snippet, despite the second line being absolute nonsense\nexit 0\n])} total garbage line of C0De ))))\n\nBut Python works differently. It reads ...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0074280479_python.txt
Q: How to remove parts of a str in a list? I have a variable called data and I would like to remove "//x00" from all of them if they have it. How would I go about doing so? I thought of iterating through all of them and checking each individually, but... data = ["b'$VNYMR", '-103.322', '-003.191', '-018.818', '+00.01...
How to remove parts of a str in a list?
I have a variable called data and I would like to remove "//x00" from all of them if they have it. How would I go about doing so? I thought of iterating through all of them and checking each individually, but... data = ["b'$VNYMR", '-103.322', '-003.191', '-018.818', '+00.0183', '+00.0107', '+00.50\\x0075', '-00.553', ...
[ "When you call for x in data, x is the element in the list, not its index. You could do either\nfor i, x in enumerate(data):\n data[i] = x.replace('//x00', '')\n\nor\nfor i in range(len(data)):\n data[i] = data[i].replace('//x00')\n\nYou will have to iterate through the list, as it isn't possible to do someth...
[ 1 ]
[ "If you want to remove all occurances, the best option is probably list comprehension\nnew_data = [i.replace(\"\\\\x00\", \"\") for i in data]\n\n" ]
[ -1 ]
[ "list", "python" ]
stackoverflow_0074282920_list_python.txt
Q: Why is there an error asserting that output is a list? aim is to write a function div_3() that will find all the values from the input parameter data_list that are perfectly divisible by 3, using a for loop with a conditional inside the function. And to save any values from data_list that meet this condition into ...
Why is there an error asserting that output is a list?
aim is to write a function div_3() that will find all the values from the input parameter data_list that are perfectly divisible by 3, using a for loop with a conditional inside the function. And to save any values from data_list that meet this condition into a new list 'output', which is returned from the function. da...
[ "instead of print(output) ,return output. Your error will go away\nSince, function does not return anything so, NoneType will be compared with list.\n" ]
[ 1 ]
[]
[]
[ "assertion", "function", "list", "python" ]
stackoverflow_0074283236_assertion_function_list_python.txt
Q: Error "AttributeError 'collections' has no attribute 'Callable' " using Beautiful Soup I followed all steps to install Beautiful Soup, but it still comes out with this error: AttributeError: module 'collections' has no attribute 'Callable' I am using Python 3.10. A: Use this! import collections collections.Cal...
Error "AttributeError 'collections' has no attribute 'Callable' " using Beautiful Soup
I followed all steps to install Beautiful Soup, but it still comes out with this error: AttributeError: module 'collections' has no attribute 'Callable' I am using Python 3.10.
[ "Use this!\nimport collections\ncollections.Callable = collections.abc.Callable\n\n", "This solution worked for me:\n\nNavigate to Python310\\Lib\\site-packages\\pyreadline in your file browser.\nOpen py3k_compat.py in an text editor.\nChange the 8th line from which should be return isinstance(x, collections.Call...
[ 23, 10, 6, 4, 2, 0, 0, 0, 0 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0069515086_beautifulsoup_python.txt
Q: Webscraping - Python - attribute href I got the fallowing: <h4><a class="" href="https://www.eloscimento.com.br/diversos/" title="Diversos">Diversos</a></h4>, <h4><a class="" href="https://www.eloscimento.com.br/pintura/" title="Pintura">Pintura</a></h4>, I am trying to get only the attribute href in this html we...
Webscraping - Python - attribute href
I got the fallowing: <h4><a class="" href="https://www.eloscimento.com.br/diversos/" title="Diversos">Diversos</a></h4>, <h4><a class="" href="https://www.eloscimento.com.br/pintura/" title="Pintura">Pintura</a></h4>, I am trying to get only the attribute href in this html website. My script: request = requests.get('h...
[ "Two issues here:\n\nYou're trying to run .get on list of tags (which is what find_all returns), when it's meant to be used directly on individual tags\nThe h4 tag doesn't have a href attribute - that belongs to the a tag inside the header tag, so even if you defined it as h4 = site_html.find('h4') (to get just the...
[ 0 ]
[]
[]
[ "beautifulsoup", "html", "python", "python_requests", "web_scraping" ]
stackoverflow_0074282355_beautifulsoup_html_python_python_requests_web_scraping.txt
Q: Continue while loop when the function catches exception I have multiple functions inside a while loop. Each of these functions has a try/except block to catch Exception. Basically, my while loop is perpetual, so if one of my functions catches an Exception, I would like to continue the loop, i.e. go back to the top...
Continue while loop when the function catches exception
I have multiple functions inside a while loop. Each of these functions has a try/except block to catch Exception. Basically, my while loop is perpetual, so if one of my functions catches an Exception, I would like to continue the loop, i.e. go back to the top of the loop. How can this be done, please? As I have many fu...
[ "I'm pretty sure you would have to surround your functions in your while loop with a try/except block.\nIf the functions themselves have a try/except block within them and they are still being raised as errors in your while loop, I would assume your try/except block in your functions are not robust enough and it is...
[ 1 ]
[]
[]
[ "continue", "python", "try_catch", "while_loop" ]
stackoverflow_0074283272_continue_python_try_catch_while_loop.txt
Q: Removing initial whitespace plus the last empty new line line using python I am trying to implement a code that prints an 8 by 8 matrix (0 to 63). It should however remove the initial tab spaces and the last empty line. My code is below : s ='' for i in range(n): for j in range(n): z = i * n + j ...
Removing initial whitespace plus the last empty new line line using python
I am trying to implement a code that prints an 8 by 8 matrix (0 to 63). It should however remove the initial tab spaces and the last empty line. My code is below : s ='' for i in range(n): for j in range(n): z = i * n + j s += ' ' if z < 10: s += ' ' s += str(z) s += ...
[ "Basically all you are looking for is whenever you go to a new line, the initial space is not printed, since every newline is a j, you will need to add:\n if j != 0:\n s += ' '\n\nIt should work. Will look like this now:\ns =''\nfor i in range(n):\n for j in range(n):\n z = i * n + j\n\n...
[ 2, 0 ]
[]
[]
[ "indentation", "python", "string", "whitespace" ]
stackoverflow_0074283130_indentation_python_string_whitespace.txt
Q: Running an infinite loop worker in python with a HTTP health check endpoint I have a python project that consumes messages from an AWS SQS queue and performs tasks. It does this by constantly trying to get messages from the queue in an infinite loop and performing operations on each message when they're found. I'd...
Running an infinite loop worker in python with a HTTP health check endpoint
I have a python project that consumes messages from an AWS SQS queue and performs tasks. It does this by constantly trying to get messages from the queue in an infinite loop and performing operations on each message when they're found. I'd like to deploy this code in a docker container and would like to integrate a hea...
[ "Given the lack of responses (and downvote) I ended up just continuing with doing things in parallel.\nI used python's multiprocessing library to put a fastapi endpoint in a separate process. I then call terminate on the process when the long running worker process exits for any reason.\nI am not handling errors in...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074270482_python.txt
Q: Webscraping 'urllib.error.HTTPError: HTTP Error 404: Not Found' error I was following a tutorial to webscrape data from yahoo finance, but my code gets this error: 'urllib.error.HTTPError: HTTP Error 404: Not Found' error. My code: import pandas as pd amd_profile = pd.read_html("https://finance.yahoo.com/quote/AM...
Webscraping 'urllib.error.HTTPError: HTTP Error 404: Not Found' error
I was following a tutorial to webscrape data from yahoo finance, but my code gets this error: 'urllib.error.HTTPError: HTTP Error 404: Not Found' error. My code: import pandas as pd amd_profile = pd.read_html("https://finance.yahoo.com/quote/AMD/profile?p=AMD") print(amd_profile) The errors: Traceback (most recent c...
[ "Quick read in the Pandas Documentation:\nhttps://pandas.pydata.org/docs/reference/api/pandas.read_html.html?highlight=read_html#pandas.read_html\n\"A URL, a file-like object, or a raw string containing HTML. Note that lxml only accepts the http, ftp and file url protocols. If you have a URL that starts with 'https...
[ 0, 0 ]
[]
[]
[ "http_error", "pandas", "python" ]
stackoverflow_0068224140_http_error_pandas_python.txt
Q: How do I update values in a nested dictionary in python without getting error "dictionary changed size during iteration"? Python beginner here. The project I'm working on uses a nested dictionary of different business locations and their hours by day of week. It's formatted like this: all_branch_hours = { 'Bra...
How do I update values in a nested dictionary in python without getting error "dictionary changed size during iteration"?
Python beginner here. The project I'm working on uses a nested dictionary of different business locations and their hours by day of week. It's formatted like this: all_branch_hours = { 'Branch 1': { 'Sunday': '12:00-18:00', 'Monday': '09:00-18:00', 'Tuesday': '09:00-20:00', ...
[ "You are using wrong key for the inner dictionaries, causing addition of new keys while iterating. You need to iterate over the items of the inner dictionaries to get access to their true keys.\nfor key, value in all_branch_hours.items():\n for k, v in value.items(): # now k is truly key of inner dictionari...
[ 0 ]
[]
[]
[ "dictionary", "python", "python_3.x" ]
stackoverflow_0074283365_dictionary_python_python_3.x.txt
Q: How To Join Two Models with Different Column Names and Return All Instances? I aim to create a dataframe of the Top 3 Selling menu_items in my Purchases table. My thoughts are to create a join on the Purchases model with the Menu_Item model where Purchases.menu_item = Menu_Item.title. I will convert the QuerySe...
How To Join Two Models with Different Column Names and Return All Instances?
I aim to create a dataframe of the Top 3 Selling menu_items in my Purchases table. My thoughts are to create a join on the Purchases model with the Menu_Item model where Purchases.menu_item = Menu_Item.title. I will convert the QuerySet to a DataFrame using django_pandas.io. I plan to use the sum of Menu_Item.pric...
[ "You didn't mention what you have tried, so it is hard for me (and other developers) to give precise suggestions.\nAnyway, have you tried something like\npurchases = Purchase.objects.values(\n 'timestamp', \n item_title=F('menu_item__title'), \n item_price=F('menu_item__price'),\n item_desc=F('menu_item...
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074282453_django_python.txt
Q: python sort json after n elements I have a json/dict in the following format: { "top": 590, "left": 105, "width": 240, "height": 40, "Zarya": "142612a11ad2ca629d2182a51b23d1f2", "Kiriko": "4d0528271fd9d0104cd2af0b1c91f4f6", "Echo": "175b9c62c57b0d6e18577f352fad4afc", "Sojourn": "8...
python sort json after n elements
I have a json/dict in the following format: { "top": 590, "left": 105, "width": 240, "height": 40, "Zarya": "142612a11ad2ca629d2182a51b23d1f2", "Kiriko": "4d0528271fd9d0104cd2af0b1c91f4f6", "Echo": "175b9c62c57b0d6e18577f352fad4afc", "Sojourn": "8ea40548f4472457cfbd46731958a432", "...
[ "Assuming you're using Python 3.7+ you can use (dct is your dictionary from the question):\nitems = list(dct.items())\nout = dict(items[:4] + sorted(items[4:]))\nprint(out)\n\nPrints:\n{\n \"top\": 590,\n \"left\": 105,\n \"width\": 240,\n \"height\": 40,\n \"Ana\": \"556e9f3ff210729dc9e1cf848c3c579f...
[ 2, 1, 0 ]
[]
[]
[ "dictionary", "json", "python", "python_3.x" ]
stackoverflow_0074283383_dictionary_json_python_python_3.x.txt
Q: BeautifulSoup findall get text but return empty I am scraping a website and would like to find specific content based on style, so I do soup.find_all('style') and it does return some result/text, but once I use .text soup_name.find_all('style')[0].text to extract the text, it returns an empty string What can I d...
BeautifulSoup findall get text but return empty
I am scraping a website and would like to find specific content based on style, so I do soup.find_all('style') and it does return some result/text, but once I use .text soup_name.find_all('style')[0].text to extract the text, it returns an empty string What can I do to extract the text in the style tag?
[ "Try .contents[0]:\nfrom bs4 import BeautifulSoup\n\n\nhtml_doc = \"\"\"\\\n<style>\n th { border: none; }\n</style>\"\"\"\n\nsoup = BeautifulSoup(html_doc, \"html5lib\")\n\nprint(soup.find(\"style\").contents[0])\n\nPrints:\n\n th { border: none; }\n\n\n", "If nothing else, you can just use\nstr(soup.find(...
[ 1, 0 ]
[]
[]
[ "beautifulsoup", "python", "web_scraping" ]
stackoverflow_0074283249_beautifulsoup_python_web_scraping.txt