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:
Replace dataframe columns names with values of another dataframe
I have two dataframes:
df1 = [ A B
X y1
XX y2 ]
df2 = [ X XX
1 2
2 3 ]
I want to replace the names of the df2 (X, XX) with the values of the same index in df1. So my result will be:
df2 = [ y1 y2... | Replace dataframe columns names with values of another dataframe | I have two dataframes:
df1 = [ A B
X y1
XX y2 ]
df2 = [ X XX
1 2
2 3 ]
I want to replace the names of the df2 (X, XX) with the values of the same index in df1. So my result will be:
df2 = [ y1 y2
1 2
2 3 ]
| [
"Make df1 into a series of column B indexed by column A, and use that to rename the columns of df2.\nrenamed = df2.rename(columns=df1.set_index(\"A\")[\"B\"])\n\n"
] | [
2
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074392122_dataframe_pandas_python.txt |
Q:
compile() from AST ignores line numbers
How do I specify line numbers in AST?
I've tried ast.increment_lineno, but compile() pays no attention to the changed line numbers:
>>> import ast
>>> example_tree=ast.parse("print('Hello, World!')")
>>> ast.increment_lineno(example_tree, 10)
>>> compile(example_tree,"somefi... | compile() from AST ignores line numbers | How do I specify line numbers in AST?
I've tried ast.increment_lineno, but compile() pays no attention to the changed line numbers:
>>> import ast
>>> example_tree=ast.parse("print('Hello, World!')")
>>> ast.increment_lineno(example_tree, 10)
>>> compile(example_tree,"somefile.py","exec")
<code object <module> at 0x7fb... | [
"Code parsed with mode='exec' (the default) becomes an ast.Module object, which does not have a lineno attribute. [Note 1]\nAs the documentation for module ast indicates, only stmt and expr subclasses have token position attributes (lineno, col_offset, end_lineno and end_col_offset). ast.increment_lineno modifies t... | [
1
] | [] | [] | [
"abstract_syntax_tree",
"python"
] | stackoverflow_0074391198_abstract_syntax_tree_python.txt |
Q:
Python Regex with variable pattern, pattern length?
I am trying to develop a function that takes a name from a user, and attempts to match the name with a database of arbitrarily reserved usernames. The pattern(the reserved names) is variable length, and the username can be anything. I'm trying to prevent users fr... | Python Regex with variable pattern, pattern length? | I am trying to develop a function that takes a name from a user, and attempts to match the name with a database of arbitrarily reserved usernames. The pattern(the reserved names) is variable length, and the username can be anything. I'm trying to prevent users from taking usernames that are reserved basically, but the ... | [
"Except for using the in function from a list of all reserved usernames and their variants, you probably could consider string similarity algorithms which can give a score to every string input and determine how similar it is to one of your keyword by a certain threshold (for example 70%). But I don't think it will... | [
0
] | [] | [] | [
"basic_authentication",
"python",
"regex"
] | stackoverflow_0074390698_basic_authentication_python_regex.txt |
Q:
python-CSV Multiple Columns with the same header into one column
I have a CSV file with company data with 22 rows and 6500 columns. The columns have the same names and I should get the columns with the same names stacked into individual columns according to their headers.
I have now the data in one df like this:
Y... | python-CSV Multiple Columns with the same header into one column | I have a CSV file with company data with 22 rows and 6500 columns. The columns have the same names and I should get the columns with the same names stacked into individual columns according to their headers.
I have now the data in one df like this:
Y C Y C Y C
1. a 1. b. 1. c.
2. a. 2. b. 2. c. ... | [
"I would try an attempt where you slice the df in chunks by iteration and concat them back together, since the column names can't be identified distinctly.\nEDIT\nChanged answer to new input:\nchunksize = 2\ndf = (\n pd.concat(\n [\n df.iloc[:, i:i+chunksize] for i in range(0, len(df.columns), ... | [
0,
0
] | [] | [] | [
"pandas",
"python",
"stack"
] | stackoverflow_0074390272_pandas_python_stack.txt |
Q:
How can i delete charcters from dictionnary [Python]
banword = ["/","\n",'"',"'","Badword","*","badword","badword","badword"]
okword = ["","","","","f","","Badword","badword","badword"]
for c in range (1,len(commentaries) + 1):
azpeo = commentaries[c]
print(azpeo)
for c in range(len(banword)):
... | How can i delete charcters from dictionnary [Python] | banword = ["/","\n",'"',"'","Badword","*","badword","badword","badword"]
okword = ["","","","","f","","Badword","badword","badword"]
for c in range (1,len(commentaries) + 1):
azpeo = commentaries[c]
print(azpeo)
for c in range(len(banword)):
azpeo.replace(banword[c],okword[c])
commentaries[c] = ... | [
"replace doesnot change your string inplace so you need to assign it to original string.\nYou need to change\nazpeo.replace(banword[c],okword[c])\n\nTo\nazpeo = azpeo.replace(banword[c],okword[c])\n\nThen it will work\n",
"the problem is that strings are immutable so you should do at line 7 in your example, the f... | [
1,
0
] | [] | [] | [
"python",
"replace"
] | stackoverflow_0074392043_python_replace.txt |
Q:
ElasticSearch mapper to insert data in ES
I was write the mapper for insert data into elastic index but I got following error.
elasticsearch.BadRequestError: BadRequestError(400, 'mapper_parsing_exception', 'not_x_content_exception: Compressor detection can only be called on some xcontent bytes or compressed xcont... | ElasticSearch mapper to insert data in ES | I was write the mapper for insert data into elastic index but I got following error.
elasticsearch.BadRequestError: BadRequestError(400, 'mapper_parsing_exception', 'not_x_content_exception: Compressor detection can only be called on some xcontent bytes or compressed xcontent bytes')
mapper = {"mappings":
{
... | [
"With Elasticsearch 8.5.0, this works for me.\nMapping:\n{\n \"mappings\": {\n \"properties\": {\n \"event_info\": {\n \"type\": \"nested\",\n \"properties\": {\n \"type_info\": {\"type\": \"text\"},\n \"op_type\": {\"type\": \"text\"},\n ... | [
0
] | [] | [] | [
"elasticsearch",
"python"
] | stackoverflow_0074374280_elasticsearch_python.txt |
Q:
Issue while converting string to DateTime in Polars
I am converting string column into datetime column...
Here is my input,
col
00000001011970
00000001011970
00000001011970
...
00000001011970
Here is my snippet,
df[col].with_column= df.with_column(pl.col(col).str.strptime(pl.Datetime, fmt='%Y-%m-%d %H:%M:%S',stri... | Issue while converting string to DateTime in Polars | I am converting string column into datetime column...
Here is my input,
col
00000001011970
00000001011970
00000001011970
...
00000001011970
Here is my snippet,
df[col].with_column= df.with_column(pl.col(col).str.strptime(pl.Datetime, fmt='%Y-%m-%d %H:%M:%S',strict=False).alias('parsed EventTime') )
this ... | [
"Your format clause should match the input.\ndf = pl.DataFrame({\n\"col\": [\"00000001011970\", \"00000001011970\", \"00000001011970\"]\n})\nprint(df.with_column(\n pl.col('col')\n .str\n .strptime(pl.Datetime, fmt='%S%M%H%d%m%Y',strict=False)\n .alias('parsed EventTime')\n))\n\n\ngives me\nshape: (3, 2... | [
1,
0
] | [] | [] | [
"dataframe",
"datetime",
"python",
"python_polars"
] | stackoverflow_0074385464_dataframe_datetime_python_python_polars.txt |
Q:
Python list of list changes when changing a previously pointed list of lists
I have a function that looks like this
https://i.stack.imgur.com/PQTjc.png
I assign the variable test to board[:] (board is an 8x8 list of lists). Later in the function I make a change to test, and send test to another function. The probl... | Python list of list changes when changing a previously pointed list of lists | I have a function that looks like this
https://i.stack.imgur.com/PQTjc.png
I assign the variable test to board[:] (board is an 8x8 list of lists). Later in the function I make a change to test, and send test to another function. The problem is: when test gets changed, the same change happens to board. Any tips to solve... | [] | [] | [
"Usually to avoid this you have to copy\n# In Python 3 whether you have a list or np.array or pd.DataFrame\ntest = board[:].copy()\n\nThen the two variables are decorrelated\n"
] | [
-1
] | [
"list",
"python"
] | stackoverflow_0074392175_list_python.txt |
Q:
Pytube: urllib.error.HTTPError: HTTP Error 410: Gone
I've been getting this error on several programs for now.
I've tried upgrading pytube, reinstalling it, tried some fixes, changed URLs and code, but nothing seems to work.
from pytube import YouTube
#ask for the link from user
link = input("Enter the link of Yo... | Pytube: urllib.error.HTTPError: HTTP Error 410: Gone | I've been getting this error on several programs for now.
I've tried upgrading pytube, reinstalling it, tried some fixes, changed URLs and code, but nothing seems to work.
from pytube import YouTube
#ask for the link from user
link = input("Enter the link of YouTube video you want to download: ")
yt = YouTube(link)
... | [
"Try to upgrade, there is a fix in version 11.0.0:\npython -m pip install --upgrade pytube\n\n",
"If you haven't already, install Git on your PC:\nhttps://git-scm.com/download/win\nThen open the command window as admin and install this patch:\npython -m pip install git+https://github.com/Zeecka/pytube@fix_1060\n\... | [
21,
7,
2,
1,
0,
0,
0
] | [] | [] | [
"http",
"http_error",
"python",
"pytube"
] | stackoverflow_0068680322_http_http_error_python_pytube.txt |
Q:
How to run parallel lambdas from another lambda?
I'm trying to trigger several lambdas in parallel from another lambda. I'm using aiobotocore and this works fine locally but when I try to run it on AWSLambda, I have an error on the import modules:
Unable to import module 'lambda_function': cannot import name 'appl... | How to run parallel lambdas from another lambda? | I'm trying to trigger several lambdas in parallel from another lambda. I'm using aiobotocore and this works fine locally but when I try to run it on AWSLambda, I have an error on the import modules:
Unable to import module 'lambda_function': cannot import name 'apply_request_checksum' from 'botocore.client' (/var/runti... | [
"Use stepfunctions!!!. It's service for lamba orchestration simply put run multiple lambdas sequentially, or in parallel.\n\nUsing a Parallel state, Step Functions can execute multiple lambdas at the same time.\n\n",
"After investigating, it turns out that it was a package version error. The botocore package need... | [
1,
0,
0
] | [] | [] | [
"amazon_web_services",
"aws_lambda",
"botocore",
"python"
] | stackoverflow_0074058094_amazon_web_services_aws_lambda_botocore_python.txt |
Q:
Property 'sheets' of 'OpenpyxlWriter' object has no setter using pandas and openpyxl
This code used to get a xlsx file and write over it, but after updating from pandas 1.1.5 to 1.5.1 I got zipfile.badzipfile file is not a zip file
Then I read here that after pandas 1.2.0 the pd.ExcelWriter(report_path, engine='op... | Property 'sheets' of 'OpenpyxlWriter' object has no setter using pandas and openpyxl | This code used to get a xlsx file and write over it, but after updating from pandas 1.1.5 to 1.5.1 I got zipfile.badzipfile file is not a zip file
Then I read here that after pandas 1.2.0 the pd.ExcelWriter(report_path, engine='openpyxl') creates a new file but as this is a completely empty file, openpyxl cannot load i... | [
"try this:\nfilepath = r'Resultados.xlsx'\nwith pd.ExcelWriter(\n filepath,\n engine='openpyxl',\n mode='a',\n if_sheet_exists='overlay') as writer:\n reader = pd.read_excel(filepath)\n df.to_excel(\n writer,\n startrow=reader.shape[0] + 1,\n index=False,\n ... | [
2,
2
] | [] | [] | [
"openpyxl",
"pandas",
"python",
"setter"
] | stackoverflow_0074383395_openpyxl_pandas_python_setter.txt |
Q:
Can I set the start position from the Silder to e.g 9? Instead of 0?
currently I just try out some Stuff in Python. I did some stuff with Sliders, but I never found a command that I can set the Slider starting position to 9. Is there some command to the the Start pos?
Thank you in Advance
from tkinter import *
ma... | Can I set the start position from the Silder to e.g 9? Instead of 0? | currently I just try out some Stuff in Python. I did some stuff with Sliders, but I never found a command that I can set the Slider starting position to 9. Is there some command to the the Start pos?
Thank you in Advance
from tkinter import *
master = Tk()
Slider1 = Scale(master, from_=0, to=42, orient=VERTICAL, lengt... | [
"You can set the scale to any value you want with the set method:\nSlider1.set(9)\n\n"
] | [
0
] | [] | [] | [
"python",
"slider",
"tkinter"
] | stackoverflow_0074389462_python_slider_tkinter.txt |
Q:
Problem on running telethon bot on heroku
I wrote a small autoresponder bot for myself and deployed using GitHub to Heroku. When I run it, it works only one minute then shuts down.
Here my code:
import time
import telethon
from telethon import TelegramClient, events
api_id = x
api_hash = 'x'
phone_number = 9... | Problem on running telethon bot on heroku | I wrote a small autoresponder bot for myself and deployed using GitHub to Heroku. When I run it, it works only one minute then shuts down.
Here my code:
import time
import telethon
from telethon import TelegramClient, events
api_id = x
api_hash = 'x'
phone_number = 998x
password = 'a'
session_file = "TelegramCl... | [
"web processes must listen for HTTP requests on the port they are assigned. If they don't bind to that port quickly enough, Heroku declares that they have crashed.\nYour application does not listen for HTTP requests. It should therefore not be declared as a web process. It is common for such processes to be called ... | [
0
] | [] | [] | [
"bots",
"client_server",
"heroku",
"python",
"telethon"
] | stackoverflow_0074389602_bots_client_server_heroku_python_telethon.txt |
Q:
Breaking the tie by removing the last element from the list in python
I am trying to return the majority, or break a tie by keep removing the last element from the list. This is what I have been trying to do but does not seem to work
Given an input of a list label = [4,4,4,3,3,3,5,5,5,6,6,6] I am trying to get an ... | Breaking the tie by removing the last element from the list in python | I am trying to return the majority, or break a tie by keep removing the last element from the list. This is what I have been trying to do but does not seem to work
Given an input of a list label = [4,4,4,3,3,3,5,5,5,6,6,6] I am trying to get an output of [4,4,4,3,3] where 4 is the majority here after removing keep remo... | [
"This will iterate over label and pop the last value, until there is only one \"max\" value inside of label:\ndef tie_breaker(x):\n x_set = set(x)\n x_count = [x.count(i) for i in x_set]\n return x_count.count(max(x_count)) > 1\n\nlabel = [4,4,4,3,3,3,5,5,5,6,6,6] \nwhile tie_breaker(label):\n label.pop... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074392029_python.txt |
Q:
How to change size of VS Code jupyter notebook graphs?
My problem is that when I use google collab to display graphs they are much bigger, but recently I have switched from google collab to vs code jupyter notebook but when I try to display a graph is much smaller. Is there a way to change the graph size on vs cod... | How to change size of VS Code jupyter notebook graphs? | My problem is that when I use google collab to display graphs they are much bigger, but recently I have switched from google collab to vs code jupyter notebook but when I try to display a graph is much smaller. Is there a way to change the graph size on vs code jupyter notebook. BTW I am using plotly.
| [
"I know in matplotlib you can do something like this:\nimport matplotlib as mpl\nmpl.rcParams['figure.dpi'] = 150\n\nThis will change the graph size for all cells that follow. You can set to a different size in a later cell if you want to.\n",
"You may try it in VS Code Insider, which shows the bigger graph.\nVS... | [
5,
2,
2,
0,
0
] | [] | [] | [
"jupyter",
"jupyter_notebook",
"plotly",
"python",
"visual_studio_code"
] | stackoverflow_0067837572_jupyter_jupyter_notebook_plotly_python_visual_studio_code.txt |
Q:
Convert pandas dataframe to tuple of tuples
I have the following pandas dataframe df:
Description Code
0 Apples 014
1 Oranges 015
2 Bananas 017
3 Grapes 021
I need to convert it to a tuple of tuples, like this:
my_fruits = ( ('Apples', '014'),
('Ora... | Convert pandas dataframe to tuple of tuples | I have the following pandas dataframe df:
Description Code
0 Apples 014
1 Oranges 015
2 Bananas 017
3 Grapes 021
I need to convert it to a tuple of tuples, like this:
my_fruits = ( ('Apples', '014'),
('Oranges', '015'),
('Bananas', '017'),... | [
"Would something like this work?\ntuple(df.itertuples(index=False, name=None))\n\n",
"You need to zip the two columns:\ntuple(zip(df.Description, df.Code))\n# (('Apples', 14), ('Oranges', 15), ('Bananas', 17), ('Grapes', 21))\n\n",
"Though it is not recommended for large dataframes, you can also use apply\nimpo... | [
11,
3,
0
] | [] | [] | [
"dataframe",
"pandas",
"python",
"tuples"
] | stackoverflow_0051897708_dataframe_pandas_python_tuples.txt |
Q:
Combining sets of multiple rows in a single Dataframe to generate new Dataframe
I'm having trouble thinking of a vectorized (or efficient...) solution to a problem involving two large dataframes. One dataframe (df1) is filled with data (floats, ints, and nans). The other (df2) contains a column with n, where n is ... | Combining sets of multiple rows in a single Dataframe to generate new Dataframe | I'm having trouble thinking of a vectorized (or efficient...) solution to a problem involving two large dataframes. One dataframe (df1) is filled with data (floats, ints, and nans). The other (df2) contains a column with n, where n is the number of rows that I want to combine. The index of n matches the index in df1 wh... | [
"You can use the indexes from df2 to indicate where the groupings start. So index 0, and index 2 are a group, and since the sum of n is 4, any rows after 4 in df1 must be their own group.\nBased on that you can number the groups using cumsum, and then creating an incremental value per group which will determine ho... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074392136_dataframe_pandas_python.txt |
Q:
Extracting attachment in an email which is an attachment inside an email using outlook api Python
I use the code below to extract the attachment from an email, but the problem is that I need to extract an attachment inside an email which is already an attachment of an email. It goes like this :
email -> email (as ... | Extracting attachment in an email which is an attachment inside an email using outlook api Python | I use the code below to extract the attachment from an email, but the problem is that I need to extract an attachment inside an email which is already an attachment of an email. It goes like this :
email -> email (as an attachment) -> attachment
Can someone help ? I have a shit ton of email attachment to extract...
The... | [
"The problematic lines of code are:\n # Create separate folder for each message\n target_folder = output_dir / str(subject)\n target_folder.mkdir(parents=True, exist_ok=True)\n\nMake sure that the Subject property value doesn't contain forbidden symbols. Windows (and linux) has a number of symbols forbidden ... | [
0
] | [] | [] | [
"api",
"email",
"extract",
"outlook",
"python"
] | stackoverflow_0074391683_api_email_extract_outlook_python.txt |
Q:
How to Merge two pages from a pdf file as one page
I have a pdf in which there are total 6 pages of images.I want to merge page 1 and 2 as a single pdf and so on for 3 to 6 pages.
I splitted all 6 pages of pdf as individual pdf.
import os
from PyPDF2 import PdfFileReader, PdfFileWriter
def pdf_splitter(path):
... | How to Merge two pages from a pdf file as one page | I have a pdf in which there are total 6 pages of images.I want to merge page 1 and 2 as a single pdf and so on for 3 to 6 pages.
I splitted all 6 pages of pdf as individual pdf.
import os
from PyPDF2 import PdfFileReader, PdfFileWriter
def pdf_splitter(path):
fname = os.path.splitext(os.path.basename(path))[0]
pdf... | [
"The library pyPDF2 has also a PdfFileMerger object, that should do exactly what you want.\nAs from the example here you can just create a PdfFileMerger, read two pages and put them into one single file.\nI changed your script slightly to create also files with pages 0-1, 2-3, 4-5 ecc.. (of course page 0 is the fir... | [
1,
0,
0
] | [] | [] | [
"image",
"merge",
"pdf",
"python",
"split"
] | stackoverflow_0056970605_image_merge_pdf_python_split.txt |
Q:
How to get the date by day name in python?
I have a day name such as Monday. and the current day is Wednesday. Now i want to get the date of next coming Monday. How can i do it with a best practice in a very short way. right now i am trying to do this with bunch of if conditions and it made things messy and very d... | How to get the date by day name in python? | I have a day name such as Monday. and the current day is Wednesday. Now i want to get the date of next coming Monday. How can i do it with a best practice in a very short way. right now i am trying to do this with bunch of if conditions and it made things messy and very difficult.
here is my code :
day_time = timezone.... | [
"We can add a day to the current day till the new day_time has same day as the required day -\nday_time = timezone.now()\ncoming_day = \"monday\"\nwhile day_time.strftime(\"%A\") != coming_day:\n day_time = day_time + timedelta(days=1)\n\n",
"You might want to check out dateutils. It will do the math for you. ... | [
2,
0
] | [] | [] | [
"django",
"python",
"python_3.x"
] | stackoverflow_0074392212_django_python_python_3.x.txt |
Q:
Validate combination of codes with clause operators
First of all, I'm sorry this question may sound easy, but I'm not a real programmer, just a hobbyist.
I have a problem I can't get around solving how to program following thing in any available language or even Excel. I can do it myself in java, but I'm guessing ... | Validate combination of codes with clause operators | First of all, I'm sorry this question may sound easy, but I'm not a real programmer, just a hobbyist.
I have a problem I can't get around solving how to program following thing in any available language or even Excel. I can do it myself in java, but I'm guessing it is fairly simple to do in py. So here goes:
Say you ha... | [
"Solution Regex:\nUse Regex to find all matches of an expression or \"conditional clause\" in a String. The following regular Expression will match against any character sequences\nStatement\nIn short, the full statement, you have to match against looks like this:\n(100|200);ABC;(AAA|BBB)(?:(?!(CCC|DDD))).$\n\nExpl... | [
0
] | [] | [] | [
"conditional_statements",
"java",
"operators",
"python",
"sql"
] | stackoverflow_0074376040_conditional_statements_java_operators_python_sql.txt |
Q:
Fix jupyter_nbextensions_configurator & jupyter_lsp fail to load?
Related: jupyter-lab does not load jupyter_nbextensions_configurator (but jupyter-notebook does)
This time I didn't request installation of any jupyter notebook stuff - did something else drag it in?
The full console output for jupyter lab startup i... | Fix jupyter_nbextensions_configurator & jupyter_lsp fail to load? | Related: jupyter-lab does not load jupyter_nbextensions_configurator (but jupyter-notebook does)
This time I didn't request installation of any jupyter notebook stuff - did something else drag it in?
The full console output for jupyter lab startup is given below
Issues
jupyter_nbextensions_configurator doesn't load - ... | [
"I hope this answer will be superseded by a better one, explaining why the situation arose, however I discovered that the json config files that needed to be edited are in fact at:\nC:\\ProgramData\\jupyter\n\n(found by running !jupyter server extension list in a notebook cell)\nwhere jupyter_notebook_config.json i... | [
0
] | [] | [] | [
"jupyter",
"jupyter_lab",
"jupyter_notebook",
"python"
] | stackoverflow_0074392115_jupyter_jupyter_lab_jupyter_notebook_python.txt |
Q:
Calculating angular distance via python atan2()
I need a function to calculate the shortest angular distance from an object in 2D space (x,y,theta) to a point.
So far I have:
def ang_distance(x1,y1,theta,x2,y2):
ang_distance = atan2(y2 - y1, x2 - x1) - theta
return ang_distance
The problem is: theta range... | Calculating angular distance via python atan2() | I need a function to calculate the shortest angular distance from an object in 2D space (x,y,theta) to a point.
So far I have:
def ang_distance(x1,y1,theta,x2,y2):
ang_distance = atan2(y2 - y1, x2 - x1) - theta
return ang_distance
The problem is: theta ranges from -pi to pi, and atan2 also returns from -pi to ... | [
"It sounds like you want to add/subtract some multiple of 2 * pi so that the angle is always between -pi and pi:\ndef ang_distance(x1,y1,theta,x2,y2):\n angle = atan2(y2 - y1, x2 - x1) - theta\n angle = angle - 2 * math.pi * math.floor(0.5 + angle / (2 * math.pi))\n return angle\n\nMinor aside: I changed t... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074392313_python.txt |
Q:
Django rest framework ajax form submit error 403 (forbidden)
When i try to submit my ajaxified form that's working with the DRF API i get in the browser console!
POST http://localhost:8000/api/texts/ 403 (Forbidden)
here is my html file :
<form id="text-form" method="POST" action="">
... | Django rest framework ajax form submit error 403 (forbidden) | When i try to submit my ajaxified form that's working with the DRF API i get in the browser console!
POST http://localhost:8000/api/texts/ 403 (Forbidden)
here is my html file :
<form id="text-form" method="POST" action="">
<input type="text" name="title" placeholder=... | [
"Now that you told us the content of the details field, it should be easier to fix your problem.\nThe Django documentation advises you to get the CSRF token from the cookies.\nIt even gives you the following function to do that:\nfunction getCookie(name) {\n let cookieValue = null;\n if (document.cookie && do... | [
2,
0,
0
] | [] | [] | [
"ajax",
"django",
"django_rest_framework",
"python",
"python_3.x"
] | stackoverflow_0068414729_ajax_django_django_rest_framework_python_python_3.x.txt |
Q:
jupyter notebook running kernel in different env
I've gotten myself into some kind of horrible virtualenv mess. Help?!
I manage environments with conda. Until recently, I only had a python2 jupyter notebook kernel, but I decided to drag myself kicking and screaming into the 21st century and installed a python3 k... | jupyter notebook running kernel in different env | I've gotten myself into some kind of horrible virtualenv mess. Help?!
I manage environments with conda. Until recently, I only had a python2 jupyter notebook kernel, but I decided to drag myself kicking and screaming into the 21st century and installed a python3 kernel; I forget how I did it.
My main (anaconda) pyt... | [
"This is a tricky part of ipython / Jupyter. The set of kernels available are independent of what your virtualenv is when you start jupyter Notebook. The trick is setting up the the ipykernel package in the environment you want to identify itself uniquely to jupyter. From docs on multiple ipykernels, \nsource activ... | [
172,
12,
8,
4,
1,
0,
0
] | [] | [] | [
"conda",
"jupyter",
"package",
"python",
"virtual_environment"
] | stackoverflow_0037891550_conda_jupyter_package_python_virtual_environment.txt |
Q:
Serial communication with Raspberry Pi Pico and Python
I'm trying to achieve 2-way comms over USB (COM port) between Raspberry Pi Pico and Windows PC (Python).
The point is, that I'm unable to send anything from my PC to raspberry nor the way back.
Doesn't affect the LEDs on breadboard, nor the messages get printe... | Serial communication with Raspberry Pi Pico and Python | I'm trying to achieve 2-way comms over USB (COM port) between Raspberry Pi Pico and Windows PC (Python).
The point is, that I'm unable to send anything from my PC to raspberry nor the way back.
Doesn't affect the LEDs on breadboard, nor the messages get printed in terminal.
Here's the code for PC:
import serial
import ... | [
"Easiest Solution\nSerial communication is purely bi-directional. There cannot be more than 2 devices on a given serial port. In Thonny (and micropython) this is dedicated to loading code. You cannot directly write to the serial port from your computer when a program is running. When a program isn't running on the ... | [
0
] | [] | [] | [
"micropython",
"python",
"raspberry_pi_pico",
"usbserial"
] | stackoverflow_0074390514_micropython_python_raspberry_pi_pico_usbserial.txt |
Q:
how can i connect my google sql postgres to my django application?
I have create my google postgres instance on cloud sql service, and i couldn't connect it with my django application,
in the link below they give sqlalchemy configuration, but nothing about the database host
[cloud.google](https://cloud.google.com... | how can i connect my google sql postgres to my django application? | I have create my google postgres instance on cloud sql service, and i couldn't connect it with my django application,
in the link below they give sqlalchemy configuration, but nothing about the database host
[cloud.google](https://cloud.google.com/sql/docs/postgres/connect-admin-proxy#debianubuntu )
This is
my databa... | [
"You'll need to either:\n\nRun the Cloud SQL Auth Proxy locally next to your Django app\nAllowlist your machine's IP address using Authorized Networks\n\nThere's more about the Proxy here:\n\nhttps://github.com/GoogleCloudPlatform/cloud-sql-proxy and\nhttps://cloud.google.com/sql/docs/postgres/connect-admin-proxy\n... | [
1
] | [] | [] | [
"django",
"docker",
"google_cloud_sql",
"postgresql",
"python"
] | stackoverflow_0074379278_django_docker_google_cloud_sql_postgresql_python.txt |
Q:
Python Tkinter for loop checkbuttons not working as intended
having trouble with tkinter and making checkbuttons through a for loop.
i need to create a dynamic amount of buttons based on a previously created list.
With this code, all of the buttons get ticked and unticked at the same time when i click one of them.... | Python Tkinter for loop checkbuttons not working as intended | having trouble with tkinter and making checkbuttons through a for loop.
i need to create a dynamic amount of buttons based on a previously created list.
With this code, all of the buttons get ticked and unticked at the same time when i click one of them.
also, calling checktab[i] doesn't actually give me the value the ... | [
"Tkinter uses IntVars to keep track of the value of a checkbutton. You can't just use a normal integer. Changing\nchecktab.append(0)\n\nto\nchecktab.append(tkinter.IntVar())\n\nshould work. You can then use checktab[i].get() to get the value of the IntVar.\n"
] | [
2
] | [] | [] | [
"for_loop",
"python",
"tkinter",
"tkinter.checkbutton"
] | stackoverflow_0074392602_for_loop_python_tkinter_tkinter.checkbutton.txt |
Q:
Python 3.x Shifting Ranges
suppose I have a range like this:
x = range(10)
which would have the following values as a list:
list(x) # Prints [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
I would like to shift this range (possibly multiple times)
and iterate over the results e.g.
# [7, 8, 9, 0, 1, 2, 3,... | Python 3.x Shifting Ranges | suppose I have a range like this:
x = range(10)
which would have the following values as a list:
list(x) # Prints [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
I would like to shift this range (possibly multiple times)
and iterate over the results e.g.
# [7, 8, 9, 0, 1, 2, 3, 4, 5, 6]
Creating an equivalen... | [
"You can wrap the range in a generator expression, applying the shift and modulo on the fly:\ndef shifted_range(rangeob, shift):\n size, shift = rangeob.stop, shift * rangeob.step\n return ((i + shift) % size for i in rangeob)\n\nDemo:\n>>> def shifted_range(rangeob, shift):\n... size, shift = rangeob.sto... | [
7,
1,
1,
0
] | [] | [] | [
"loops",
"python",
"python_3.x",
"range"
] | stackoverflow_0026633561_loops_python_python_3.x_range.txt |
Q:
Python, re.match with regex
I have a code where I am trying to match strings. My regex may be wrong or it could be my re_year not being read in properly.
code:
Fiscal_Year = 2023
re_year = re.compile(f'^StackOverFlow-{Fiscal_Year}-\d+$')
for idx, row in df.iterrows():
# Ensure it's for the current Fiscal_Y... | Python, re.match with regex | I have a code where I am trying to match strings. My regex may be wrong or it could be my re_year not being read in properly.
code:
Fiscal_Year = 2023
re_year = re.compile(f'^StackOverFlow-{Fiscal_Year}-\d+$')
for idx, row in df.iterrows():
# Ensure it's for the current Fiscal_Year
if not re.match(re_year,... | [
"Your re is wrong. It would match something like StackOverFlow-2023-0704 but not if the second group number repeats do\nre.compile(f'^StackOverFlow-{Fiscal_Year}[-\\d+]+$')\nAlso your string ends with '-' not digits. Add that to the end of the regex using '-*' if you want 0 or more times, '-+' for 1 or more times ... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074392611_python.txt |
Q:
How to create nested loop in python?
In python I'm trying to write nested loops in one line. I've seen a lot of examples, but in all of them the inner iterable variable is different compared to the outer one. So in my case, it won't work. Here's my try:
my_list = [for ip in subnet for subnet in subnets]
where I'm... | How to create nested loop in python? | In python I'm trying to write nested loops in one line. I've seen a lot of examples, but in all of them the inner iterable variable is different compared to the outer one. So in my case, it won't work. Here's my try:
my_list = [for ip in subnet for subnet in subnets]
where I'm getting:
Unresolved reference 'subnet'
| [
"There is a syntax error, it should be\nmy_list = [ip for subnet in subnets for ip in subnet]\n\n"
] | [
1
] | [
"Try with this\nmy_list = [[ip for ip in subnet] for subnet in subnets]\n\nis a way to nest loops in list comprehension\nCan check this too https://www.geeksforgeeks.org/nested-list-comprehensions-in-python/\n"
] | [
-1
] | [
"for_loop",
"python",
"python_3.x"
] | stackoverflow_0074392634_for_loop_python_python_3.x.txt |
Q:
Visual Studio Code - Python debugging - Step into the code of external functions when executing
In a Python project, how do you tell the built-in VSCode debugger to step into the code of functions from other libraries on execution?
I know it is possible for functions implemented in standard libraries by adding a
... | Visual Studio Code - Python debugging - Step into the code of external functions when executing | In a Python project, how do you tell the built-in VSCode debugger to step into the code of functions from other libraries on execution?
I know it is possible for functions implemented in standard libraries by adding a
"debugOptions": ["DebugStdLib"]
to your configuration in launch.json as specified here, however it d... | [
"In order to improve the accepted answer by John Smith, it is worth mentioning that now the option has been renamed again. The new option is \n\"justMyCode\": false\n\nand as per the documentation \n\nWhen omitted or set to True (the default), restricts debugging to\n user-written code only. Set to False to also e... | [
135,
13,
6,
3,
1
] | [] | [] | [
"debugging",
"python",
"visual_studio_code"
] | stackoverflow_0053594900_debugging_python_visual_studio_code.txt |
Q:
How to print the updated output
I need help with my code because it doesn't print the updated output
For example:
Enter First name: Cid
Enter Middle name: RAZOR
Enter Last name: Kamisato
Enter number of subjects: 1
Please enter this valid subjects: ['CC1', 'CC2', 'CC3', 'CC4', 'CC5']
Please enter the subject: cc1
... | How to print the updated output | I need help with my code because it doesn't print the updated output
For example:
Enter First name: Cid
Enter Middle name: RAZOR
Enter Last name: Kamisato
Enter number of subjects: 1
Please enter this valid subjects: ['CC1', 'CC2', 'CC3', 'CC4', 'CC5']
Please enter the subject: cc1
**** This is your info *****
First na... | [
"When you change one of the fields, you use a different variable than the one you use when printing out the info after changing other fields. E.g. you assign the new first name to cf_name, but the rest of the code expects it to be in name. You need to use the same variable consistently.\nSo change\n if option1 =... | [
0
] | [] | [] | [
"if_statement",
"python",
"while_loop"
] | stackoverflow_0074392316_if_statement_python_while_loop.txt |
Q:
First numbers stuck together and horizontal in the label (tkinter)
im makin a machine for prime number,But I want the output of the numbers to be stuck together and horizontal, for example:
>>2,3,5,7,11,13,......
but machine do this:
It is neither horizontal nor joined together
my code:
from tkinter import *
def... | First numbers stuck together and horizontal in the label (tkinter) | im makin a machine for prime number,But I want the output of the numbers to be stuck together and horizontal, for example:
>>2,3,5,7,11,13,......
but machine do this:
It is neither horizontal nor joined together
my code:
from tkinter import *
def prime():
a = int(spin.get())
for number in range(a + 1):
... | [
"You can do this by storing the numbers in a list (result) and then joining them at the end.\ndef prime():\n a = int(spin.get())\n result = []\n for number in range(a + 1):\n if number > 1:\n for i in range(2,number):\n if (number % i) == 0:\n break\n ... | [
3
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074392637_python_tkinter.txt |
Q:
How to implement custom authentication on function based view in django rest framework?
if i have created a custom Authentication
class CustomAuthentication(BaseAuthentication):
def authenticate(self, request):
return super().authenticate(request)
how do I implement this in function based views?
Norma... | How to implement custom authentication on function based view in django rest framework? | if i have created a custom Authentication
class CustomAuthentication(BaseAuthentication):
def authenticate(self, request):
return super().authenticate(request)
how do I implement this in function based views?
Normally we can use decorators as
from rest_framework.authentication import SessionAuthentication,... | [
"Try adding @permission_classes([IsAuthenticated]) to your function\n@authentication_classes([CustomAuthentication])\n@permission_classes([IsAuthenticated])\ndef view(request):\n pass\n\n"
] | [
0
] | [] | [] | [
"django",
"django_authentication",
"django_rest_framework",
"django_views",
"python"
] | stackoverflow_0074389322_django_django_authentication_django_rest_framework_django_views_python.txt |
Q:
find words that matches the 3 consecutive vowels Regex
text = "Life is beautiful"
pattern = r"[aeiou]{3,}"
result = re.findall(pattern, text)
print(result)
desired result:
['beautiful']
the output I get:
['eau']
I have tried googling and etc....I found multiple answers but none of them worked!!
I am new to regex ... | find words that matches the 3 consecutive vowels Regex | text = "Life is beautiful"
pattern = r"[aeiou]{3,}"
result = re.findall(pattern, text)
print(result)
desired result:
['beautiful']
the output I get:
['eau']
I have tried googling and etc....I found multiple answers but none of them worked!!
I am new to regex so maybe I am having issues but I am not sure how to get thi... | [
"Your regex only captures the 3 consecutive vowels, so you need to expand it to capture the rest of the word. This can be done by looking for a sequence of letters between two word breaks and using a positive lookahead for 3 consecutive vowels within the sequence. For example:\nimport re\n\ntext = \"Life is beautif... | [
4,
0,
0,
0
] | [] | [] | [
"findandmodify",
"python",
"regex",
"string"
] | stackoverflow_0062077928_findandmodify_python_regex_string.txt |
Q:
How to force display of x- and y-axis for each subplot in plotly.express
I want to plot a histogram with row and colum facets using plotly.express.histogram() where each subplot gets its own x- and y-axis (for better readability). When looking at the documentation (e.g. go to section "Histogram Facet Grids") I can... | How to force display of x- and y-axis for each subplot in plotly.express | I want to plot a histogram with row and colum facets using plotly.express.histogram() where each subplot gets its own x- and y-axis (for better readability). When looking at the documentation (e.g. go to section "Histogram Facet Grids") I can see a lot of examples where the x- and y-axes are repeated. But in my case, t... | [
"All you need to do is to customize each y and x axis by:\nfig.for_each_yaxis(lambda y: y.update(showticklabels=True,matches=None))\nfig.for_each_xaxis(lambda x: x.update(showticklabels=True,matches=None))\n\nOutput\n\n"
] | [
0
] | [] | [] | [
"histogram",
"plotly",
"python",
"subplot"
] | stackoverflow_0074392223_histogram_plotly_python_subplot.txt |
Q:
How do I make two functions share a variable?
My assignment is to make a secret number, which is 26, and make a guessing game saying the guess is either "too low" or "too high". I made two functions, int_guess for if the input is an integer and not_int_guess for when the input is not an integer. The problem that i... | How do I make two functions share a variable? | My assignment is to make a secret number, which is 26, and make a guessing game saying the guess is either "too low" or "too high". I made two functions, int_guess for if the input is an integer and not_int_guess for when the input is not an integer. The problem that i have though is when im counting the amount of gues... | [
"Instead of using two functions, use the try and except within the while loop. That was everything is much neater and more efficient (also good to define functions before any main code):\ndef int_guess(secret_num):\n count = 0\n guess = 0 #Just defining it here so everything in the function knows about it\n ... | [
0,
0
] | [] | [] | [
"python",
"try_except"
] | stackoverflow_0074392525_python_try_except.txt |
Q:
search for data from a list in MongoDB
my database looks like:
{'_id': ObjectId('3f05e2aa794e17504a6674a7'),
'lt': [
{'_id': ObjectId('6f05e2aa794e177b456674a9'), 'name': 'text1'},
{'_id': ObjectId('2f05e2aa794e1765286674a8'),'name': 'text3', }
]
}
{'_id': ObjectId('3f05e3aa791e17f23b6674aa'),
'lt... | search for data from a list in MongoDB | my database looks like:
{'_id': ObjectId('3f05e2aa794e17504a6674a7'),
'lt': [
{'_id': ObjectId('6f05e2aa794e177b456674a9'), 'name': 'text1'},
{'_id': ObjectId('2f05e2aa794e1765286674a8'),'name': 'text3', }
]
}
{'_id': ObjectId('3f05e3aa791e17f23b6674aa'),
'lt': [
{'_id': ObjectId('7f05e2aa494e17f5b... | [
"You can use an aggregate pipeline using $filter like this:\nThis query project the result using $project showing only the values into lt that are also into your array.\ndb.collection.aggregate([\n {\n \"$project\": {\n \"_id\": 0,\n \"lt\": {\n \"$filter\": {\n \"input\": \"$lt\",\n ... | [
0
] | [] | [] | [
"mongodb",
"python"
] | stackoverflow_0074391734_mongodb_python.txt |
Q:
Why is my beautiful soup scraper returning no text? The script doesnt throw an error
#scraping ESPN
from bs4 import BeautifulSoup
import requests
html_text = requests.get('https://www.espn.com/womens-college-basketball/scoreboard/_/date/20221107').text
soup = BeautifulSoup(html_text, 'lxml')
game = soup.find('u... | Why is my beautiful soup scraper returning no text? The script doesnt throw an error | #scraping ESPN
from bs4 import BeautifulSoup
import requests
html_text = requests.get('https://www.espn.com/womens-college-basketball/scoreboard/_/date/20221107').text
soup = BeautifulSoup(html_text, 'lxml')
game = soup.find('ul', class_= "ScoreCell__Competitors").text
[enter image description here][1]print(game)
... | [
"Try using Selenium with chrome\nDownload Chrome and Chromedrive\nInstall selenium\npip install selenium\nfrom selenium import webdriver\n\nDRIVER_PATH = '/path/to/chromedriver'\ndriver = webdriver.Chrome(executable_path=DRIVER_PATH)\ndriver.get('https://google.com')\n\nGet the element using your class name using t... | [
0
] | [] | [] | [
"beautifulsoup",
"python",
"web_scraping"
] | stackoverflow_0074392583_beautifulsoup_python_web_scraping.txt |
Q:
Renaming image files with PyExifTool 0.5.4 (exiftool in python)
I'm trying to rename jpg files from a python script with exiftool using PyExifTool 0.5.4.
I can change tags, e.g. DateTimeOriginal, but when I try to rename files using tags I can't get the correct formatting for the filename.
with exiftool.ExifToolHe... | Renaming image files with PyExifTool 0.5.4 (exiftool in python) | I'm trying to rename jpg files from a python script with exiftool using PyExifTool 0.5.4.
I can change tags, e.g. DateTimeOriginal, but when I try to rename files using tags I can't get the correct formatting for the filename.
with exiftool.ExifToolHelper() as et:
et.execute('-d %Y-%m.%%e', '-filename<DateTimeOrigi... | [
"dropf, your call to execute() is incorrect. The parameter '-d %Y-%m.%%e' needs to be two different parameters to ExifToolHelper.execute()\nwith exiftool.ExifToolHelper() as et:\n et.execute('-d', '%Y-%m.%%e', '-filename<DateTimeOriginal', os.path.join(subdir, file))\n\nThis is the way that execute() works. If... | [
0
] | [] | [] | [
"exiftool",
"python"
] | stackoverflow_0074305074_exiftool_python.txt |
Q:
How do I set dataframe names from a list of names?
I have a list of pdb codes:
proteins = ['1h1p', '1h1s', '1pmn', '1q41', '1u4d_a', '1u4d_b', '1unl', '2br1']
I want to initialise an empty dataframe for each protein and name it after its code.
so I end up with 8 empty dataframes named:
dataframes = [1h1p, 1h1s, 1... | How do I set dataframe names from a list of names? | I have a list of pdb codes:
proteins = ['1h1p', '1h1s', '1pmn', '1q41', '1u4d_a', '1u4d_b', '1unl', '2br1']
I want to initialise an empty dataframe for each protein and name it after its code.
so I end up with 8 empty dataframes named:
dataframes = [1h1p, 1h1s, 1pmn, 1q41, 1u4d_a, 1u4d_b, 1unl, 2br1]
How do I do this... | [
"import pandas as pd\n\nproteins = ['1h1p', '1h1s', '1pmn', '1q41', '1u4d_a', '1u4d_b', '1unl', '2br1']\ndata = {k:[] for k in proteins}\ndf = pd.DataFrame(data)\n\n"
] | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074391806_pandas_python.txt |
Q:
Quiz listbox items displaying in one line
I am trying to show the options for quiz questions in a listbox. The value will later be retrieved with a button. They show as one line instead of different listed items. I think it has something to do with the list and how it is formatted, but I am not sure how to fix thi... | Quiz listbox items displaying in one line | I am trying to show the options for quiz questions in a listbox. The value will later be retrieved with a button. They show as one line instead of different listed items. I think it has something to do with the list and how it is formatted, but I am not sure how to fix this. How can I fix this?
from tkinter import *
fr... | [
"my_list only contains one item, labeled_alternative, so when you iterate it in the for loop, the entire dictionary gets inserted. Instead, you want to iterate labeled_alternatives.items() to get the keys and values for each item in your dictionary. Change the for loop to\nfor k, v in labeled_alternatives.items():\... | [
1
] | [] | [] | [
"list",
"listbox",
"python",
"tkinter",
"tuples"
] | stackoverflow_0074392538_list_listbox_python_tkinter_tuples.txt |
Q:
pyenv giving errors after trying to install python 3.6.9
i am currently on Kali Linux and after i wrote "pyenv install python3.6.9" it gave me this:the error can someone help?
BUILD FAILED (Kali 2022.2 using python-build 2.3.3) Inspect or clean up the working tree at /tmp/python-build.20220804174325.3014
Results l... | pyenv giving errors after trying to install python 3.6.9 | i am currently on Kali Linux and after i wrote "pyenv install python3.6.9" it gave me this:the error can someone help?
BUILD FAILED (Kali 2022.2 using python-build 2.3.3) Inspect or clean up the working tree at /tmp/python-build.20220804174325.3014
Results logged to /tmp/python-build.20220804174325.3014.log
Last 10 log... | [
"Try this:\nsudo apt install gcc-10\nCC=gcc-10 pyenv install 3.6.9\n\n"
] | [
0
] | [] | [] | [
"linux",
"python"
] | stackoverflow_0073239153_linux_python.txt |
Q:
Pycharm jupyter cell background
I'm using PyCharm with Darcula theme and Jupyter notebook from anaconda package.
I faced a problem that Darcula theme is inconvinient to use with Jupyter notebook
For example, pandas plot's axis is not readable.
I tried to find out, how to change notebook cell background, but looks... | Pycharm jupyter cell background | I'm using PyCharm with Darcula theme and Jupyter notebook from anaconda package.
I faced a problem that Darcula theme is inconvinient to use with Jupyter notebook
For example, pandas plot's axis is not readable.
I tried to find out, how to change notebook cell background, but looks like that there is no possibility to... | [
"Per https://stackoverflow.com/a/40371037/2529760, you can use\nfig = plt.figure()\nfig.patch.set_facecolor('white')\n\nor \nplt.gca().patch.set_facecolor('white')\n\nto force a white background beneath the axis labels on a per-plot basis. You can use\nplt.rcParams['figure.facecolor'] = 'white'\n\nto achieve this o... | [
2,
1,
1,
0
] | [] | [] | [
"jupyter_notebook",
"pycharm",
"python"
] | stackoverflow_0046343865_jupyter_notebook_pycharm_python.txt |
Q:
pyparsing list of lists and values
A mock version of the code that I am trying is the following. I have many more cases of what a SingleValue is, and other constructions, but this is the part I am failing to represent.
import pyparsing as pp
SingleValue = pp.Word(pp.alphas) # Single values are strings of letters... | pyparsing list of lists and values | A mock version of the code that I am trying is the following. I have many more cases of what a SingleValue is, and other constructions, but this is the part I am failing to represent.
import pyparsing as pp
SingleValue = pp.Word(pp.alphas) # Single values are strings of letters
ListOfValues = pp.Forward() # To be de... | [
"The pyparsing moduleβs default behaviour is to ignore the leading whitespace. (see 1.1.2 Usage notes)\nThat means Literal(' ') won't match and delimited_list will stop parsing\nFor non-skipping whitespace, there is pp.White:\nListOfValues <<= '{' + pp.delimited_list(Values, delim=pp.White(' ')) + '}'\n\nYou could ... | [
1
] | [] | [] | [
"pyparsing",
"python"
] | stackoverflow_0074391264_pyparsing_python.txt |
Q:
Websockets send message in sync function
I'm using websockets and asyncio to manage connections in my app.
The send method is async
async def send(self, message):
logging.debug('send {}'.format(message))
await self.websocket.send(message)
and i usually use it in async threads and everything is ok.... | Websockets send message in sync function | I'm using websockets and asyncio to manage connections in my app.
The send method is async
async def send(self, message):
logging.debug('send {}'.format(message))
await self.websocket.send(message)
and i usually use it in async threads and everything is ok.
There is only one situation where i need to c... | [
"On the one thread which is running the async code you should launch a task that goes listening to a queue - and whenever it gets something, it processes the request and post the result back.\nThat way on the sync thread you just have to post to that queue and wait for the result. The Queue iteself is for inter-thr... | [
0
] | [] | [] | [
"python",
"python_3.x",
"python_asyncio"
] | stackoverflow_0074385888_python_python_3.x_python_asyncio.txt |
Q:
Dask and persistence of data on the cluster
I am working on a project that uses historical data and also incoming data for analysis. I would like to learn how to manage updating incoming data on dask while not having to dispatch all the historical data every time.
I gather data for time series for analysis, but t... | Dask and persistence of data on the cluster | I am working on a project that uses historical data and also incoming data for analysis. I would like to learn how to manage updating incoming data on dask while not having to dispatch all the historical data every time.
I gather data for time series for analysis, but the time series grow with incoming data, and the i... | [
"This might not be the right solution, but one possibility is to designate specific workers to perform specific computations. For example, let's separate the workers into two groups:\n# instantiate workers\nfrom distributed import Client\nc = Client(n_workers=5)\n\n# here the separation is done based on order\n# bu... | [
1
] | [] | [] | [
"dask",
"directed_acyclic_graphs",
"python"
] | stackoverflow_0074367670_dask_directed_acyclic_graphs_python.txt |
Q:
How to extract last three chars from word if they are uppercase?
How to extract last three chars from word if they are uppercase?
a = "aaaAAA"
b = "bbbbBBB"
c = "ccc CCC"
d = "dddddDDD"
e = "eeeEEEE"
My function:
def get_three(value):
search = re.search("[A-Z]{3}$", value)
if search:
return s... | How to extract last three chars from word if they are uppercase? | How to extract last three chars from word if they are uppercase?
a = "aaaAAA"
b = "bbbbBBB"
c = "ccc CCC"
d = "dddddDDD"
e = "eeeEEEE"
My function:
def get_three(value):
search = re.search("[A-Z]{3}$", value)
if search:
return search.group(0)
return "NONE"
It returns:
AAA
BBB
CCC
DDD
EEE
... | [
"You can use a negative lookbehind:\n(?<![A-Z])[A-Z]{3}$\n\nSee the regex demo.\nDetails:\n\n(?<![A-Z]) - a negative lookbehind that fails the match if there is an uppercase letter immediately to the left of the current location\n[A-Z]{3} - three uppercase letters\n$ - end of string.\n\nIf you need to support any U... | [
2
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0074392913_python_regex.txt |
Q:
Removing multiple values from ndarray at random
I need to remove multiple elements, specifically 11 samples from a Numpy array object with shape (5891, 10) so that when converted to 3d array, its second dimension = 6 in the resultant shape (-1, 6, 10). Need some help in this regard.
array([[-0.0296606 , -0.8663941... | Removing multiple values from ndarray at random | I need to remove multiple elements, specifically 11 samples from a Numpy array object with shape (5891, 10) so that when converted to 3d array, its second dimension = 6 in the resultant shape (-1, 6, 10). Need some help in this regard.
array([[-0.0296606 , -0.86639415, 1.31166578, ..., -0.56398655,
-0.62098712, -... | [
"arr = np.random.random((5891, 10))\n\n# set a static seed if you want reproducability of the choices\nrng = np.random.default_rng(seed=42)\n\n# choose all but 11 rows\nchosen = rng.choice(arr, size=arr.shape[0] - 11, replace=False, axis=0)\n\n# and reshape\nout = chosen.reshape((-1, 6, 10))\n\n"
] | [
0
] | [] | [] | [
"arrays",
"numpy",
"python"
] | stackoverflow_0074392896_arrays_numpy_python.txt |
Q:
Get same characters from 2 lists in right order - Python
I have two lists and I need to print matching characters to string in order of characters in list 2. If there is no match, i need to print "-" instead of that character. Final string should have same length of chars as list 2
Example 1 :
list 1 = ["r", "w", ... | Get same characters from 2 lists in right order - Python | I have two lists and I need to print matching characters to string in order of characters in list 2. If there is no match, i need to print "-" instead of that character. Final string should have same length of chars as list 2
Example 1 :
list 1 = ["r", "w", "d"]
list 2 = ["w", "o", "r", "d"]
Expected output = W - R D
... | [
"You can use list comprehension to check if the character in actual word (list2) is present in the list1 or not so:\nlist1 = [\"r\", \"w\", \"d\"]\nlist2 = [\"w\", \"o\", \"r\", \"d\"]\nprint(' '.join([i.upper() if i in list1 else '-' for i in list2]))\n\nOutput:\nW - R D\n\n\nYou can optionally create a set from l... | [
2,
1,
0
] | [] | [] | [
"list",
"python",
"string"
] | stackoverflow_0074392814_list_python_string.txt |
Q:
Python pip install error [SSL: CERTIFICATE_VERIFY_FAILED]
I have been trying to figure this out for a while now and for some reason I get stuck with an ssl issue and have no idea what is going on.
Problem:
I have installed python2.7 and easy_install2.7, but when trying to install pip with easy_install2.7 I get the... | Python pip install error [SSL: CERTIFICATE_VERIFY_FAILED] | I have been trying to figure this out for a while now and for some reason I get stuck with an ssl issue and have no idea what is going on.
Problem:
I have installed python2.7 and easy_install2.7, but when trying to install pip with easy_install2.7 I get the following error.
[root@cops-wc-01]# /usr/local/bin/easy_instal... | [
"apt-get install ca-certificates\n\nIf you missed this package.\n",
"On my device (that runs nix), \n$ date showed ...1969\n\nso I had to set the date to a more recent time :\n$ date -s \"26 MAR 2017 13:16:00\"\n\nThen the SSL error was gone.\n",
"YAS (Yet Another Solution)\nI had the same issue.\nTried everyth... | [
6,
4,
1,
0,
0,
0,
0,
0,
0,
0
] | [] | [] | [
"centos",
"python"
] | stackoverflow_0032772895_centos_python.txt |
Q:
Python: from list of decimal to hours / minutes
I have a list like the following:
T = [10.749957462142994, 10.90579301143351, 10.981580990083001]
That contains timestamp in a decimal format
hours = [ int(x) for x in T ]
minutes =[ (x*60) % 60 for x in T]
print("%d:%02d"%(hours[0], minutes[0]), "%d:%02d"%(hours[... | Python: from list of decimal to hours / minutes | I have a list like the following:
T = [10.749957462142994, 10.90579301143351, 10.981580990083001]
That contains timestamp in a decimal format
hours = [ int(x) for x in T ]
minutes =[ (x*60) % 60 for x in T]
print("%d:%02d"%(hours[0], minutes[0]), "%d:%02d"%(hours[1], minutes[1]), "%d:%02d"%(hours[2], minutes[2]))
['... | [
"Here's a simple way to do it:\nimport datetime\n\nDUMMY_DATETIME = datetime.datetime(2000, 1, 1, 0, 0)\nHOUR = datetime.timedelta(hours=1)\n\nT = [10.749957462142994, 10.90579301143351, 10.981580990083001]\nDT = [(DUMMY_DATETIME + hours * HOUR).time() for hours in T]\n\nA timedelta can be multiplied by a float (au... | [
1,
1,
0
] | [] | [] | [
"datetime",
"python"
] | stackoverflow_0074392708_datetime_python.txt |
Q:
Measure line thickness image processing
I'm new to coding (use python) and working on line pattern defect detection. I have located all the defect with deep-learning and now want to measure the thickness of the line.
I isolated each bounding box and image proccess every defect.
So far these steps what i have done:... | Measure line thickness image processing | I'm new to coding (use python) and working on line pattern defect detection. I have located all the defect with deep-learning and now want to measure the thickness of the line.
I isolated each bounding box and image proccess every defect.
So far these steps what i have done:
OpenCV adaptive threshold
Put mask in th... | [
"You could use findContours to get the contour of an individual defect and then use contour moments or other contour properties to estimate the line thickness.\n"
] | [
0
] | [] | [] | [
"computer_vision",
"image_processing",
"opencv",
"python",
"python_3.x"
] | stackoverflow_0074392820_computer_vision_image_processing_opencv_python_python_3.x.txt |
Q:
How to remove a specific fox object from a dictionary while iterating through it
I get a runtime error when i try to remove a fox object from a dictionary when it has starved in my simulation program, how can i fix this?
I tried to use other methods i discovered online, but i kept getting the same error.
import ra... | How to remove a specific fox object from a dictionary while iterating through it | I get a runtime error when i try to remove a fox object from a dictionary when it has starved in my simulation program, how can i fix this?
I tried to use other methods i discovered online, but i kept getting the same error.
import random
class Simulation:
def __init__(self):
self.Foxes = {}
for i ... | [
"Not sure if this is a copy/paste error but your indentation is incorrect. Lines 10-16 under the Main function need to be indented. The entire Main function might also need to be unintended to be equal with the __init__ function depending on how you want to use it.\nclass Simulation:\n def __init__(self):\n ... | [
0,
0
] | [] | [] | [
"oop",
"python"
] | stackoverflow_0074392966_oop_python.txt |
Q:
Python error - "List index out of range" on my code
when I run this code below I am getting IndexError: list index out of range.
I am trying to go through the list "years" and compare the value found in the list to the list of lists "data". I am unsure why I am getting the error below. Any thoughts on why this is ... | Python error - "List index out of range" on my code | when I run this code below I am getting IndexError: list index out of range.
I am trying to go through the list "years" and compare the value found in the list to the list of lists "data". I am unsure why I am getting the error below. Any thoughts on why this is the case?
PS. I am new to writing code... so pls excuse m... | [
"Python indexes lists from 0 and your <= len(data) allows it to go past the end of the list. Should be < len(data). data will range from 0 to len(data) - 1.\n",
"That means you don't have n elements in the \"years\" array, or you don't have y elements in the \"data\" two dimensional array, or the data[y] array ... | [
0,
0,
0
] | [] | [] | [
"for_loop",
"if_statement",
"list",
"python"
] | stackoverflow_0074392937_for_loop_if_statement_list_python.txt |
Q:
Python web-scraping: error 401 You must provide a http header
Before I start let me point out that I have almost no clue wtf I'm doing. Like imagine a cat that tries to do some coding. I try to write some Python code using Pycharm on Ubuntu 22.04.1 LTS and also used Insomnia if this makes any difference. Here is t... | Python web-scraping: error 401 You must provide a http header | Before I start let me point out that I have almost no clue wtf I'm doing. Like imagine a cat that tries to do some coding. I try to write some Python code using Pycharm on Ubuntu 22.04.1 LTS and also used Insomnia if this makes any difference. Here is the code:
`
# sad_scrape_code_attempt.py
import time
import httpx
f... | [
"The page you're navigating to shows this on a GET request:\nHTTP ERROR 401 You must provide a http header 'JWT'\nThis means that this page requires a level of authorization to be accessed.\nSee JWTs.\n\"Authorization: This is the most common scenario for using JWT. Once the user is logged in, each subsequent reque... | [
0
] | [] | [] | [
"http_status_code_401",
"python",
"web_scraping"
] | stackoverflow_0074392663_http_status_code_401_python_web_scraping.txt |
Q:
Problem with training Word2Vec after opening csv
I'm trying to train Word2Vec model. When I try to train the model directly from the Series I get everything is fine, but when I save the DataFrame to csv and then open it, I have a problem.
data = pd.read_csv('test.txt', sep='\r\n', names=['input'], engine="python")... | Problem with training Word2Vec after opening csv | I'm trying to train Word2Vec model. When I try to train the model directly from the Series I get everything is fine, but when I save the DataFrame to csv and then open it, I have a problem.
data = pd.read_csv('test.txt', sep='\r\n', names=['input'], engine="python")
data = data.dropna().drop_duplicates()
data = data['i... | [
"First, it'd help to name the variable holding data that's come from a different place different from the original data, for clarity of reference/comparison.\nFor example, instead of loading your saved data as...\ndata = pd.read_csv('test.csv')['input']\n\n...give it a distinctive name instead:\ndata_from_csv = pd.... | [
1
] | [] | [] | [
"gensim",
"machine_learning",
"pandas",
"python",
"word2vec"
] | stackoverflow_0074392926_gensim_machine_learning_pandas_python_word2vec.txt |
Q:
How to run Google Colab file locally and save Runtime forever
I have a large project I am working on in Google Colab, and every time I close my browser I lose my runtime, which is annoying because I have to run everything again.
Is there any way that I can run my colab .ipynb file locally so that my runtime is sav... | How to run Google Colab file locally and save Runtime forever | I have a large project I am working on in Google Colab, and every time I close my browser I lose my runtime, which is annoying because I have to run everything again.
Is there any way that I can run my colab .ipynb file locally so that my runtime is saved and I don't have to re run every cell?
| [
"Running .ipynb files locally is easy. My way to do it:\nUsing VSCode, you download Jupyter notebook extensions:\nhttps://marketplace.visualstudio.com/items?itemName=ms-toolsai.jupyter\nOpen your .ipynb file and voila, your runtime is saved as long as your computer is running. If you want to save runtime even when ... | [
1,
0
] | [] | [] | [
"artificial_intelligence",
"google_colaboratory",
"python"
] | stackoverflow_0070626388_artificial_intelligence_google_colaboratory_python.txt |
Q:
How to import pairwise function from itertools? Do I need to update itertools?
I have a problem with updating itertools package, so that the pairwise function is available.
I am getting this error:
AttributeError: module 'itertools' has no attribute 'pairwise'
Additionally, this command:
print(itertools.__versio... | How to import pairwise function from itertools? Do I need to update itertools? | I have a problem with updating itertools package, so that the pairwise function is available.
I am getting this error:
AttributeError: module 'itertools' has no attribute 'pairwise'
Additionally, this command:
print(itertools.__version__)
returns:
AttributeError: module 'itertools' has no attribute 'version'
and I... | [
" $ python3.11 -c 'import itertools.pairwise'\nTraceback (most recent call last):\n File \"<string>\", line 1, in <module>\nModuleNotFoundError: No module named 'itertools.pairwise'; 'itertools' is not a package\n\nThis is how it's done\nfrom itertools import pairwise\npairwise(...)\n# OR\nimport itertools\niterto... | [
2
] | [] | [] | [
"python",
"python_itertools"
] | stackoverflow_0074392604_python_python_itertools.txt |
Q:
Flatten a column value using dataframe
Im trying to flatten 2 columns from a table loaded into a dataframe as below:
u_group
t_group
{"link": "https://hi.com/api/now/table/system/2696f18b376bca0", "value": "2696f18b376bca0"}
{"link": "https://hi.com/api/now/table/system/2696f18b376bca0", "value": "2696f18b376bca... | Flatten a column value using dataframe | Im trying to flatten 2 columns from a table loaded into a dataframe as below:
u_group
t_group
{"link": "https://hi.com/api/now/table/system/2696f18b376bca0", "value": "2696f18b376bca0"}
{"link": "https://hi.com/api/now/table/system/2696f18b376bca0", "value": "2696f18b376bca0"}
{"link": "https://hi.com/api/now... | [
"need simple example and code for answer\nexample:\ndata = [[{'link':'A1', 'value':'B1'}, {'link':'A2', 'value':'B2'}], \n [{'link':'C1', 'value':'D1'}, {'link':'C2', 'value':'D2'}]]\ndf = pd.DataFrame(data, columns=['u', 't'])\n\noutput(df):\n u t\n0 {'link': 'A1', 'value'... | [
0,
0
] | [] | [] | [
"pandas",
"pyspark",
"python"
] | stackoverflow_0074392160_pandas_pyspark_python.txt |
Q:
CMake boost_python not found
Hi I'm having some problems with using cmake to build this example. This is what I have:
βββ _build
βΒ Β βββ CMakeCache.txt
βΒ Β βββ CMakeFiles
βΒ Β βββ cmake_install.cmake
βΒ Β βββ Makefile
βββ CMakeLists.txt
βββ hello_ext.cpp
βββ README.md
CMakeLists.txt:
cmake_minimum_required(VERSION ... | CMake boost_python not found | Hi I'm having some problems with using cmake to build this example. This is what I have:
βββ _build
βΒ Β βββ CMakeCache.txt
βΒ Β βββ CMakeFiles
βΒ Β βββ cmake_install.cmake
βΒ Β βββ Makefile
βββ CMakeLists.txt
βββ hello_ext.cpp
βββ README.md
CMakeLists.txt:
cmake_minimum_required(VERSION 3.16.3)
project(test)
# Find py... | [
"As Tsyvarev posted in the comments I just had to removed the config file in /usr/local/lib/cmake/Boost-1.77.0/BoostConfig.cmake and rebuild my project.\n"
] | [
0
] | [] | [] | [
"boost",
"c++",
"cmake",
"python"
] | stackoverflow_0070385287_boost_c++_cmake_python.txt |
Q:
Program don't executes after handling an error
I need to create functions to perform the calculation of the triangle area that include error handling using exceptions.
Def 1: Function named checkTriangleEdges(a, b, c) that verifies:
That the three parameters are greater than 0, and
if the three parameters can for... | Program don't executes after handling an error | I need to create functions to perform the calculation of the triangle area that include error handling using exceptions.
Def 1: Function named checkTriangleEdges(a, b, c) that verifies:
That the three parameters are greater than 0, and
if the three parameters can form a triangle.
Raise a ValueError exception with the ... | [
"Do not use recursion for repeated input. Use a while True loop then break (or, in this case, return) once you have valid inputs.\nReturn values from your functions rather than printing within them.\nFor example:\ndef checkTriangleEdges(a, b, c):\n if a <= 0 or b <= 0 or c <= 0:\n raise ValueError(\"All t... | [
1,
0
] | [] | [] | [
"python",
"python_3.x",
"try_except"
] | stackoverflow_0074392851_python_python_3.x_try_except.txt |
Q:
Passing variables through Selenium send.keys instead of strings
I'm trying to use Selenium for some app testing, and I need it to plug a variable in when filling a form instead of a hardcoded string. IE:
this works
name_element.send_keys("John Doe")
but this doesnt
name_element.send_keys(username)
Does anyone kno... | Passing variables through Selenium send.keys instead of strings | I'm trying to use Selenium for some app testing, and I need it to plug a variable in when filling a form instead of a hardcoded string. IE:
this works
name_element.send_keys("John Doe")
but this doesnt
name_element.send_keys(username)
Does anyone know how I can accomplish this? Pretty big Python noob, but used Google ... | [
"In at least one case, I found that I couldn't pass a variable to send_keys unless I first passed a regular empty string:\ninputElement.send_keys(\"\")\ninputElement.send_keys(my_text_variable)\n\nIt also works as a list:\ninputElement.send_keys(\"\", my_text_variable)\n",
"Try this. \n\nusername = r'John Doe'\n... | [
3,
1,
0,
0,
0,
0
] | [] | [] | [
"python",
"selenium"
] | stackoverflow_0012289700_python_selenium.txt |
Q:
Overflow while using ReadWriteMemory
I'm trying to fetch information from a hex editor. But ReadWriteMemory gives me an error about "<class 'OverflowError'>: int too long to convert"
Here is my code:
from ReadWriteMemory import ReadWriteMemory
base_address = 0x7FF6D60A0000
static_address_offset = 0x0074DE40
point... | Overflow while using ReadWriteMemory | I'm trying to fetch information from a hex editor. But ReadWriteMemory gives me an error about "<class 'OverflowError'>: int too long to convert"
Here is my code:
from ReadWriteMemory import ReadWriteMemory
base_address = 0x7FF6D60A0000
static_address_offset = 0x0074DE40
pointer_static_address = base_address + static_... | [
"I fixed it using 'pymem', So it appears that ReadWriteMemory can't handle 64bit applications.\nfrom pymem import *\nfrom pymem.process import *\n\npm = Pymem('010Editor.exe')\n\ndef GetByteNumber():\n def GetPtrAddr(base, offsets):\n addr = pm.read_longlong(base)\n for i in offsets:\n i... | [
0
] | [] | [] | [
"python",
"ram"
] | stackoverflow_0074348681_python_ram.txt |
Q:
If, Else not working when checking if function is true
I am a beginner in Python programming. Recently I decided to build an Audio assistant(basically a chatbot with audio), but I ran into an issue when trying to produce the Outputs. I wrote the code in a way that if what the user says/asks the bot to do, is somet... | If, Else not working when checking if function is true | I am a beginner in Python programming. Recently I decided to build an Audio assistant(basically a chatbot with audio), but I ran into an issue when trying to produce the Outputs. I wrote the code in a way that if what the user says/asks the bot to do, is something which has not been defined to the bot or it does not ha... | [
"Although it is common in English (and other human languages) to say things like:\n\nif X and Y are in Z...\n\n⦠that is not quite how boolean logic works.\nWhat you've actually written is parsed more like this:\n\nif X-and-Y is in Z...\n\nAnd something like ('hi' and 'hru') is going to give you a useless result ('... | [
1,
0
] | [] | [] | [
"chatbot",
"if_statement",
"python"
] | stackoverflow_0060774953_chatbot_if_statement_python.txt |
Q:
What command can fix visual output (layout)
Can someone tell me why the columns are arranged like that or tell how to fix it ?
Thanks
# import libraries
import numpy as np
import pandas as pd
from time import time
import mysql.connector
from IPython.display import display # Allows the use display() for datafram... | What command can fix visual output (layout) | Can someone tell me why the columns are arranged like that or tell how to fix it ?
Thanks
# import libraries
import numpy as np
import pandas as pd
from time import time
import mysql.connector
from IPython.display import display # Allows the use display() for dataframes
data = pd.read_csv("car_dataset.csv", delimit... | [
"If you look closely, your data is delimited by , not ;. Remove the delimiter parameter.\ndata = pd.read_csv(\"car_dataset.csv\")\n\n"
] | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074392903_dataframe_pandas_python.txt |
Q:
Iterate through pandas dataframe, creating new field from existing field based on conditions
Here I have some logic for this process:
if(group_member_df['group_email'].astype(str).str.startswith("gcp") is True):
group_member_df['group_code'] = (group_member_df['group_email'].str.extract('(?:prod-)(.*)-'))
... | Iterate through pandas dataframe, creating new field from existing field based on conditions | Here I have some logic for this process:
if(group_member_df['group_email'].astype(str).str.startswith("gcp") is True):
group_member_df['group_code'] = (group_member_df['group_email'].str.extract('(?:prod-)(.*)-'))
elif(group_member_df['group_email'].astype(str).str.startswith("irm") is True):
g... | [
"Given the logic doesn't seem to convoluted, I would consider using a nested np.where() for efficiency.\ngroup_member_df['group_code'] = np.where(group_member_df.str.startswith(\"gcp\"),\n group_member_df.str.extract('(?:prod-)(.*)-'),\n ... | [
0
] | [] | [] | [
"dataframe",
"iterator",
"loops",
"pandas",
"python"
] | stackoverflow_0074393364_dataframe_iterator_loops_pandas_python.txt |
Q:
How can I create an API index using multiple DRF routers?
I'm trying to build an API using DRF with the following structure (example):
api/
βββ v1/
β βββ foo/
β β βββ bar/
β β β βββ urls.py # There's one `rest_framework.routers.DefaultRouter` here
β β βββ bar2/
β β β βββ urls.py # There's one... | How can I create an API index using multiple DRF routers? | I'm trying to build an API using DRF with the following structure (example):
api/
βββ v1/
β βββ foo/
β β βββ bar/
β β β βββ urls.py # There's one `rest_framework.routers.DefaultRouter` here
β β βββ bar2/
β β β βββ urls.py # There's one `rest_framework.routers.DefaultRouter` here
β β βββ __init... | [
"I ended up writing an IndexRouter class, which then can be used as the following:\n\nExample 1: reusing your urlpatterns:\n\nyour_old_urlpatterns = []\nrouter = IndexRouter(urlpatterns=your_old_urlpatterns)\nurlpatterns = router.to_urlpatterns()\n\n\nExample 2: using other DRF routers:\n\nfrom my_app.urls import r... | [
0
] | [] | [] | [
"django",
"django_rest_framework",
"drf_nested_routers",
"python"
] | stackoverflow_0074353176_django_django_rest_framework_drf_nested_routers_python.txt |
Q:
Dictionary Initializers in pandas library
import pandas as pd
grades = pd.Series({'Wally': 87, 'Eva': 100, 'Sam': 94},index=['a', 'b', 'c'])
print(grades)
output:
a NaN
b NaN
c NaN
dtype: float64
why this output? I searched in diffrent site but I don't understand this output, when use index ... | Dictionary Initializers in pandas library | import pandas as pd
grades = pd.Series({'Wally': 87, 'Eva': 100, 'Sam': 94},index=['a', 'b', 'c'])
print(grades)
output:
a NaN
b NaN
c NaN
dtype: float64
why this output? I searched in diffrent site but I don't understand this output, when use index attribute in dictionary initializer. Please exp... | [
"read pd.Series document\nhttps://pandas.pydata.org/docs/reference/api/pandas.Series.html\n\nindex : array-like or Index (1d) \nValues must be hashable and have the same length as data. Non-unique index values are allowed. Will default to RangeIndex (0, 1, 2, β¦, n) if not provided. If data is dict-like and index is... | [
0
] | [] | [] | [
"dictionary",
"pandas",
"python",
"series"
] | stackoverflow_0074393362_dictionary_pandas_python_series.txt |
Q:
Adding to a list of list of integers
I have a list x = [[2873, 5321, 5421], [2788, 5171, 5271], [2788, 5171, 5271]].
I want to add y = 400, to each of the elements in the list.
The output should be z = [3273, 5721, 5821], 3188, 5571, 5671], [3188, 5571, 5671]]
I tried by using
def add(x,y):
addlists=[(x[i] + y) f... | Adding to a list of list of integers | I have a list x = [[2873, 5321, 5421], [2788, 5171, 5271], [2788, 5171, 5271]].
I want to add y = 400, to each of the elements in the list.
The output should be z = [3273, 5721, 5821], 3188, 5571, 5671], [3188, 5571, 5671]]
I tried by using
def add(x,y):
addlists=[(x[i] + y) for i in range(len(x))]
return addlists... | [
"As another approach, if you wanted to go as far as using numpy you can use the following.\nDepending on the size of your dataset, this approach might provide some efficiency gains over using nested loops, as numpy employs a method known as 'broadcasting' to apply a given operation to each value in the array, rathe... | [
2,
0
] | [] | [] | [
"add",
"function",
"list",
"python"
] | stackoverflow_0074393232_add_function_list_python.txt |
Q:
Geocode: Module has no attribute "google"
I know several have already asked similar questions but I'm a beginner and trying to figure this out for days and no luck yet.
I want to geocoder and execute geocoder.google command to get the latitude and longitude of the location but "google" attribute doesn't seem to be... | Geocode: Module has no attribute "google" | I know several have already asked similar questions but I'm a beginner and trying to figure this out for days and no luck yet.
I want to geocoder and execute geocoder.google command to get the latitude and longitude of the location but "google" attribute doesn't seem to be running in my Jupyter Notebook for some reason... | [
"I happened to uninstall Anaconda and reinstall python and get this done. \n",
"1.ensure execute\npip install geocoder\n\n2.remove the statement\nfrom geocoder import google\n\n3.keep only one import statement\nif __name__ == '__main__':\n import geocoder\n g = geocoder.google('Mountain View, CA')\n prin... | [
0,
0,
0
] | [
"I suggest upgrading your pip:\npip install --upgrade pip\n\nand then run the following command:\npip install geocoder\n\n"
] | [
-1
] | [
"attributes",
"geocode",
"module",
"python"
] | stackoverflow_0052468575_attributes_geocode_module_python.txt |
Q:
How to resolve infinite recursion when using metaclasses with python __repr__ function
I am trying to implement a logger functionality using metaclasses. This is for learning purposes and may not be a good use case practically.
from functools import wraps
def custom_logger(fn):
@wraps(fn)
def inner(*args,**kw... | How to resolve infinite recursion when using metaclasses with python __repr__ function | I am trying to implement a logger functionality using metaclasses. This is for learning purposes and may not be a good use case practically.
from functools import wraps
def custom_logger(fn):
@wraps(fn)
def inner(*args,**kwargs):
result=fn(*args,**kwargs)
print(f'LOG: {fn.__qualname__} {args},{kwargs}, res... | [
"The decorator will change the behavior of methods hence a reference of the instance/class should be passed as well.\ndef custom_logger(fn):\n @wraps(fn)\n def inner(self, *args,**kwargs):\n result=fn(self, *args,**kwargs)\n print(f'LOG: {fn.__qualname__} {args},{kwargs}, result={result}')\n return resul... | [
0,
0
] | [] | [] | [
"metaclass",
"python"
] | stackoverflow_0074385165_metaclass_python.txt |
Q:
Random Forest Regressor model in R?
I'm currently using Python for Random Forest Regressor model:
rfr = RandomForestRegressor(random_state=42)
param_grid = {'bootstrap': [True],
'max_depth': [10, 30, 50],
'n_estimators': [200, 400, 600]}
CV = RandomizedSearchCV(estimator = rfr, param_distributions = param_grid... | Random Forest Regressor model in R? | I'm currently using Python for Random Forest Regressor model:
rfr = RandomForestRegressor(random_state=42)
param_grid = {'bootstrap': [True],
'max_depth': [10, 30, 50],
'n_estimators': [200, 400, 600]}
CV = RandomizedSearchCV(estimator = rfr, param_distributions = param_grid, n_iter = 5, cv = 5, verbose=2, random_s... | [
"Your best bet is going to be the caret package. This package doesn't really have models, it is like a framework. For example, when you train a caret model, the default model is from randomForest::randomForest.\nNo encoding is needed or recommended. I don't know of any models that require you to encode categorical ... | [
0
] | [] | [] | [
"python",
"r",
"random_forest"
] | stackoverflow_0074384364_python_r_random_forest.txt |
Q:
Inner join in pandas results into cartesian product
this is a very general question. Is it possible that by performing an inner join in pandas, the resulting merged db has more observations than the maximum observation number of the two datasets. In other words, if I have a db with 30181537 obs and a database with... | Inner join in pandas results into cartesian product | this is a very general question. Is it possible that by performing an inner join in pandas, the resulting merged db has more observations than the maximum observation number of the two datasets. In other words, if I have a db with 30181537 obs and a database with
23483111 observations, how is it possible that the resul... | [
"Because you have duplicates of the v1 column in both data sets, you'll get i * j rows with that merge column value, where i is the number of rows with that value in dataframe A and j is the number of rows with that value in dataframe B.\nIf you don't want this, try using\ndf_A = df_A.drop_duplicates(subset=['v1']... | [
1
] | [] | [] | [
"merge",
"pandas",
"python"
] | stackoverflow_0074392890_merge_pandas_python.txt |
Q:
Specify Hydra multirun sweeps in a config file
I would like to run a Hydra multirun, but specify the sweeps in a config file.
I would like to know if there is a way to do this before asking for a feature request.
So far what I have tried is the following:
Tree structure:
.
βββ conf
β βββ compile
β β βββ base... | Specify Hydra multirun sweeps in a config file | I would like to run a Hydra multirun, but specify the sweeps in a config file.
I would like to know if there is a way to do this before asking for a feature request.
So far what I have tried is the following:
Tree structure:
.
βββ conf
β βββ compile
β β βββ base.yaml
β β βββ grid_search.yaml
β βββ config.ya... | [
"I had also asked this question on GitHub, and got an answer.\nIn conf/experiment/grid_search.yaml, you can have:\n# @package _global_\nhydra:\n sweeper:\n params:\n +compile.lr: 1e-2,1e-3,1e-4\n\nThen you can run:\npython my_app.py -m +experiment=grid_search\n\nIn order to have a sweep defined over a dict... | [
4,
0
] | [] | [] | [
"fb_hydra",
"python"
] | stackoverflow_0070619014_fb_hydra_python.txt |
Q:
An error in loading deep learning model via pickle
I made a deep learning model using Keras and stored it in a folder named model.pkl and for loading the model for deployment I used the code i.e.
import pickle
model = pickle.load(open('/home/samar/Desktop/ckd/model.pkl', 'rb'))
prediction = model.predict(data)
Bu... | An error in loading deep learning model via pickle | I made a deep learning model using Keras and stored it in a folder named model.pkl and for loading the model for deployment I used the code i.e.
import pickle
model = pickle.load(open('/home/samar/Desktop/ckd/model.pkl', 'rb'))
prediction = model.predict(data)
But it returned me as
IsADirectoryError: [Errno 21] Is a d... | [
"Using the model.save() method doesn't actually pickle it, you would want to use the built-in model loader from keras to load your model, like this:\nmodel = keras.models.load_model('/home/samar/Desktop/ckd/model.pkl')\nprediction = model.predict(data)\n\n"
] | [
1
] | [] | [] | [
"keras",
"pickle",
"python"
] | stackoverflow_0074393534_keras_pickle_python.txt |
Q:
Data analysis question PYTHON about subsetting and selecting
I have a question , i am actually learning data analysis with python , and i can't see the difference when we use these lines of code :
rice_consumption = food_consumption[food_consumption["food_category"]=="rice"]
for example we want to define rice_con... | Data analysis question PYTHON about subsetting and selecting | I have a question , i am actually learning data analysis with python , and i can't see the difference when we use these lines of code :
rice_consumption = food_consumption[food_consumption["food_category"]=="rice"]
for example we want to define rice_consumption, why here do we rewrite the dataframe "food_consumption" ... | [
"food_consumption[\"food_category\"]==\"rice\"\n\nAbove line gives you a mask, which are composed of True or False. food_consumption with the mask as the argument can return you the items where mask value is True.\n"
] | [
0
] | [] | [] | [
"dataframe",
"python"
] | stackoverflow_0074393550_dataframe_python.txt |
Q:
Python parser xml nested element find by name
I have a nested XML to parser with Python. Example
<custom-objects xmlns="http://www.demandware.com/xml/impex/customobject/2006-10-31">
<custom-object type-id="AbandonedBaskets" object-id="b4122d6090d1d6a3f8dafd34b0">
<object-attribute attribute-id="basketJson">{"U... | Python parser xml nested element find by name | I have a nested XML to parser with Python. Example
<custom-objects xmlns="http://www.demandware.com/xml/impex/customobject/2006-10-31">
<custom-object type-id="AbandonedBaskets" object-id="b4122d6090d1d6a3f8dafd34b0">
<object-attribute attribute-id="basketJson">{"UUID":"b4122d6090d1d6a3f8dafd34b0"}</object-attribut... | [
"You can use for example beautifulsoup to parse the XML:\nxml_doc = \"\"\"\\\n<custom-objects xmlns=\"http://www.demandware.com/xml/impex/customobject/2006-10-31\">\n<custom-object type-id=\"AbandonedBaskets\" object-id=\"b4122d6090d1d6a3f8dafd34b0\">\n <object-attribute attribute-id=\"basketJson\">{\"UUID\":\"b... | [
1
] | [] | [] | [
"parsing",
"python"
] | stackoverflow_0074393007_parsing_python.txt |
Q:
Is there a way to make a text string bold in python
How do I make this string of printed python text bold (python IDLE v.3.10.5 windows 10):
subtotal = total_price * 1.20
print("The price for your custom pizza is Β£" , total_price)
I have tried looking it up on the web but I cannot find much. Please help :-)
| Is there a way to make a text string bold in python | How do I make this string of printed python text bold (python IDLE v.3.10.5 windows 10):
subtotal = total_price * 1.20
print("The price for your custom pizza is Β£" , total_price)
I have tried looking it up on the web but I cannot find much. Please help :-)
| [] | [] | [
"try this :\nprint('\\033[1m' + \"The price for your custom pizza is Β£\"+ '\\033[0m',total_price)\n\n"
] | [
-2
] | [
"python"
] | stackoverflow_0074393639_python.txt |
Q:
getting the following error = ValueError: All arrays must be of the same length
df = pd.DataFrame({'user_message':messages, 'message_date':dates })
# convert message_date type
df['message_date'] = pd.to_datetime(df['message_date'], format='%d/%m/%Y, %H:%M - ')
df.rename(columns={'message_date': 'date'}, inp... | getting the following error = ValueError: All arrays must be of the same length | df = pd.DataFrame({'user_message':messages, 'message_date':dates })
# convert message_date type
df['message_date'] = pd.to_datetime(df['message_date'], format='%d/%m/%Y, %H:%M - ')
df.rename(columns={'message_date': 'date'}, inplace=True)
df.head()
ValueError Traceback (most rec... | [
"It appears that your lists messages and dates in this line df = pd.DataFrame({'user_message':messages, 'message_date':dates }) are not the same length, you may want to verify that they are the same length.\n"
] | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074393668_pandas_python.txt |
Q:
Creating a decorator to mock input() using monkeypatch in pytest
End goal: I want to be able to quickly mock the input() built-in function in pytest, and replace it with an iterator that generates a (variable) list of strings. This is my current version, which works:
from typing import Callable
import pytest
def... | Creating a decorator to mock input() using monkeypatch in pytest | End goal: I want to be able to quickly mock the input() built-in function in pytest, and replace it with an iterator that generates a (variable) list of strings. This is my current version, which works:
from typing import Callable
import pytest
def _create_patched_input(str_list: list[str]) -> Callable:
str_iter... | [
"I'd use indirect parametrization for mock_input, since it cannot work without receiving parameters. Also, I would refactor mock_input into a fixture that does passing through the arguments it receives, performing the mocking on the way. For example, when using unittest.mock.patch():\nimport pytest\nfrom unittest.m... | [
1
] | [] | [] | [
"decorator",
"mocking",
"pytest",
"python"
] | stackoverflow_0074383626_decorator_mocking_pytest_python.txt |
Q:
Image segmentation background subtraction
I need to tweak this code from real-time to still image.
This code can already remove the background in real-time but I want to change it into still image. I need the code for my project.
# Data Flair background removal
# import necessary packages
import os
import cv2
im... | Image segmentation background subtraction | I need to tweak this code from real-time to still image.
This code can already remove the background in real-time but I want to change it into still image. I need the code for my project.
# Data Flair background removal
# import necessary packages
import os
import cv2
import numpy as np
import mediapipe as mp
# ini... | [
"You have still images already there:\ncv2.imshow(\"Output\", output_image)\n\noutput_image is one of them, so add in your code:\nkey = cv2.waitKey(1) # your code line\nif key == ord('q'): # your code line\n break # your code line\nelif key == ord('c'): # <<< line to add\n cv2.imwrite('images/resu... | [
-1
] | [] | [] | [
"computer_vision",
"image_processing",
"machine_learning",
"opencv",
"python"
] | stackoverflow_0074392493_computer_vision_image_processing_machine_learning_opencv_python.txt |
Q:
Return an arbitrary object when referencing an instance of a class in Python
For the purpose of quickly operating on json objects in a Dash application, I am using dcc.Store to pass a dictionary (you cannot pass objects in dcc.Store) between callbacks. However I want to construct a dictionary out of class instance... | Return an arbitrary object when referencing an instance of a class in Python | For the purpose of quickly operating on json objects in a Dash application, I am using dcc.Store to pass a dictionary (you cannot pass objects in dcc.Store) between callbacks. However I want to construct a dictionary out of class instance (Preferably from a dataclass) and then return it to the data property of the afor... | [
"You can implement __getitem__ and __setitem__ in your class so that it behaves like a dictionary:\nclass MyDataClass:\n def __getitem__(self, item):\n return self.my_dictionary[item]\n\n def __setitem__(self, item, value):\n self.my_dictionary[item] = value\n\n"
] | [
0
] | [] | [] | [
"class",
"dictionary",
"magic_methods",
"python"
] | stackoverflow_0074393583_class_dictionary_magic_methods_python.txt |
Q:
Duplicate a single row at index?
In the past hour I was searching here and couldn't find a very simple thing I need to do, duplicate a single row at index x, and just put in on index x+1.
df
a b
0 3 8
1 2 4
2 9 0
3 5 1
copy index 2 and insert it as is in the next row:
a b
0 3 8
1 2 4
2 9 0
3 9 0 # n... | Duplicate a single row at index? | In the past hour I was searching here and couldn't find a very simple thing I need to do, duplicate a single row at index x, and just put in on index x+1.
df
a b
0 3 8
1 2 4
2 9 0
3 5 1
copy index 2 and insert it as is in the next row:
a b
0 3 8
1 2 4
2 9 0
3 9 0 # new row
4 5 1
What I tried is concat(... | [
"You can use repeat(). Fill in the dictionary with the index and the key, and how many extra rows you would like to add as the value. This can work for multiple values.\nd = {2:1}\ndf.loc[df.index.repeat(df.index.map(d).fillna(0)+1)].reset_index()\n\nOutput:\n index a b\n0 0 3 8\n1 1 2 4\n2 2... | [
1,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074392870_pandas_python.txt |
Q:
Python Selenium; getting data from value 'data-label'
try:
data = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.ID, "DataTables_Table_5"))
)
scores = data.find_elements_by_tag_name('tbody')
for score in scores:
finalScores = score.find_element(By.Name, "Score")... | Python Selenium; getting data from value 'data-label' |
try:
data = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.ID, "DataTables_Table_5"))
)
scores = data.find_elements_by_tag_name('tbody')
for score in scores:
finalScores = score.find_element(By.Name, "Score")
print(finalScores.text)
except:
driver.quit()... | [
"Try this:\n# Needed libs\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\n# We create the driver\ndriver = webdriver.Chrome()\n\n# We maximize the window\ndriver... | [
0
] | [] | [] | [
"html",
"python",
"selenium",
"webdriver"
] | stackoverflow_0074393360_html_python_selenium_webdriver.txt |
Q:
Force conda install --file to ignore fails and install what it can
I have requirements.txt containing a list of packages
0x-contract-addresses
0x-contract-wrappers
0x-order-utils
aioconsole
aiohttp
aiokafka
appdirs
appnope
I run conda install --yes --file requirements.txt
Collecting package metadata (current_repo... | Force conda install --file to ignore fails and install what it can | I have requirements.txt containing a list of packages
0x-contract-addresses
0x-contract-wrappers
0x-order-utils
aioconsole
aiohttp
aiokafka
appdirs
appnope
I run conda install --yes --file requirements.txt
Collecting package metadata (current_repodata.json): done
Solving environment: failed with initial frozen solve. ... | [
"So this is actually the expected behavior as Anaconda wants to maintain environment integrity, to get around this you could run something like the following:\nwhile read requirement; do conda install --yes $requirement || pip install $requirement; done < requirements.txt\nThis will install the packages with conda ... | [
1
] | [] | [] | [
"anaconda",
"conda",
"pip",
"python"
] | stackoverflow_0074393715_anaconda_conda_pip_python.txt |
Q:
Connecting to Memgraph graph database from Python
What do I need to have in place to connect to a running instance of Memgraph from Python?
A:
To connect to Memgraph using Python you will need:
A running Memgraph instance. If you need to set up Memgraph, take a look at the Installation guide.
The GQLAlchemy cli... | Connecting to Memgraph graph database from Python | What do I need to have in place to connect to a running instance of Memgraph from Python?
| [
"To connect to Memgraph using Python you will need:\n\nA running Memgraph instance. If you need to set up Memgraph, take a look at the Installation guide.\nThe GQLAlchemy client. A Memgraph OGM (Object Graph Mapper) for the Python programming language.\n\nCreate a new Python script and add the following code to it:... | [
0
] | [] | [] | [
"memgraphdb",
"python"
] | stackoverflow_0074393784_memgraphdb_python.txt |
Q:
How to refine the log file created by python keylogger
I'm currently working on my school project which is about making a keylogger using python. I found this code online:
import pynput
from pynput.keyboard import Key, Listener
keys=[]
def on_press(key):
keys.append(key)
write_file(keys)
try:
... | How to refine the log file created by python keylogger | I'm currently working on my school project which is about making a keylogger using python. I found this code online:
import pynput
from pynput.keyboard import Key, Listener
keys=[]
def on_press(key):
keys.append(key)
write_file(keys)
try:
print(key.char)
except AttributeError:
print(key... | [
"with open ('log.txt','w') as f:\n for key in keys:\n #for removing quotes\n k=str(key).replace(\"'\",\"\")\n f.write(k)\n\nSimply replace that f.write(k) with some .replace() calls.\nwith open ('log.txt','w') as f:\n for key in keys:\n #for removing quotes\n k=str(key).repl... | [
0
] | [] | [] | [
"keylogger",
"python"
] | stackoverflow_0074393612_keylogger_python.txt |
Q:
How to read multiple lines of raw input?
I want to create a Python program which takes in multiple lines of user input. For example:
This is a multilined input.
It has multiple sentences.
Each sentence is on a newline.
How can I take in multiple lines of raw input?
A:
sentinel = '' # ends when this string is se... | How to read multiple lines of raw input? | I want to create a Python program which takes in multiple lines of user input. For example:
This is a multilined input.
It has multiple sentences.
Each sentence is on a newline.
How can I take in multiple lines of raw input?
| [
"sentinel = '' # ends when this string is seen\nfor line in iter(input, sentinel):\n pass # do things here\n\nTo get every line as a string you can do:\n'\\n'.join(iter(input, sentinel))\n\n\nPython 2:\n'\\n'.join(iter(raw_input, sentinel))\n\n",
"Alternatively, you can try sys.stdin.read() that returns the wh... | [
113,
19,
7,
3,
3,
2,
1,
1,
0,
0,
0,
0,
0,
0,
0
] | [
"def sentence_maker(phrase):\n return phrase\n\nresults = []\nwhile True:\n user_input = input(\"What's on your mind: \")\n if user_input == '\\end':\n break\n else:\n results.append(sentence_maker(user_input))\n\nprint('\\n'.join(map(str, results)))\n\n"
] | [
-2
] | [
"input",
"python",
"user_input"
] | stackoverflow_0011664443_input_python_user_input.txt |
Q:
Cannot turn on Mac Webcam through OpenCV python
I am new to opencv and trying to access my Macbook's built-in camera through OpenCV python but it gives an error.
import cv2
frameWidth = 640
frameHeight = 480
cap = cv2.VideoCapture(0)
cap.set(3, frameWidth)
cap.set(4, frameHeight)
cap.set(10,150)
while True:
s... | Cannot turn on Mac Webcam through OpenCV python | I am new to opencv and trying to access my Macbook's built-in camera through OpenCV python but it gives an error.
import cv2
frameWidth = 640
frameHeight = 480
cap = cv2.VideoCapture(0)
cap.set(3, frameWidth)
cap.set(4, frameHeight)
cap.set(10,150)
while True:
success, img = cap.read()
cv2.imshow("Result", img)... | [
"There are two suggestions I would like to mention.\n#1: Enable your terminal or PyCharm to reach the camera.\n\n\nGo to System Preferences-> Security and Privacy -> Camera and add PyCharm to the list.\n\n\n\n\n\n#2 Instead of while True use while cap.isOpened(), so you can know that PyCharm or terminal can access ... | [
5,
1,
0
] | [
"Try to increase frame width/height, for example use:\nframeWidth = 1048\nframeHeight = 1028\n"
] | [
-2
] | [
"computer_vision",
"opencv",
"opencv_python",
"pycharm",
"python"
] | stackoverflow_0061979361_computer_vision_opencv_opencv_python_pycharm_python.txt |
Q:
How to show last row of Pandas DataFrame in box plot
Random data:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
data = pd.DataFrame(np.random.normal(size=(20,4)))
data
0 1 2 3
0 -0.710006 -0.748083 -1.261515 0.... | How to show last row of Pandas DataFrame in box plot | Random data:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
data = pd.DataFrame(np.random.normal(size=(20,4)))
data
0 1 2 3
0 -0.710006 -0.748083 -1.261515 0.048941
1 0.856541 0.533073 0.649113 -0.2362... | [
"You could just add a scatter plot on top of the boxplot.\nFor the provided example, it looks like this:\nfig, ax = plt.subplots(figsize=(8,5))\ndf.boxplot(vert= False, patch_artist=True, ax=ax, zorder=1)\nlastrow = df.iloc[-1,:]\nprint(lastrow)\nax.scatter(x=lastrow, y=[*range(1,len(lastrow)+1)], color='r', zorder... | [
3
] | [] | [] | [
"boxplot",
"dataframe",
"matplotlib",
"pandas",
"python"
] | stackoverflow_0074393083_boxplot_dataframe_matplotlib_pandas_python.txt |
Q:
Attribute error while running apply function in python
I am trying to use this technique Calculate distance between two coordinates for a fixed point in a DataFrame
from typing import Tuple
import geopy.distance
def distance(
lat: float, lon: float, fixed_coords: Tuple[float] = (36.7196, -4.42002)
) -> flo... | Attribute error while running apply function in python | I am trying to use this technique Calculate distance between two coordinates for a fixed point in a DataFrame
from typing import Tuple
import geopy.distance
def distance(
lat: float, lon: float, fixed_coords: Tuple[float] = (36.7196, -4.42002)
) -> float:
return geopy.distance.distance((lat, lon), fixed_co... | [
"The name error is becasue the interpreter thinks lat and lon are variable names, not the name of columns. Try using strings instead.\nx = dataframe.apply(lambda row: distance(row[\"lat\"], row[\"lon\"],axis =1))\n\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074393843_python.txt |
Q:
Making the right post request
I need your help in putting together a post request.
The output I get is html, but the plan was to get the following:
Below are all the data for the desired item:
General
Request URL: https://dgslivebetting.betonline.ag/ngwbet.aspx/gvFrameHtml
Request Method: POST
Status Code: 200
Re... | Making the right post request | I need your help in putting together a post request.
The output I get is html, but the plan was to get the following:
Below are all the data for the desired item:
General
Request URL: https://dgslivebetting.betonline.ag/ngwbet.aspx/gvFrameHtml
Request Method: POST
Status Code: 200
Remote Address: 104.17.64.19:443
Refe... | [
"In order to get JSON back, you need to add the Content-Type header to your request.\nYour current examples shows you are only sending these headers:\nheaders = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36\",\n 'Referer... | [
0
] | [] | [] | [
"html",
"python"
] | stackoverflow_0074392305_html_python.txt |
Q:
Python: Multiprocessing with pool.map while main is still working
I am a few days into learning python, and would like to understand this.
I am doing a file explorer, and want to speed up thumbnail creation.
Watched a bunch of tutorials about multiprocessing, but none show hot to continue main(), while processes a... | Python: Multiprocessing with pool.map while main is still working | I am a few days into learning python, and would like to understand this.
I am doing a file explorer, and want to speed up thumbnail creation.
Watched a bunch of tutorials about multiprocessing, but none show hot to continue main(), while processes are running.
I need results in order.
import os
from multiprocessing imp... | [
"The documentation suggests that a Process Pool Executor is what you're looking for. Code below from the link. As for the unordered results, try passing in a sorted list.\nimport concurrent.futures\nimport math\n\nPRIMES = [\n 112272535095293,\n 112582705942171,\n 112272535095293,\n 115280095190773,\n ... | [
1
] | [] | [] | [
"multiple_processes",
"process_pool",
"python"
] | stackoverflow_0074393723_multiple_processes_process_pool_python.txt |
Q:
How to I call this method?
I have this piece of code and I feel so dumb for not knowing how to run it. Please help.
class Solution(object):
def countOdds(self, low: int, high: int):
if low % 2 == 0 and high % 2 == 0:
return (high-low)//2
else:
return (high-low)//2 + 1
I... | How to I call this method? | I have this piece of code and I feel so dumb for not knowing how to run it. Please help.
class Solution(object):
def countOdds(self, low: int, high: int):
if low % 2 == 0 and high % 2 == 0:
return (high-low)//2
else:
return (high-low)//2 + 1
I tried running Solution.countOdd... | [
"You're trying to access a method of the class but haven't created an instance. Try:\nclass Solution(object):...\n\ninstance = Solution()\nprint(instance.countOdds(3,11))\n\n",
"You need to create an object linking to the class and then call that.\nSo instead of doing Solution.countOdds(3, 11), you need to do\nMy... | [
0,
0
] | [] | [] | [
"class",
"methods",
"oop",
"python"
] | stackoverflow_0074393883_class_methods_oop_python.txt |
Q:
parameratized SQL queries for queries to s3 buckets
I have a CSV file in an s3 bucket and I'm accessing it using the boto3 library. I'm using the select_object_content function to query the file with SQL language.
This is my code:
resp = self.s3_client.select_object_content(
Bucket=S3_BUCKET_MAPPING,
Key=S... | parameratized SQL queries for queries to s3 buckets | I have a CSV file in an s3 bucket and I'm accessing it using the boto3 library. I'm using the select_object_content function to query the file with SQL language.
This is my code:
resp = self.s3_client.select_object_content(
Bucket=S3_BUCKET_MAPPING,
Key=S3_BUCKET_MAPPING_KEY,
ExpressionType="SQL",
Expre... | [
"s3 supports a limited SQL syntax. As long as you are using static SQL or are using the parameter passing s3 should correctly handle parameters.\nYou could, of course, get in trouble if you start creating SQL expressions from untrusted strings. But that doesn't seem to be the case here.\n"
] | [
0
] | [] | [] | [
"amazon_s3",
"boto3",
"python",
"sql_injection"
] | stackoverflow_0074383230_amazon_s3_boto3_python_sql_injection.txt |
Q:
How to multiply the value in df_a by the values in df_b, take the sum of these values, and append them together for all values in df_a?
I would like to multiply the value in one dataframe (df_a) by the values in another dataframe (df_b) and then take the sum of these values, and append them together for all values... | How to multiply the value in df_a by the values in df_b, take the sum of these values, and append them together for all values in df_a? | I would like to multiply the value in one dataframe (df_a) by the values in another dataframe (df_b) and then take the sum of these values, and append them together for all values in df_a. E.g.
df_a:
col_x
10
20
and df_b:
col_y
5
6
Would result in:
[(10 x 5) + (10 x 6), (20 x 5) + (20 x 6)] ... | [
"No need for complicated loops or broadcasting. (10 x 5) + (10 x 6) is equal to 10*(5+6). So first sum the second Series, then multiply the first one with this scalar.\nout = df_a['col_x']*df_b['col_y'].sum()\n\nOutput:\n0 110\n1 220\nName: col_x, dtype: int64\n\nAs array:\nout = df_a['col_x'].to_numpy()*df_b... | [
1,
1,
0,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074393790_pandas_python.txt |
Q:
Pong Game: Paddle Won't Move with Input (Python)
I am a novice to Python trying to make the game Pong. I have created a Paddle class with the Turtle Graphics module, but I can't get the paddle to move. I just want to start with one direction and then down shouldn't be too hard from there. Can anyone see what I am... | Pong Game: Paddle Won't Move with Input (Python) | I am a novice to Python trying to make the game Pong. I have created a Paddle class with the Turtle Graphics module, but I can't get the paddle to move. I just want to start with one direction and then down shouldn't be too hard from there. Can anyone see what I am doing wrong with my method?
from turtle import Turtle... | [
"This isn't the usual approach to this problem, but I can see why it might be advantageous. Your primary issue seems to be not being able to determine what should be global, what should be local, and what should be a property. Let's make this work to demonstrate the use of all three:\nfrom turtle import Screen, T... | [
0
] | [] | [] | [
"pong",
"python",
"python_turtle",
"turtle_graphics"
] | stackoverflow_0074383734_pong_python_python_turtle_turtle_graphics.txt |
Q:
Django; 44 connect() failed (111: Connection refused) while connecting to upstream on AWS Elastic Bean
I want to upload my django project to AWS ElasticBean but I have been getting 502 Bad Gateway error; nginx/1.20.0. I have gone through few videos on youtube but it doesn't seems to work.
Here is my project direct... | Django; 44 connect() failed (111: Connection refused) while connecting to upstream on AWS Elastic Bean | I want to upload my django project to AWS ElasticBean but I have been getting 502 Bad Gateway error; nginx/1.20.0. I have gone through few videos on youtube but it doesn't seems to work.
Here is my project directory
ββββ.ebextensions
ββββ.elasticbeanstalk
ββββebdjango
ββββ.gitattributes
ββββ.gitignore
ββββdb.sqlite3
ββ... | [
"I fixed this error by changing\nebdjango.wsgi:application\n\nto\napi.wsgi:application\n\nWhich is the name of my django app. Hope this helps!\n"
] | [
0
] | [] | [] | [
"amazon_elastic_beanstalk",
"amazon_web_services",
"django",
"django_rest_framework",
"python"
] | stackoverflow_0071672636_amazon_elastic_beanstalk_amazon_web_services_django_django_rest_framework_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.