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:
NumPy: apply vector-valued function to mesh grid
I am trying to do something like the following in NumPy:
import numpy as np
def f(x):
return x[0] + x[1]
X1 = np.array([0, 1, 2])
X2 = np.array([0, 1, 2])
X = np.meshgrid(X1, X2)
result = np.vectorize(f)(X)
with the expected result being array([[0, 1, 2], [1, ... | NumPy: apply vector-valued function to mesh grid | I am trying to do something like the following in NumPy:
import numpy as np
def f(x):
return x[0] + x[1]
X1 = np.array([0, 1, 2])
X2 = np.array([0, 1, 2])
X = np.meshgrid(X1, X2)
result = np.vectorize(f)(X)
with the expected result being array([[0, 1, 2], [1, 2, 3], [2, 3, 4]]), but it returns the following error... | [
"If you persist to use numpy.vectorize you need to define signature when defining vectorize on function.\nimport numpy as np\n\ndef f(x):\n return x[0] + x[1]\n # Or\n # return np.add.reduce(x, axis=0)\n\n\nX1 = np.array([0, 1, 2])\nX2 = np.array([0, 1, 2])\nX = np.meshgrid(X1, X2)\n\n# np.asarray(X).shape... | [
1,
0,
0,
0
] | [] | [] | [
"numpy",
"python",
"vectorization"
] | stackoverflow_0074584886_numpy_python_vectorization.txt |
Q:
Comparing Django project structure to ruby on rails
After some years developing web apps using ruby on rails, I decided to give Django a try, however it seems that I'm missing something, which is how to structure large project, or any project in general.
For example, in rails we have a models folder which contains... | Comparing Django project structure to ruby on rails | After some years developing web apps using ruby on rails, I decided to give Django a try, however it seems that I'm missing something, which is how to structure large project, or any project in general.
For example, in rails we have a models folder which contains model classes, each in a separate ruby file, a controlle... | [
"In short, Django is a Model-View-Template framework and Rails is a Model-View-Controller framework.\nIn Django we store controllers(sort of) in views.py for each specified app, while in MVC framework such as Rails store it in controllers. In Django, you also have to create your own HTML template separately which s... | [
1,
1
] | [] | [] | [
"django",
"python",
"ruby_on_rails"
] | stackoverflow_0074651540_django_python_ruby_on_rails.txt |
Q:
Get all combinations of several columns in a pandas dataframe and calculate sum for each combination
I have a dataframe as below:
df = pd.DataFrame({'id': ['a', 'b', 'c', 'd'],
'colA': [1, 2, 3, 4],
'colB': [5, 6, 7, 8],
'colC': [9, 10, 11, 12],
... | Get all combinations of several columns in a pandas dataframe and calculate sum for each combination | I have a dataframe as below:
df = pd.DataFrame({'id': ['a', 'b', 'c', 'd'],
'colA': [1, 2, 3, 4],
'colB': [5, 6, 7, 8],
'colC': [9, 10, 11, 12],
'colD': [13, 14, 15, 16]})
I want to get all combinations of 'colA', 'colB', 'colC' and 'colD'... | [
"First, select from the frame a list of all columns starting with col. Then we create a dictionary using combinations, where the keys are the names of the new summing columns, and the values are the sums of the corresponding columns of the original dataframe, then we unpack them ** as arguments to the assign method... | [
2
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074652092_pandas_python.txt |
Q:
'Line2D' object has no property 'line' error when using Matplotlib in a PyQt5 subwindow
I am trying to embed a Matplotlib plot in a PyQt5 subwindow written in Python. When I plot a line in the plot I get the error:
'Line2D' object has no property 'line'
Below is the relevant code extracted from my application. ... | 'Line2D' object has no property 'line' error when using Matplotlib in a PyQt5 subwindow | I am trying to embed a Matplotlib plot in a PyQt5 subwindow written in Python. When I plot a line in the plot I get the error:
'Line2D' object has no property 'line'
Below is the relevant code extracted from my application. Any help would be much appreciated and if anyone knows of a better way to do this that would... | [
"You should try below as official site says.\nlinestyle='--'\n"
] | [
0
] | [] | [] | [
"matplotlib",
"pyqt5",
"python"
] | stackoverflow_0071072530_matplotlib_pyqt5_python.txt |
Q:
Why won't this prophet Python module import? I have tried everything possible
I am running Python version 3.7 and trying to create a stock prediction Python program using fbprophet. However, it doesn't want to install.
I have tried importing it using pip, through python, and using conda install. Nothing seems to w... | Why won't this prophet Python module import? I have tried everything possible | I am running Python version 3.7 and trying to create a stock prediction Python program using fbprophet. However, it doesn't want to install.
I have tried importing it using pip, through python, and using conda install. Nothing seems to work. Can I get some help here?
Showing that it isn't importing
| [
"Try with virtuanenv in python.\n❯ python -m venv .venv\n❯ source .venv/bin/activate\n❯ pip install prophet\n\nThen everything you installed will be in the virtual environment.\nHere is the sample code.\n\nfrom prophet import Prophet\nprint(\"imported successfully!\")\n\nAnd the output would be following:\n❯ python... | [
0
] | [] | [] | [
"installation",
"module",
"prophet",
"python"
] | stackoverflow_0074652156_installation_module_prophet_python.txt |
Q:
Python docx2pdf AttributeError: Open.SaveAs
I am trying to convert a docx file to pdf using the docx2pdf library, using the following code:
from docx2pdf import convert
convert("generated.docx")
As written here. But I have an error:
Traceback (most recent call last):
File "c:\Users\user\Desktop\folder\script.p... | Python docx2pdf AttributeError: Open.SaveAs | I am trying to convert a docx file to pdf using the docx2pdf library, using the following code:
from docx2pdf import convert
convert("generated.docx")
As written here. But I have an error:
Traceback (most recent call last):
File "c:\Users\user\Desktop\folder\script.py", line 29, in <module>
convert("generated.d... | [
"change:\nword = win32com.client.Dispatch('Word.Application')\n\nto\nimport pythoncom\nword = win32com.client.Dispatch('Word.Application', pythoncom.CoInitialize())\n\n",
"from docx2pdf import convert\n\ninputFile = \"document.docx\"\noutputFile = \"document2.pdf\"\nfile = open(outputFile, \"w\")\nfile.close()\n\... | [
1,
0,
0
] | [] | [] | [
"comtypes",
"docx",
"python",
"python_docx",
"pywin32"
] | stackoverflow_0071292585_comtypes_docx_python_python_docx_pywin32.txt |
Q:
AddPrivateFont to App Title / Title bar in WxPython?
My problem is I can't find the way to use AddPrivateFont to change the App Title font in WxPython.
From the demo
https://github.com/wxWidgets/Phoenix/blob/master/demo/AddPrivateFont.py
and the sample
https://wiki.wxpython.org/How%20to%20add%20a%20menu%20bar%20i... | AddPrivateFont to App Title / Title bar in WxPython? | My problem is I can't find the way to use AddPrivateFont to change the App Title font in WxPython.
From the demo
https://github.com/wxWidgets/Phoenix/blob/master/demo/AddPrivateFont.py
and the sample
https://wiki.wxpython.org/How%20to%20add%20a%20menu%20bar%20in%20the%20title%20bar%20%28Phoenix%29
I tried
f = ... | [
"The reason you are getting those errors is that the title for a frame is just a string.\nTo be able to modify the font in the title you will have to create a title bar class based off of wx.Control like they did in the sample.\nThe created title bar will house the label and you will be able to set its font.\nWhen ... | [
1
] | [] | [] | [
"fonts",
"python",
"python_3.x",
"wxpython",
"wxwidgets"
] | stackoverflow_0074651265_fonts_python_python_3.x_wxpython_wxwidgets.txt |
Q:
Repairing pdfs with damaged xref table
Are there any solutions (preferably in Python) that can repair pdfs with damaged xref tables?
I have a pdf that I tried to convert to a png in Ghostscript and received the following error:
**** Error: An error occurred while reading an XREF table.
**** The file has been d... | Repairing pdfs with damaged xref table | Are there any solutions (preferably in Python) that can repair pdfs with damaged xref tables?
I have a pdf that I tried to convert to a png in Ghostscript and received the following error:
**** Error: An error occurred while reading an XREF table.
**** The file has been damaged. This may have been caused
**** b... | [
"If the file renders as expected in Ghostscript then you can run it through GS to the pdfwrite device and create a new PDF file which won't be damaged.\nPreview is (like Acrobat) almost certainly silently repairing the problem in the background. Ghostscript will be doing the same, but unlike other applications we f... | [
1
] | [
"i know im super late but, if you try...\ncat my.pdf > temp.pdf && hexdump temp.pdf > newpdf.pdf\n\n\nor\nzip my.pdf && unzip my.pdf\n\nif you opened the document in...\n\nutf-8 read mode\n\n...then you probably changed some key bytes around, specifically the octal 011, hexadecimal 0A, decimal 10... these are the l... | [
-1
] | [
"ghostscript",
"pdf",
"python"
] | stackoverflow_0043149372_ghostscript_pdf_python.txt |
Q:
sqlalchemy.orm.exc.UnmappedInstanceError: Class 'services_backend.routes.models.category.CategoryCreate' is not mapped
I am using pydantic, fastapi+sqlalchemy and postgresql for my project. When i`m trying to create new button (or category), i get UnmappedInstanceError.
Here is my code:
button.py (from routes)
fro... | sqlalchemy.orm.exc.UnmappedInstanceError: Class 'services_backend.routes.models.category.CategoryCreate' is not mapped | I am using pydantic, fastapi+sqlalchemy and postgresql for my project. When i`m trying to create new button (or category), i get UnmappedInstanceError.
Here is my code:
button.py (from routes)
from fastapi import HTTPException, APIRouter
from fastapi_sqlalchemy import db
from .models.button import ButtonCreate, Button... | [
"The error message is pretty clear: you're trying to use CategoryCreate as an ORM model, when it is a pydantic model (I'm guessing, you haven't included it here). Same in your create_button function, you're trying to add a ButtonCreate object to the database. That should be the ORM model Button instead.\n"
] | [
0
] | [] | [] | [
"fastapi",
"python",
"sqlalchemy"
] | stackoverflow_0074642491_fastapi_python_sqlalchemy.txt |
Q:
Django Serializer - how to check if a ListField is valid?
I'm currently working on a practice social media app. In this app, current users can invite their friends by email to join the app (specifically, joining a 'channel' of the app, like Discord). I'm working on unit tests to ensure that emails are valid. I'm w... | Django Serializer - how to check if a ListField is valid? | I'm currently working on a practice social media app. In this app, current users can invite their friends by email to join the app (specifically, joining a 'channel' of the app, like Discord). I'm working on unit tests to ensure that emails are valid. I'm working with serializers for the first time and I'm trying to mo... | [
"if you are getting email in list then write for loop to get each mail to validate, in your to_internal_value function write code as below:\nfrom django.core.validators import validate_email\n \ndef to_internal_value(data):\n for email in data:\n try:\n validate_email(email)\n except:... | [
0,
0
] | [] | [] | [
"django",
"error_handling",
"python",
"serialization",
"validation"
] | stackoverflow_0074648592_django_error_handling_python_serialization_validation.txt |
Q:
read json composite attribute by python
I have the following content of Json file
{
"role": [
{
"type": "account",
"attributes": {
"order": 50
}
},
{
"type": "secretary",
"attributes": {
"order": 10
}
},
{
"type": "account",
"attribute... | read json composite attribute by python | I have the following content of Json file
{
"role": [
{
"type": "account",
"attributes": {
"order": 50
}
},
{
"type": "secretary",
"attributes": {
"order": 10
}
},
{
"type": "account",
"attributes": {
"order": 3
}
}
]
}
I... | [] | [] | [
"You from JS background?\nIndeed the list does not have such attribute.\nAssuming roles is your list (cause you didn't bother to provide any code unfortunately):\nmax_order_role = sorted(roles, key= lambda i:i.get(\"attributes\",{}).get(\"order\"))[-1]\n\n"
] | [
-1
] | [
"composite",
"json",
"python"
] | stackoverflow_0074652304_composite_json_python.txt |
Q:
How to replace strings with int in sublist?
I'm trying to split above special letters '/' or '_' whatever comes first in the string column.
Here is the sample of the dataset(df2):
4. 발견장소 코딩사유 Unnamed : 1
1 67488 교외/야산_등산로 계곡 앞
2 100825 자택_자택 방안 텐트
3. 101199 ... | How to replace strings with int in sublist? | I'm trying to split above special letters '/' or '_' whatever comes first in the string column.
Here is the sample of the dataset(df2):
4. 발견장소 코딩사유 Unnamed : 1
1 67488 교외/야산_등산로 계곡 앞
2 100825 자택_자택 방안 텐트
3. 101199 숙박업소_게스트하우스 21층 복도
I converted Unnamed: ... | [
"In pandas, with your method, you are referring to a value instead of row or column. In findplace[i][0], i is your column name and 0 is your row name, and it is returning the value of column i where row is 0.\nI don't really know, either you are trying to use replace on row (with index name as 0) or the whole colum... | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074652325_pandas_python.txt |
Q:
Converting stl code plot from Matlab to Python
I am looking to be able to plot an stl file in Python. I can do it in Matlab easily enough with this code:
phacon = stlread("Spine_PhaconModel.stl");
hold on
figure = trisurf(phacon,'FaceColor',[0.6 0.6 0.6], 'Edgecolor','none','FaceLighting','gouraud','AmbientStren... | Converting stl code plot from Matlab to Python | I am looking to be able to plot an stl file in Python. I can do it in Matlab easily enough with this code:
phacon = stlread("Spine_PhaconModel.stl");
hold on
figure = trisurf(phacon,'FaceColor',[0.6 0.6 0.6], 'Edgecolor','none','FaceLighting','gouraud','AmbientStrength', 0.15, 'MarkerEdgeColor',"r")
view([180, -1])
... | [
"from the documentation it seems you need to plot it as 3d polygons, the answer below shows how to plot it, the following is a modified example because the docs are outdated, and matplotlib seems to have changed since then.\nfrom stl import mesh\nfrom mpl_toolkits import mplot3d\nfrom matplotlib import pyplot\n\n# ... | [
1
] | [] | [] | [
"matlab",
"plot",
"python"
] | stackoverflow_0074617585_matlab_plot_python.txt |
Q:
TCP sockets. Missing bytes when transmitting data over internet
I have simple client-server setup that communicate JPG bytes. When running locally it works perfectly. However when transmitting over internet JPGs get corrupted and when decoded have severe visual artifacts.
Client is a Rust Tokio application. It co... | TCP sockets. Missing bytes when transmitting data over internet | I have simple client-server setup that communicate JPG bytes. When running locally it works perfectly. However when transmitting over internet JPGs get corrupted and when decoded have severe visual artifacts.
Client is a Rust Tokio application. It consumes jpeg stream from a camera and pushed the jpeg bytes to TCP soc... | [
"To write the bytes to the TCP socket you are calling AsyncWriteExt::write:\nlet tcp_result = tcp_conn.write(&slice).await;\n\nAnd quoting the docs:\n\nThis function will attempt to write the entire contents of buf, but the entire write may not succeed...\nIf the return value is Ok(n) then it must be guaranteed tha... | [
1
] | [] | [] | [
"python",
"python_asyncio",
"rust",
"rust_tokio",
"tcp"
] | stackoverflow_0074608177_python_python_asyncio_rust_rust_tokio_tcp.txt |
Q:
How to copy a file in the time stamp folder
I make a directory with the current timestamp 12:32:57 PM. I want to copy the file to the time folder who can I do this? I run the following code
import os
import shutil
cmd_mkdir = 'mkdir /home/mubashir/catkin_ws/src/germany1_trush/ros_bag_saved/"$(date +%r)"'
os.sy... | How to copy a file in the time stamp folder | I make a directory with the current timestamp 12:32:57 PM. I want to copy the file to the time folder who can I do this? I run the following code
import os
import shutil
cmd_mkdir = 'mkdir /home/mubashir/catkin_ws/src/germany1_trush/ros_bag_saved/"$(date +%r)"'
os.system(cmd_mkdir)
origin_past=f'/home/mubashir/cat... | [
"What you want to do is grab the time in python and save it in a variable, that way you can reference the same time for both creating the folder and copying the file into it.\nYou could use\nimport os\nimport shuitil\nfrom datetime import datetime\ntime = datetime.now().strftime('%I:%M:%S %p')\n\nThis will get the ... | [
0
] | [] | [] | [
"linux",
"mkdir",
"python",
"timestamp"
] | stackoverflow_0074652356_linux_mkdir_python_timestamp.txt |
Q:
How can i read large EmailMessage object using wb+ if the file is large using python3?
I wish to write a very large EmailMessage object using binary in small sizes just like it is done using buffer.read(1024). IS there a way?
I have tried like this which is wrong as the Email Message object is not having read() m... | How can i read large EmailMessage object using wb+ if the file is large using python3? | I wish to write a very large EmailMessage object using binary in small sizes just like it is done using buffer.read(1024). IS there a way?
I have tried like this which is wrong as the Email Message object is not having read() method:
with open(complete_path,'wb+') as fp:
while True:
x = msg.rea... | [
"Try using this:\n import email\n import os\n\n # Open the file in binary mode\n with open(complete_path, 'rb') as fp:\n msg = email.message_from_binary_file(fp)\n\n # Write the message to a file in binary mode\n with open(complete_path, 'wb+') as fp:\n fp.write(msg.as_bytes())\n\nOR\nimport email\nimpo... | [
0
] | [] | [] | [
"email",
"python"
] | stackoverflow_0074579971_email_python.txt |
Q:
ElementNotInteractableException: Message: Element could not be scrolled into view
I am trying to press a the download on this page
https://data.unwomen.org/data-portal/sdg?annex=All&finic[]=SUP_1_1_IPL_P&flocat[]=478&flocat[]=174&flocat[]=818&flocat[]=504&flocat[]=729&flocat[]=788&flocat[]=368&flocat[]=400&floca... | ElementNotInteractableException: Message: Element could not be scrolled into view | I am trying to press a the download on this page
https://data.unwomen.org/data-portal/sdg?annex=All&finic[]=SUP_1_1_IPL_P&flocat[]=478&flocat[]=174&flocat[]=818&flocat[]=504&flocat[]=729&flocat[]=788&flocat[]=368&flocat[]=400&flocat[]=275&flocat[]=760&fys[]=2015&fyr[]=2030&fca[ALLAGE]=ALLAGE&fca[<15Y]=<15Y&fca[15%2B]=... | [
"You have to modify the XPath, try the below code:\ndriver.get(\"https://data.unwomen.org/data-portal/sdg?annex=All&finic[]=SUP_1_1_IPL_P&flocat[]=478&flocat[]=174&flocat[]=818&flocat[]=504&flocat[]=729&flocat[]=788&flocat[]=368&flocat[]=400&flocat[]=275&flocat[]=760&fys[]=2015&fyr[]=2030&fca[ALLAGE]=ALLAGE&fca[<15... | [
2,
0
] | [] | [] | [
"download",
"python",
"python_3.x",
"selenium",
"web_scraping"
] | stackoverflow_0074652258_download_python_python_3.x_selenium_web_scraping.txt |
Q:
I have a problem about DuplicateWidgetID. When program runs it says there are multiple identical st.checkbox widgets with the same generated key
import streamlit as st
import functions
list = functions.get_list()
def add_todo():
todo = st.session_state["new_todo"] + "\n"
list.append(todo)
functions.w... | I have a problem about DuplicateWidgetID. When program runs it says there are multiple identical st.checkbox widgets with the same generated key | import streamlit as st
import functions
list = functions.get_list()
def add_todo():
todo = st.session_state["new_todo"] + "\n"
list.append(todo)
functions.write_list(list)
st.title("Simple To-Do app")
st.subheader("This is my todo app")
st.write("Increase your productivity")
for todo in list:
st.ch... | [
"This happens because every new st.text_input() expects a unique key value. You can use an increment in your for-loop to always re-assign a new key value. for the next st.text_input() to be created.\nExample:\nunique_value = 0\nfor todo in list:\n unique_value += 1\n if st.checkbox(todo):\n st.text_inp... | [
0
] | [] | [] | [
"pysimplegui",
"python",
"session_state",
"streamlit"
] | stackoverflow_0074650034_pysimplegui_python_session_state_streamlit.txt |
Q:
How can i fix this issue TypeError: 'SMTP_SSL' object is not callable
How can i fix this error in python TypeError: 'SMTP_SSL' object is not callable
this is a function
import smtplib, ssl
def show_im_having_fun():
return
smtplib.SMTP_SSL("smtp.gmail.com", 465, context=ssl.create_default_context()).login('hell... | How can i fix this issue TypeError: 'SMTP_SSL' object is not callable | How can i fix this error in python TypeError: 'SMTP_SSL' object is not callable
this is a function
import smtplib, ssl
def show_im_having_fun():
return
smtplib.SMTP_SSL("smtp.gmail.com", 465, context=ssl.create_default_context()).login('hello@gmail.com', 'pass')
smtplib.SMTP_SSL("smtp.gmail.com", 465, context=ssl... | [
"Unlike in some other programming languages, you can't chain the object's initializer like that; the error message tells you as much.\nCode which is not inside a def or class or similar will run when you import that file, which is probably not what you want here. The immediate fix would be to move your SMTP code t... | [
0
] | [] | [] | [
"python",
"python_3.x",
"ssl"
] | stackoverflow_0074651581_python_python_3.x_ssl.txt |
Q:
how to take take multiple pages as input in pdfplumber?
I am using pdfplumber to take input from a pdf file.
My question is how can I take from page 1-7 input using pdfplumber.
I'm using this code:
filename = "1st Year 1stSemester.pdf"
pdf = pdfplumber.open(filename)
totalpages = len(pdf.pages)
p0 = pdf.pages[0-6... | how to take take multiple pages as input in pdfplumber? | I am using pdfplumber to take input from a pdf file.
My question is how can I take from page 1-7 input using pdfplumber.
I'm using this code:
filename = "1st Year 1stSemester.pdf"
pdf = pdfplumber.open(filename)
totalpages = len(pdf.pages)
p0 = pdf.pages[0-6]
table = p0.extract_table()
table
I want to take input fro... | [
"for i in range (0,7):\n print(filename.pages[i].extract_text)\n\nTo show the pages, use the for loop. Input the desired pages you want to show for example in your case you want to display the pages 1-7, just like how you count an array, it start with 0 till the last page which is 7.\n"
] | [
0
] | [] | [] | [
"pdf",
"pdfplumber",
"python"
] | stackoverflow_0070461352_pdf_pdfplumber_python.txt |
Q:
missing 2 required positional arguments flask python
I'm developing a web application where I pull and use bluetooth data via the browser via the Bleak library.I do not intend to connect to the database. My only purpose is to keep the person's bluettoh data on the browser (cookies or sessions) as well. I haven't g... | missing 2 required positional arguments flask python | I'm developing a web application where I pull and use bluetooth data via the browser via the Bleak library.I do not intend to connect to the database. My only purpose is to keep the person's bluettoh data on the browser (cookies or sessions) as well. I haven't gotten to this stage yet. At the moment, I just need to vie... | [
"Don't you call the function devices in the line:\nscanner.register_detection_callback(devices)\nIf so you have to give it the two arguments device and advertisement_data.\n"
] | [
0
] | [] | [] | [
"bluetooth",
"flask",
"python",
"web"
] | stackoverflow_0074652327_bluetooth_flask_python_web.txt |
Q:
python.h file not found after using command on cygwin
I tried to include python.h but received fatal error
I downloaded a code which includes python.h, but i received fatal error python.h not found. I followed stackoverflow using the command shown below on cygwin
apt-cyg install python-devel
However, in \usr\inc... | python.h file not found after using command on cygwin | I tried to include python.h but received fatal error
I downloaded a code which includes python.h, but i received fatal error python.h not found. I followed stackoverflow using the command shown below on cygwin
apt-cyg install python-devel
However, in \usr\include i only find a folder python2.7 with pyconfig.h file on... | [
"do not use apt-cyg as it is unmaintained and not updated to the latest format of Setup.ini format\nUse Cygwin Setup.\nYou should install python3-devel or python39-devel\nhttps://cygwin.com/packages/summary/python3-devel.html\n"
] | [
0
] | [] | [] | [
"cygwin",
"python"
] | stackoverflow_0074651523_cygwin_python.txt |
Q:
not the desirable output
the expected out put was
1 1
2 2
3 3
4 4
5 5
but the output I got is
1
1 2
2 3
3 4
4 5
5
for num in numlist:
print(num)
print(num,end=' ')
I tried to execute this python code in python interpreter and got the wrong output
A:
Every print has an end. Unless you overwrite what ... | not the desirable output | the expected out put was
1 1
2 2
3 3
4 4
5 5
but the output I got is
1
1 2
2 3
3 4
4 5
5
for num in numlist:
print(num)
print(num,end=' ')
I tried to execute this python code in python interpreter and got the wrong output
| [
"Every print has an end. Unless you overwrite what print should end in, it ends in a new line. In your first print, you don't overwrite end, so you get a new line. In your second print command, you do overwrite end with a single whitespace.\nWhat you get is this order:\n1st print NEWLINE\n2nd print SPACE 1st print ... | [
1,
0
] | [] | [] | [
"for_loop",
"python",
"python_3.x"
] | stackoverflow_0074651923_for_loop_python_python_3.x.txt |
Q:
Match True in python
In JavaScript, using the switch statement, I can do the following code:
switch(true){
case 1 === 1:
console.log(1)
break
case 1 > 1:
console.log(2)
break
default:
console.log(3)
break
}
And it's going to return 1, since JavaScript ... | Match True in python | In JavaScript, using the switch statement, I can do the following code:
switch(true){
case 1 === 1:
console.log(1)
break
case 1 > 1:
console.log(2)
break
default:
console.log(3)
break
}
And it's going to return 1, since JavaScript switch is comparing true =... | [
"\nIn JavaScript, using the switch statement, I can do the following code\n\nI definitely wouldn't be using JavaScript as any form of litmus or comparator for python.\n\nIf you used 1==1 in your first test case, the below is what both of your test cases are ultimately doing.\nmatch True:\n case True:\n pr... | [
1,
1,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074209719_python_python_3.x.txt |
Q:
After updating python version, old downloaded packages not working in vsc when using jupyter
I updated my python version to latest in my WSL and now when running the latest kernel version with Visual Studio Code jupyter extension it cannot regognize the packages I have downloaded from pip with the earlier version.... | After updating python version, old downloaded packages not working in vsc when using jupyter | I updated my python version to latest in my WSL and now when running the latest kernel version with Visual Studio Code jupyter extension it cannot regognize the packages I have downloaded from pip with the earlier version.
With the earlier version (3.8.10) when I run
import torch
all goes normal, but when using (3.11.... | [
"Good practice is to have virtual env for each python version, using Anaconda or pipenv.\nin your case you may change the python path to the new version\nin you .bashrc file\nexport PYTHONPATH=${PYTHONPATH}:${HOME}/[path to new version]\n\nsource .bashrc and you good to go\nyou can now install packages to the new v... | [
2
] | [] | [] | [
"jupyter_notebook",
"kernel",
"pip",
"python",
"visual_studio_code"
] | stackoverflow_0074652560_jupyter_notebook_kernel_pip_python_visual_studio_code.txt |
Q:
query = query % self._escape_args(args, conn) TypeError: unsupported operand type(s) for %: 'tuple' and 'str'
[enter[
query = query % self._escape_args(args, conn) TypeError: unsupported operand type(s) for %: 'tuple' and 'str'
](https://i.stack.imgur.com/nkDJb.png) image description here](https://i.stack.imgur... | query = query % self._escape_args(args, conn) TypeError: unsupported operand type(s) for %: 'tuple' and 'str' | [enter[
query = query % self._escape_args(args, conn) TypeError: unsupported operand type(s) for %: 'tuple' and 'str'
](https://i.stack.imgur.com/nkDJb.png) image description here](https://i.stack.imgur.com/zIEAR.png)
update on the datas on the sql database
| [] | [] | [
"I'd like to help. But you haven't really posted a question here.\nThe pictures you have linked don't seem to explicitly cover the code you have in the post (query = query %...)\nFrom the code you have posted you are trying to run a math operation between a string and a tuple, which is not possible.\nIf you are try... | [
-1
] | [
"python"
] | stackoverflow_0074652272_python.txt |
Q:
How can get products for active owners (users) only with Django Rest Framework?
I'm creating an e-commerce API with DRF.
I would like to retrieve and display only active products from active owners (users) using a ModelViewSet How can I do this? Here is my code :
views.py
class ProductViewSet(viewsets.ModelViewSet... | How can get products for active owners (users) only with Django Rest Framework? | I'm creating an e-commerce API with DRF.
I would like to retrieve and display only active products from active owners (users) using a ModelViewSet How can I do this? Here is my code :
views.py
class ProductViewSet(viewsets.ModelViewSet):
serializer_class = ProductSerializer
parser_classes = (MultiPartParser, Fo... | [
"if u have a model like this:\nclass Prooduct(m.Model):\n ...\n is_active = m.BooleanField()\n owner = m.ForeingKey(User, ...)\n\n\nThen on the get_queryset method\ndef get_queryset(self)\n\n return Product.objects.filter(is_active = True, owner__is_active = True)\n\nthis would return all products that ... | [
0
] | [] | [] | [
"django",
"django_rest_framework",
"django_views",
"python"
] | stackoverflow_0074648593_django_django_rest_framework_django_views_python.txt |
Q:
Select all the values from a drag and drop Listbox in python
I am trying to create a gui in tkinter where I will have a Listbox and be able to drag and drop files into it. How can I store all the items inside this listbox in a list with a command on the button?
lb = tk.Listbox(root, height=8)
lb.drop_target_regist... | Select all the values from a drag and drop Listbox in python | I am trying to create a gui in tkinter where I will have a Listbox and be able to drag and drop files into it. How can I store all the items inside this listbox in a list with a command on the button?
lb = tk.Listbox(root, height=8)
lb.drop_target_register(DND_FILES)
lb.dnd_bind("<<Drop>>", lambda e: lb.insert(tk.END, ... | [
"First you need to assign a callback to the command option of the button, then you can use lb.get(0, tk.END) to get the item list inside the callback:\n...\ndef submit():\n # in case you need to access itemlist outside this function\n global itemlist\n # get all the items inside the listbox to itemlist\n ... | [
1
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074639094_python_tkinter.txt |
Q:
python seaborn plot title or footnote including variable?
I'd like to be able to include a variable in either the title (subtitle) or footnote text on a seaborn pairplot -- I'm selecting for a date range and specifically want to add the dates and a name.
I can easily put a static title on the pairplot and it runs ... | python seaborn plot title or footnote including variable? | I'd like to be able to include a variable in either the title (subtitle) or footnote text on a seaborn pairplot -- I'm selecting for a date range and specifically want to add the dates and a name.
I can easily put a static title on the pairplot and it runs as expected.
Here's the code:
subData = rslt_avgData[['averageS... | [
"Seaborn is based on Matplotlib and you can use the syntax from matplotlib.pyplot.text()\n\ntext(x, y, s, fontdict=None, **kwargs)\nAdd text to the Axes.\nAdd the text s to the Axes at location x, y in data coordinates.\nParameters:\nx, y: float\nThe position to place the text. By default, this is in data coordinat... | [
0
] | [] | [] | [
"pairplot",
"python",
"seaborn"
] | stackoverflow_0074652376_pairplot_python_seaborn.txt |
Q:
How to set proxy on cmd or python for windows 10?
can anyone help me about this? I just wanna set up a proxy with cmd or python. I have tried these but it doesn't work.
First try(on cmd):
netsh winhttp set proxy proxy-ip:proxy-port
Output:
C:\Windows\system32>netsh winhttp show proxy
Current WinHTTP proxy settin... | How to set proxy on cmd or python for windows 10? | can anyone help me about this? I just wanna set up a proxy with cmd or python. I have tried these but it doesn't work.
First try(on cmd):
netsh winhttp set proxy proxy-ip:proxy-port
Output:
C:\Windows\system32>netsh winhttp show proxy
Current WinHTTP proxy settings:
Proxy Server(s) : proxy-ip:proxy-port
Bypa... | [
"When you need something major changes on OS, you should provide admin permissions, here is the solution;\npip install elevate\n\nAnd you can use this code;\nimport os\nfrom elevate import elevate\n\nelevate(show_console=False)\n\ncommand = 'netsh winhttp set proxy proxy_ip:proxy_port bypass-list=\"localhost\"'\nos... | [
0
] | [] | [] | [
"cmd",
"proxy",
"python",
"windows"
] | stackoverflow_0074641570_cmd_proxy_python_windows.txt |
Q:
I have a dataframe in which one columns contains day and time and I want to put each day and its time in different column
I have a dataframe in which one column contains day and its time, I want to put that each day and its time in its respective column.
I have put a '$' in each day to either split or use it to pu... | I have a dataframe in which one columns contains day and time and I want to put each day and its time in different column | I have a dataframe in which one column contains day and its time, I want to put that each day and its time in its respective column.
I have put a '$' in each day to either split or use it to put it in its respective column.
import pandas as pd
data = [{'timings' : 'Friday 10 am - 6:30 pm$Saturday 10am-6:30pm$Sunday Cl... | [
"Use nested list comprehension for list of dictionaries, then pass to DataFrame constructor:\nL = [dict(y.split(maxsplit=1) for y in x.split('$')) for x in df['timings']]\n\ndf = pd.DataFrame(L, index=df.index)\nprint (df) \n Friday Saturday Sunday Monday Tuesday \\\n0 10 am - 6:30 pm ... | [
0,
0
] | [] | [] | [
"dataframe",
"numpy",
"pandas",
"python"
] | stackoverflow_0074652369_dataframe_numpy_pandas_python.txt |
Q:
Visual Studio Select Python Interpreter error
Am trying to use visual studio to run my python notebook. I have setup my venv.
I managed to select my Python interpreter in visual studio code using the ctrl + shift + p function to the specific python script in my newly made venv as per image below
But the kernel st... | Visual Studio Select Python Interpreter error | Am trying to use visual studio to run my python notebook. I have setup my venv.
I managed to select my Python interpreter in visual studio code using the ctrl + shift + p function to the specific python script in my newly made venv as per image below
But the kernel still remains the same as per image below
Appreciate... | [
"My jupyter extension version is v2022.9.1303220346.\nIf your are pre-release version. You can switch to release version.\nAnd you can try the following way to find python interpreter.\nOpen your settins and search for Python Path.\n\nEnter the absolute path here manually.\n"
] | [
0
] | [] | [] | [
"python",
"visual_studio_code"
] | stackoverflow_0074652226_python_visual_studio_code.txt |
Q:
having an issue when installing pygraphviz
I'm having an issue when trying to install pygraphviz via pip. It took a long time, but I managed to install graphviz.
(base) C:\Users\>pip install graphviz --upgrade
Requirement already satisfied: graphviz in c:\programdata\anaconda3\lib\site-packages (0.19.2)
I am usin... | having an issue when installing pygraphviz | I'm having an issue when trying to install pygraphviz via pip. It took a long time, but I managed to install graphviz.
(base) C:\Users\>pip install graphviz --upgrade
Requirement already satisfied: graphviz in c:\programdata\anaconda3\lib\site-packages (0.19.2)
I am using Python 3.9.7 and the OS is Windows 10. When I ... | [
"Try to install from your Anaconda environment:\nconda install -c conda-forge python-graphviz\n"
] | [
0
] | [] | [] | [
"graphviz",
"pygraphviz",
"python"
] | stackoverflow_0071845331_graphviz_pygraphviz_python.txt |
Q:
Google Auth Service Account Bearer Photo API
I am trying to upload an image to google photos service using a google service account with a domain-wide delegation to use a user@domain.com account.
Somehow I only get a 401 error: "Authentication session is not defined." using the code below
What am I doing wrong?
CO... | Google Auth Service Account Bearer Photo API | I am trying to upload an image to google photos service using a google service account with a domain-wide delegation to use a user@domain.com account.
Somehow I only get a 401 error: "Authentication session is not defined." using the code below
What am I doing wrong?
CODE:
class GooglePhotosApi:
def __init__(self):... | [
"You may want to consult the Google Photos api documentation on service-accounts\n\n"
] | [
0
] | [] | [] | [
"google_api_python_client",
"google_photos",
"google_photos_api",
"python",
"service_accounts"
] | stackoverflow_0074652665_google_api_python_client_google_photos_google_photos_api_python_service_accounts.txt |
Q:
Segmentation fault after calling py_Finalize() with python version higher than 3.6
I am using ubuntu 18.04 LTS.
I am embedding python to C++ for uploading logs to azure application insights. My code worked well with python3.6 but now support is not available for python3.6 for the python core team. So I am trying t... | Segmentation fault after calling py_Finalize() with python version higher than 3.6 | I am using ubuntu 18.04 LTS.
I am embedding python to C++ for uploading logs to azure application insights. My code worked well with python3.6 but now support is not available for python3.6 for the python core team. So I am trying to use a higher version of python for my code, but it causes a segmentation fault when re... | [
"I found solution for the issue I was facing.\nIsuue as per my understandings:\nMy concern was to upload data to cloud on every iteration. I was calling Py_Initialize() and Py_FinalizeEx() in order to do that.\nBut with python versions higher than 3.6, memory for external library was not getting freed correctly. Th... | [
0
] | [] | [] | [
"azure_application_insights",
"opencensus",
"python",
"python_3.8",
"segmentation_fault"
] | stackoverflow_0074637543_azure_application_insights_opencensus_python_python_3.8_segmentation_fault.txt |
Q:
LoRa HAT communication module doesn't send anything
I'm working on a long-range communication system, and I need help. I can't use GSM, WIFI, etc. I am testing a LoRa Raspberry Pi shield, and I bought this, and I have followed this tutorial. Of course I have tested other tutorials, like this, this lib, and others.... | LoRa HAT communication module doesn't send anything | I'm working on a long-range communication system, and I need help. I can't use GSM, WIFI, etc. I am testing a LoRa Raspberry Pi shield, and I bought this, and I have followed this tutorial. Of course I have tested other tutorials, like this, this lib, and others. None of them worked.
I have bought another 2 modules, be... | [
"The problem is with the eByte module on the RPi shield. What module are you using on the other end? The same? Or something else? If it's the same, it should work. But if you are using a non-eByte, regular LoRa module, like an SX1276 or SX1262 attached to an ESP32, forget about it, it won't work. It turns out that ... | [
0
] | [] | [] | [
"communication",
"lora",
"python",
"raspberry_pi",
"raspberry_pi4"
] | stackoverflow_0074421719_communication_lora_python_raspberry_pi_raspberry_pi4.txt |
Q:
howto install pygraphviz on windows 10 64bit
Has anyone succeeded in installing pygraphviz on windows 10 64bit? I tried anaconda with python 3.5 64bit & 32bit with no success.
Here is the error I am getting with python 3.5 32bit on win10 64bit
python -m pip install pygraphviz --install-option="--include-path=C:\Pr... | howto install pygraphviz on windows 10 64bit | Has anyone succeeded in installing pygraphviz on windows 10 64bit? I tried anaconda with python 3.5 64bit & 32bit with no success.
Here is the error I am getting with python 3.5 32bit on win10 64bit
python -m pip install pygraphviz --install-option="--include-path=C:\Program Files (x86)\Graphviz2.38\include" --install-... | [
"I've created a build of PyGraphviz 1.5 on my Anaconda channel for Windows 64 bit running Python 3.6 through 3.9. If you're running Anaconda, you can install with:\nconda install -c alubbock pygraphviz\n\nThis will also install Graphviz 2.41 as a dependency (don't install it separately, it might conflict and not al... | [
42,
10,
8,
2,
2,
2,
1,
0
] | [
"If all the solutions above failed, you can still clone directly from the pygraphviz repository\n\nVisit: https://github.com/pygraphviz/pygraphviz.git\nDownload/Clone it\nput the folder into C:\\Users\\\\AppData\\Local\\Programs\\Python\\Python37-32\\Lib\\site-packages\nChange directory to “pygraphviz”\nRun “python... | [
-1
] | [
"64_bit",
"pygraphviz",
"python",
"windows_10"
] | stackoverflow_0040809758_64_bit_pygraphviz_python_windows_10.txt |
Q:
How Do You Enumerate Over a List of Strings, Converting Each String to Its Own List?
I know I can use split and variable assignment to convert a string within a list to a separate list, like this:
list_of_strings = ["the 1st string", "the 2nd string", "the 3rd string"]
first_list = list_of_strings[0].split(" ")
... | How Do You Enumerate Over a List of Strings, Converting Each String to Its Own List? | I know I can use split and variable assignment to convert a string within a list to a separate list, like this:
list_of_strings = ["the 1st string", "the 2nd string", "the 3rd string"]
first_list = list_of_strings[0].split(" ")
But what I cannot quite figure out how to do is how to do this conversion through enumerat... | [
"I'd use list comprehension for this task:\nlist_of_split_string = [the_string.split(\" \") for the_string in list_of_strings]\n\n",
"You could use map on your list to apply str.split to all its elements:\nlist(map(str.split,list_of_strings))\n\n[['the', '1st', 'string'], ['the', '2nd', 'string'], ['the', '3rd', ... | [
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074645728_python.txt |
Q:
How to put legends in each plots
I am new learner of python and I'm having hard time to make a legend in each 4 graphs.
I want to put each equation's formula in the legend. I cant think about more to make the legend on the graphs.
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
mpl.rcP... | How to put legends in each plots | I am new learner of python and I'm having hard time to make a legend in each 4 graphs.
I want to put each equation's formula in the legend. I cant think about more to make the legend on the graphs.
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
mpl.rcParams['lines.color'] = 'k'
mpl.rcParam... | [
"The issue is that contour plots do not really support labels (they work a bit different than the usual plot). If you need to use contour, I don't see a better way (please, proof me wrong!) then \"sneaking\" the label in by adding a regular plot with just a single point. E.g. like this:\na = 2\nb = 1\naxes(ax[1, 1]... | [
1
] | [] | [] | [
"graph",
"python",
"subplot"
] | stackoverflow_0074651128_graph_python_subplot.txt |
Q:
Use Spacy with Pandas
I'm trying to build a multi-class text classifier using Spacy and I have built the model, but facing a problem applying it to my full dataset. The model I have built so far is in the screenshot:
Screenshot
Below is the code I used to apply to my full dataset using Pandas:
Messages = pd.read_... | Use Spacy with Pandas | I'm trying to build a multi-class text classifier using Spacy and I have built the model, but facing a problem applying it to my full dataset. The model I have built so far is in the screenshot:
Screenshot
Below is the code I used to apply to my full dataset using Pandas:
Messages = pd.read_csv('Messages.csv', encodin... | [
"You should provide a callable into Series.apply call:\nMessages['NLP_Result'] = Messages['Body'].apply(lambda x: nlp(x)._.cats)\n\nHere, each value in the NLP_Result column will be assigned to x variable.\nThe nlp(x) will create an NLP object that contains the necessary properties you'd like to access. Then, the n... | [
0
] | [] | [] | [
"pandas",
"python",
"spacy",
"text_classification"
] | stackoverflow_0074649908_pandas_python_spacy_text_classification.txt |
Q:
Trying to load cookie into requests session from dictionary
I'm working with the python requests library. I am trying to load a requests session with a cookie from a dictionary:
cookie = {'name':'my_cookie','value': 'kdfhgfkj' ,'domain':'.ZZZ.org', 'expires':'Fri, 01-Jan-2020 00:00:00 GMT'}
I've tried:
s.cookies.... | Trying to load cookie into requests session from dictionary | I'm working with the python requests library. I am trying to load a requests session with a cookie from a dictionary:
cookie = {'name':'my_cookie','value': 'kdfhgfkj' ,'domain':'.ZZZ.org', 'expires':'Fri, 01-Jan-2020 00:00:00 GMT'}
I've tried:
s.cookies.set_cookie(cookie)
but this gives:
File "....lib\site-packages\r... | [
"cookies has a dictionary-like interface, you can use update():\ns.cookies.update(cookie)\n\nOr, just add cookies to the next request:\nsession.get(url, cookies=cookie)\n\nIt would \"merge\" the request cookies with session cookies and the newly added cookies would be retained for subsequent requests, see also:\n\n... | [
11,
0,
0
] | [] | [] | [
"cookies",
"python",
"python_requests",
"session"
] | stackoverflow_0031928942_cookies_python_python_requests_session.txt |
Q:
geting SyntaxError: invalid syntax jupyter labs
wring this batch of code and geting syntax exxor what seems to be the problem
File "", line 2
if color == 1: color_sq =
^
SyntaxError: invalid syntax
def calc_color(data, color=None):
if color == 1: color_sq =
['#dadaebFF','#bcbd... | geting SyntaxError: invalid syntax jupyter labs | wring this batch of code and geting syntax exxor what seems to be the problem
File "", line 2
if color == 1: color_sq =
^
SyntaxError: invalid syntax
def calc_color(data, color=None):
if color == 1: color_sq =
['#dadaebFF','#bcbddcF0','#9e9ac8F0',
'#807dbaF0... | [
"A few things on python syntax:\n\nindentations are required and need to be consistent\nafter a : you need a new-line\nno ;\n\nTry this:\ndef calc_color(data, color=None):\n if color == 1: \n color_sq = ['#dadaebFF','#bcbddcF0','#9e9ac8F0',\n '#807dbaF0','#6a51a3F0','#54278fF0'] \n ... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074652847_python.txt |
Q:
Why does calling the KFold generator with shuffle give the same indices?
With sklearn, when you create a new KFold object and shuffle is true, it'll produce a different, newly randomized fold indices. However, every generator from a given KFold object gives the same indices for each fold even when shuffle is true.... | Why does calling the KFold generator with shuffle give the same indices? | With sklearn, when you create a new KFold object and shuffle is true, it'll produce a different, newly randomized fold indices. However, every generator from a given KFold object gives the same indices for each fold even when shuffle is true. Why does it work like this?
Example:
from sklearn.cross_validation import KF... | [
"A new iteration with the same KFold object will not reshuffle the indices, that only happens during instantiation of the object. KFold() never sees the data but knows number of samples so it uses that to shuffle the indices. From the code during instantiation of KFold:\nif shuffle:\n rng = check_random_state(se... | [
6,
0
] | [] | [] | [
"cross_validation",
"python",
"scikit_learn"
] | stackoverflow_0034940465_cross_validation_python_scikit_learn.txt |
Q:
Anaconda Navigator and Spyder don't start
I am having a problem opening Spyder or Anaconda Navigator. Anaconda shell still works without a problem.
I already tried:
reinstalling Spyder
reinstalling Anaconda
opening it from shell with the following result:
(base) C:\Users\***>anaconda-navigator
Traceback (most re... | Anaconda Navigator and Spyder don't start | I am having a problem opening Spyder or Anaconda Navigator. Anaconda shell still works without a problem.
I already tried:
reinstalling Spyder
reinstalling Anaconda
opening it from shell with the following result:
(base) C:\Users\***>anaconda-navigator
Traceback (most recent call last):
File "C:\Users\***\anaconda3... | [
"I also got the same error after installing anaconda. What did for me was:\n\nuninstall all previous Anaconda installations\nextend admin rights to my local account\nselect the add PATH option during installation, even if not recommended\n\n"
] | [
0
] | [] | [] | [
"anaconda",
"python",
"spyder"
] | stackoverflow_0060952055_anaconda_python_spyder.txt |
Q:
AWS Greengrass doesn't send data to AWS Kinesis
The main purpose of my program is to connect to an incoming MQTT channel, and send the data received to my AWS Kinesis Stream called "MyKinesisStream".
Here is my code:
import argparse
import logging
import random
from paho.mqtt import client as mqtt_client
from str... | AWS Greengrass doesn't send data to AWS Kinesis | The main purpose of my program is to connect to an incoming MQTT channel, and send the data received to my AWS Kinesis Stream called "MyKinesisStream".
Here is my code:
import argparse
import logging
import random
from paho.mqtt import client as mqtt_client
from stream_manager import (
ExportDefinition,
Kinesi... | [
"After contacting official AWS personnel, we got the following answer:\n\nSo looking at the code a bit further its seems that The API call the\nstreams manager library is making to Kinesis is done asynchronously.\nWhat this means for your program is that when you try to call\nkinesis_client.append_message(stream_na... | [
0,
0
] | [] | [] | [
"amazon_kinesis",
"amazon_web_services",
"aws_iot_greengrass",
"greengrass",
"python"
] | stackoverflow_0074573002_amazon_kinesis_amazon_web_services_aws_iot_greengrass_greengrass_python.txt |
Q:
Decorator WITH arguments for FastAPI endpoint
I'm having this decorator:
def security(required_roles):
def decorator(function):
async def wrapper():
print("ROLES", required_roles)
return function
return wrapper
return decorator
and this endpoint, I want to decorate:... | Decorator WITH arguments for FastAPI endpoint | I'm having this decorator:
def security(required_roles):
def decorator(function):
async def wrapper():
print("ROLES", required_roles)
return function
return wrapper
return decorator
and this endpoint, I want to decorate:
@app.get(
"/me", summary="Get details of curre... | [
"You should pass the wrapper arguments to the wrapped function and await it:\ndef security(required_roles):\n def decorator(function):\n async def wrapper(user):\n print(\"ROLES\", required_roles)\n return await function(user)\n return wrapper\n return decorator\n\n"
] | [
0
] | [] | [] | [
"fastapi",
"python",
"python_decorators"
] | stackoverflow_0074652763_fastapi_python_python_decorators.txt |
Q:
Altair Charts containing Encoding of Special Characters
I am trying to plot a chart from a spreadsheet with this code.
import pandas as pd
import altair as alt
crude_df = pd.read_excel(open('PET_CONS_PSUP_DC_NUS_MBBLPD_M.xls', 'rb'),
sheet_name='Data 1',index_col=None, header=2)
alt.Chart(crude_df... | Altair Charts containing Encoding of Special Characters | I am trying to plot a chart from a spreadsheet with this code.
import pandas as pd
import altair as alt
crude_df = pd.read_excel(open('PET_CONS_PSUP_DC_NUS_MBBLPD_M.xls', 'rb'),
sheet_name='Data 1',index_col=None, header=2)
alt.Chart(crude_df.tail(100)).mark_circle().encode(
x = 'Date',
y = r'U... | [
"It has to do with the dot (.) present in the name of the columns of your spreadsheet/dataframe and It seems that the escape (suggested by the documentation) does not work in your case.\nAs a workaround, you can remove the dot with pandas str.replace before using altair.Chart.\nTry this :\nimport pandas as pd\nimpo... | [
1
] | [] | [] | [
"altair",
"python",
"python_3.x",
"visualization"
] | stackoverflow_0074652841_altair_python_python_3.x_visualization.txt |
Q:
matplotlib moasic subplots share y axis
I created a plt.subplots with 4 subplots (2*2) and I wanted all of them to share y axis, so I used sharey=True.
Later, I wanted to add another subplot below (2*3), and used plt.subplot_mosaicfor convinence. Now, I want the 2 subplots in the first row and the 2 subplots in th... | matplotlib moasic subplots share y axis | I created a plt.subplots with 4 subplots (2*2) and I wanted all of them to share y axis, so I used sharey=True.
Later, I wanted to add another subplot below (2*3), and used plt.subplot_mosaicfor convinence. Now, I want the 2 subplots in the first row and the 2 subplots in the seconed row to still share their Y ticks va... | [
"The sharey argument is not a valid argument for the subplot_mosaic function. It is only valid for the subplots function.\nYou can achieve the same effect by manually setting the y-axis limits on all of your subplots to be the same. This can be done using the set_ylim method of the axes object.\nHere is an example:... | [
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0074652999_matplotlib_python.txt |
Q:
Animation using pads in curses
I would like to move a curses pad across the screen, but I can't figure out a way to automatically erase the pad from the previous position in the screen without erasing the contents of the pad. I don't want to have to redraw the pad every time I move it. Here's my test program:
impo... | Animation using pads in curses | I would like to move a curses pad across the screen, but I can't figure out a way to automatically erase the pad from the previous position in the screen without erasing the contents of the pad. I don't want to have to redraw the pad every time I move it. Here's my test program:
import curses
import time
def main(stds... | [
"That's roughly the case. The sample code is inefficient however, doing extra repainting. Take a look at noutrefresh and doupdate (to replace those refresh calls), and replace the time.sleep with napms (again, to improve performance).\n"
] | [
0
] | [] | [] | [
"curses",
"python",
"python_3.x",
"python_curses"
] | stackoverflow_0074649261_curses_python_python_3.x_python_curses.txt |
Q:
Error importing plugin "sqlalchemy.ext.mypy.plugin": cannot import name 'Optional' from 'mypy.plugin'
Following the documentation here https://docs.sqlalchemy.org/en/14/orm/extensions/mypy.html I got an error while running mypy on any file using sqlalchemy mypy plugin.
To Reproduce
Create a new virtualenv using Py... | Error importing plugin "sqlalchemy.ext.mypy.plugin": cannot import name 'Optional' from 'mypy.plugin' | Following the documentation here https://docs.sqlalchemy.org/en/14/orm/extensions/mypy.html I got an error while running mypy on any file using sqlalchemy mypy plugin.
To Reproduce
Create a new virtualenv using Python 3.8
pip install sqlalchemy[mypy]==1.4
Create a simple mypy config (mypy.ini)
[mypy] plugins = sqlalc... | [
"Following the issue on GitHub the problem is the SQLAlchemy version.\nSQLAlchemy 1.4.0 is not supported.\nUsing SQLAlchemy 1.4.44 solved the problem.\n"
] | [
0
] | [] | [] | [
"mypy",
"python",
"sqlalchemy"
] | stackoverflow_0074642545_mypy_python_sqlalchemy.txt |
Q:
How to clean up anaconda base environment?
I have just reinstalled Miniconda. After that I ran pip list in base environment. The output is following:
Package Version
---------------------- ---------
brotlipy 0.7.0
certifi 2021.10.8
cffi 1.15.0
charset-n... | How to clean up anaconda base environment? | I have just reinstalled Miniconda. After that I ran pip list in base environment. The output is following:
Package Version
---------------------- ---------
brotlipy 0.7.0
certifi 2021.10.8
cffi 1.15.0
charset-normalizer 2.0.4
colorama 0.4.4... | [
"Do:\nconda uninstall -n base --all\n\n",
"i would do:\nconda clean -a -d\n#-d = dryrun\n\nand if that's okay with me\nconda clean -a -y\n#-y = yes (no promt)\n\n"
] | [
0,
0
] | [] | [] | [
"anaconda",
"miniconda",
"pip",
"python"
] | stackoverflow_0073978696_anaconda_miniconda_pip_python.txt |
Q:
how to not overwrite file in python in different os path
so i want to avoid overwrite the file name that existed. but i don't know how to combine the code with mycode. please help me
here's my code for write file:
def filepass(f):
print(f)
with open ('media/pass/'+'filepass.txt', 'a') as fo:
fo.wri... | how to not overwrite file in python in different os path | so i want to avoid overwrite the file name that existed. but i don't know how to combine the code with mycode. please help me
here's my code for write file:
def filepass(f):
print(f)
with open ('media/pass/'+'filepass.txt', 'a') as fo:
fo.write(f)
fo.close()
return fo
and here's the code to... | [
"Something like this?\ndef filepass(f):\n print(f)\n filename = find_next_filename('media/pass/filepass.txt')\n with open (filename, 'a') as fo:\n fo.write(f)\n # you don't need to close when you use \"with open\";\n # but then it doesn't make sense to return a closed file handle\n # ma... | [
0
] | [] | [] | [
"file",
"filenames",
"python"
] | stackoverflow_0074652931_file_filenames_python.txt |
Q:
Writing in a file while reading the keybord with pynput not working
from pynput.keyboard import Key, Listener
lol = open("GOTEM.txt",'a')
def on_press(key):
lol.write('{0}'.format(key))
with Listener(on_press=on_press) as listener:
listener.join()
lol.close()
100% a code problem because I tried writing ... | Writing in a file while reading the keybord with pynput not working | from pynput.keyboard import Key, Listener
lol = open("GOTEM.txt",'a')
def on_press(key):
lol.write('{0}'.format(key))
with Listener(on_press=on_press) as listener:
listener.join()
lol.close()
100% a code problem because I tried writing into a file without the whole keybord thing and it works just fine.I am n... | [
"You need to convert the key to char. You can use key.char to get the string without any single quotes around it. But be careful, as it will throw an AttributeError if the key is a special key like space, backspace, control keys etc. So you'll have to put it in a try/except block.\nYou should only open file when yo... | [
0
] | [] | [] | [
"file",
"pynput",
"python"
] | stackoverflow_0074652900_file_pynput_python.txt |
Q:
Can I select multiple elements in a Python dictionary with reference to position rather than specific keys?
I'm fairly new to Python, so I apologize if this question seems a little naive. I'm working on a final project for my comp sci class that involves visualizing some data, but I ran into some difficulty with i... | Can I select multiple elements in a Python dictionary with reference to position rather than specific keys? | I'm fairly new to Python, so I apologize if this question seems a little naive. I'm working on a final project for my comp sci class that involves visualizing some data, but I ran into some difficulty with it.
Basically, I'm using a CSV file (which you can find here) that contains reported emissions data from every cou... | [
"Because dictionaries are by default not sorted, i.e., the position of a key-value pair in a dictionary carries no meaning, you can't access any item through indexing. However, you can turn the dictionary into a list of tuples, where the keys are the first element, and the values are the second element of the tuple... | [
0
] | [] | [] | [
"csv",
"dictionary",
"python"
] | stackoverflow_0074636710_csv_dictionary_python.txt |
Q:
How to consume a rabbitmq stream starting from the last message in the stream?
I'd like to implement something with a similar behaviour to MQTT's "Retained Message". IE I want to attach a consumer and immediately start reading from the most recent message sent. It looks like Rabbitmq Streams should give me what ... | How to consume a rabbitmq stream starting from the last message in the stream? | I'd like to implement something with a similar behaviour to MQTT's "Retained Message". IE I want to attach a consumer and immediately start reading from the most recent message sent. It looks like Rabbitmq Streams should give me what I'm looking for.
I'm a little stuck because its possible to set the offset to last (... | [
"At the moment, it is not possible to determine the last message in a specific chuck.\nThis is because the clients don't expose all the chunk information.\nWhen you select last you get the last chuck. The chuck itself contains the number of messages. This information atm is not exposed.\nYou are using PIKA so amqp... | [
0
] | [] | [] | [
"pika",
"python",
"rabbitmq"
] | stackoverflow_0074644511_pika_python_rabbitmq.txt |
Q:
How to run the whole async function in given timeout?
From the last post, the duplicate post cannot answer my question.
Right now, I have a function f1() which contains CPU intensive part and async IO intensive part. Therefore f1() itself is an async function. How can I run the whole f1() with given timeout? I fou... | How to run the whole async function in given timeout? | From the last post, the duplicate post cannot answer my question.
Right now, I have a function f1() which contains CPU intensive part and async IO intensive part. Therefore f1() itself is an async function. How can I run the whole f1() with given timeout? I found the method provided in the post cannot solve my situatio... | [
"one way to do it is to make process not an async function, so it can run in another thread, and have it start an asyncio loop in the other thread to run f1.\nnote that starting another loops means you cannot share coroutines and futures between the two loops.\nimport asyncio\nimport time\nimport concurrent.futures... | [
0,
0
] | [] | [] | [
"python",
"python_asyncio"
] | stackoverflow_0074652884_python_python_asyncio.txt |
Q:
pandas `pd.melt` multiindex column usage
I'm having troubles trying to write intelligible pandas which makes me feel like I'm missing some feature or usage (probably of the pd.melt method).
I have two datasets I want to combine. Both are similar:
time indicating when the state changed
name and instance a compound... | pandas `pd.melt` multiindex column usage | I'm having troubles trying to write intelligible pandas which makes me feel like I'm missing some feature or usage (probably of the pd.melt method).
I have two datasets I want to combine. Both are similar:
time indicating when the state changed
name and instance a compound identity used to uniquely identify the record... | [
"Note that combined look like this after ffill.\n location state \nname a b a b \ninstance 0 1 2 1 2 0 1 2 1 2\ntime ... | [
0,
0,
0,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074575019_pandas_python.txt |
Q:
Executor Lost Failure (executor ID: 1): Likely due to containers exceeding thresholds, or network issues. Check driver logs for WARN messages
I'm using AWS Glue to run spark jobs.
My flow is more or less like:
client have defined rules (hundreds of them)
client select rules to run and provides input data
job take... | Executor Lost Failure (executor ID: 1): Likely due to containers exceeding thresholds, or network issues. Check driver logs for WARN messages | I'm using AWS Glue to run spark jobs.
My flow is more or less like:
client have defined rules (hundreds of them)
client select rules to run and provides input data
job takes data and execute each rule on that data
Rules are definned as python files, and system executes them by running:
for rule in rules:
result =... | [
"If you look closely at your error logs you see that you've got a java.lang.StackOverflowError at java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:3109). That seems to hint at the fact that the problem is related to your input data.\nAre the objects that you're reading in deeply nested... | [
1
] | [] | [] | [
"apache_spark",
"aws_glue",
"java",
"pyspark",
"python"
] | stackoverflow_0074015450_apache_spark_aws_glue_java_pyspark_python.txt |
Q:
Print out array in table widget
How to print out 1d array in table widget? I have array Sum_main(float data) and table table_Sum. Table has 1 col and 5 rows.
I tried this:
item=self.ui.table_Sum(str(Sum_main))
for row in range(5):
self.ui.table_Sum.setItem(row, 0, self.ui.table_Sum.item(str(Sum_main[row][0])))... | Print out array in table widget | How to print out 1d array in table widget? I have array Sum_main(float data) and table table_Sum. Table has 1 col and 5 rows.
I tried this:
item=self.ui.table_Sum(str(Sum_main))
for row in range(5):
self.ui.table_Sum.setItem(row, 0, self.ui.table_Sum.item(str(Sum_main[row][0])))
But get error: TypeError: 'QTableWi... | [
"Try this:\nfor row in range(5): \n item=QTableWidgetItem(str(Sum_main[row])) \n self.ui.table_Sum.setItem(row, 0, item) \n\n"
] | [
0
] | [] | [] | [
"python",
"qt",
"qt_designer"
] | stackoverflow_0074641616_python_qt_qt_designer.txt |
Q:
pytorch lightning "got an unexpected keyword argument 'weights_summary'"
I have been dealing an error when trying to learn Google "temporal fusion transformer" algorithm in anaconda spyder 5.1.5.
Guys, it is very important for me to solve this error. Somebody should say something. I will be very glad.
The example ... | pytorch lightning "got an unexpected keyword argument 'weights_summary'" | I have been dealing an error when trying to learn Google "temporal fusion transformer" algorithm in anaconda spyder 5.1.5.
Guys, it is very important for me to solve this error. Somebody should say something. I will be very glad.
The example which i use in the link below;
https://pytorch-forecasting.readthedocs.io/en/l... | [
"So, i had same ploblom as you have.\nI suggest you find out \"weights_suammry\" variable on your code\nI use .yaml file and put parameters of pytorch_lightning.Trainer automatically using hydra also use strategy=DDPStrategy(find~)\ni just realize there was weights_summary in .yaml file,\nthe structure was\ntrainer... | [
0,
0
] | [] | [] | [
"anaconda",
"optuna",
"python",
"pytorch_lightning"
] | stackoverflow_0074157157_anaconda_optuna_python_pytorch_lightning.txt |
Q:
Can pip (or setuptools, distribute etc...) list the license used by each installed package?
I'm trying to audit a Python project with a large number of dependencies and while I can manually look up each project's homepage/license terms, it seems like most OSS packages should already contain the license name and ve... | Can pip (or setuptools, distribute etc...) list the license used by each installed package? | I'm trying to audit a Python project with a large number of dependencies and while I can manually look up each project's homepage/license terms, it seems like most OSS packages should already contain the license name and version in their metadata.
Unfortunately I can't find any options in pip or easy_install to list m... | [
"Here is a copy-pasteable snippet which will print your packages.\nRequires: prettytable (pip install prettytable)\nCode\nimport pkg_resources\nimport prettytable\n\ndef get_pkg_license(pkg):\n try:\n lines = pkg.get_metadata_lines('METADATA')\n except:\n lines = pkg.get_metadata_lines('PKG-INFO... | [
36,
28,
17,
11,
4,
3,
2,
1,
1,
0,
0,
0
] | [] | [] | [
"easy_install",
"licensing",
"pip",
"python",
"virtualenv"
] | stackoverflow_0019086030_easy_install_licensing_pip_python_virtualenv.txt |
Q:
python - When are WebSocketHandler and TornadoWebSocketClient completely deleted?
I'm working on an application that must support client-server connections. In order to do that, I'm using the module of tornado that allows me to create WebSockets. I intend to be always in operation, at least the server-side. So I a... | python - When are WebSocketHandler and TornadoWebSocketClient completely deleted? | I'm working on an application that must support client-server connections. In order to do that, I'm using the module of tornado that allows me to create WebSockets. I intend to be always in operation, at least the server-side. So I am very worried about the performance and memory usage of each of the objects created on... | [
"The WebSocket code currently contains some reference cycles, which means that objects are not cleaned up until the next full GC. Even worse, __del__ methods can actually prevent the deletion of an object (in python 3.3 and older: https://docs.python.org/3.3/library/gc.html#gc.garbage), so it's difficult to tell wh... | [
3,
0
] | [] | [] | [
"object",
"python",
"tornado",
"websocket"
] | stackoverflow_0030806485_object_python_tornado_websocket.txt |
Q:
How to return a value from __init__ in Python?
I have a class with an __init__ function.
How can I return an integer value from this function when an object is created?
I wrote a program, where __init__ does command line parsing and I need to have some value set. Is it OK set it in global variable and use it in o... | How to return a value from __init__ in Python? | I have a class with an __init__ function.
How can I return an integer value from this function when an object is created?
I wrote a program, where __init__ does command line parsing and I need to have some value set. Is it OK set it in global variable and use it in other member functions? If so how to do that? So far,... | [
"Why would you want to do that?\nIf you want to return some other object when a class is called, then use the __new__() method:\nclass MyClass(object):\n def __init__(self):\n print \"never called in this case\"\n def __new__(cls):\n return 42\n\nobj = MyClass()\nprint obj\n\n",
"__init__ is r... | [
176,
157,
41,
23,
16,
10,
7,
4,
3,
0,
0
] | [
"solution here\nYes,\ntrying to return from the init method in python returns errors as it is a constructor of the class you can only assign values for the scope of the class but not return a specific value.\nif you want to return a value but do not wish to create a method, you can use\nstr method\ndef __init__(sel... | [
-3,
-4
] | [
"class",
"init",
"python"
] | stackoverflow_0002491819_class_init_python.txt |
Q:
Moving tables data from sqlite3 to postgressql
What is the simplest way to move data from sqlite3 tables to posgressql in Django project
A:
To perform a data backup, we use the following command:
python manage.py dumpdata > data.json #use this command adding before postgres in django
This command will generate ... | Moving tables data from sqlite3 to postgressql | What is the simplest way to move data from sqlite3 tables to posgressql in Django project
| [
"To perform a data backup, we use the following command:\npython manage.py dumpdata > data.json #use this command adding before postgres in django\n\nThis command will generate a data.json file in the root of your project, meaning you generated the dumpdata from SQLite and stored it in JSON format.\nSync Database\n... | [
0
] | [] | [] | [
"django",
"postgresql",
"python",
"sqlite"
] | stackoverflow_0074653143_django_postgresql_python_sqlite.txt |
Q:
iPython custom cell magic - store output in variable?
I recently discovered iPython magic functions and wrote some custom magic. I would like to use cell magic to parse strings, change them slightly and return the result.
Is there a way to store the output of my custom cell magic function in a variable?
I know you... | iPython custom cell magic - store output in variable? | I recently discovered iPython magic functions and wrote some custom magic. I would like to use cell magic to parse strings, change them slightly and return the result.
Is there a way to store the output of my custom cell magic function in a variable?
I know you can store the output of a line magic function like this:
@... | [
"You can use IPython's input/output caching system:\nOutput caching:\n\n_ (a single underscore): stores previous output, like Python’s default interpreter.\n__ (two underscores): next previous.\n___ (three underscores): next-next previous.\n_n (n being the prompt counter): the result of output \nactually, _4, Out[4... | [
2
] | [] | [] | [
"ipython",
"ipython_magic",
"jupyter_notebook",
"parsing",
"python"
] | stackoverflow_0074643538_ipython_ipython_magic_jupyter_notebook_parsing_python.txt |
Q:
Python Custom Package tries to load Cuda for every module
I have written a custom Python package with two modules as follows:
Project/
|-- deepmodel
|-- __init__.py
|-- deepmodelmodule.py
|-- standalone_utilities
|-- __init__.py
|-- standalone_module.py
|-- setup.py
|-- README
For the deepmodel ... | Python Custom Package tries to load Cuda for every module | I have written a custom Python package with two modules as follows:
Project/
|-- deepmodel
|-- __init__.py
|-- deepmodelmodule.py
|-- standalone_utilities
|-- __init__.py
|-- standalone_module.py
|-- setup.py
|-- README
For the deepmodel module I import tensorflow models so it makes total sense tha... | [
"It looks like the problem is with your setup.py file. You're using the find_namespace_packages function from setuptools, which allows you to specify which packages should be included in your package. However, you're not using this function properly.\nIn your setup.py file, you should specify the names of your pack... | [
0
] | [] | [] | [
"installation",
"python"
] | stackoverflow_0074653145_installation_python.txt |
Q:
Adding text or cross sign on every subplot of plotly, each in unique positions of the subplots
I am struggling to put a cross sign in certain positions of each subplots of plotly in Python. I have 2 subplots and in each one, I want to out the cross in certain positions as below.
Position of the cross sign at the s... | Adding text or cross sign on every subplot of plotly, each in unique positions of the subplots | I am struggling to put a cross sign in certain positions of each subplots of plotly in Python. I have 2 subplots and in each one, I want to out the cross in certain positions as below.
Position of the cross sign at the subplot_1 and 2 are attached.
import numpy as np
import plotly.graph_objs as go
import plotly.figure... | [
"There are two ways to deal with this question: the first is to use the line mode of the scatterplot and the second is to add a shape. In the line mode of the scatterplot, the real starting position is -0.5, so the heatmap and the cross line are misaligned. So I chose to add a figure.\nAlso, I can now annotate with... | [
0
] | [] | [] | [
"dataframe",
"matplotlib",
"numpy",
"plotly",
"python"
] | stackoverflow_0074650730_dataframe_matplotlib_numpy_plotly_python.txt |
Q:
Django not updated inside the docker cookiecutters template
My Django project that is created based on Cookiecutters is not updated in local development environment after I changed the source code, I need to stop and start the docker again. I checked the volume and it seems ok but still no auto-update. The files a... | Django not updated inside the docker cookiecutters template | My Django project that is created based on Cookiecutters is not updated in local development environment after I changed the source code, I need to stop and start the docker again. I checked the volume and it seems ok but still no auto-update. The files and their contents are as follow:
version: '3'
volumes:
one_sel... | [
"It seems you have copied a lot of things from production docker setup to your local docker setup. I assume you have also copied the production/django/start file as well. You can revert it back to its original version because gunicorn does not reload the server when code is changed (unless you allow it). The origin... | [
0
] | [] | [] | [
"cookiecutter_django",
"django",
"docker",
"python"
] | stackoverflow_0073616735_cookiecutter_django_django_docker_python.txt |
Q:
Create a vector length n with n entries 'x'
Example:
n = 5
x = 3.5
Output:
array([3.5, 3.5, 3.5, 3.5, 3.5])
My code:
import numpy as np
def init_all_x(n, x):
np.all = [x]*n
return np.all
init_all_x(5, 3.5)
My question:
Why init_all_x(5, 3.5).shape cannot run?
If my code is wrong, what is the correct code... | Create a vector length n with n entries 'x' | Example:
n = 5
x = 3.5
Output:
array([3.5, 3.5, 3.5, 3.5, 3.5])
My code:
import numpy as np
def init_all_x(n, x):
np.all = [x]*n
return np.all
init_all_x(5, 3.5)
My question:
Why init_all_x(5, 3.5).shape cannot run?
If my code is wrong, what is the correct code?
Thank you!
| [
"you can use np.ones\narr = np.ones(5)*3.5\n\n",
"Simple approach with numpy.repeat:\nn = 5\nx = 3.5\na = np.repeat(x, n)\n\nOutput:\narray([3.5, 3.5, 3.5, 3.5, 3.5])\n\n",
"For your requirement, no need to use Numpy lib, you can code like this:\ndef init_all_x(n, x):\n return [x]*n\n\np = init_all_x(5, 3.5)... | [
0,
0,
0,
0
] | [] | [] | [
"numpy",
"python",
"vector"
] | stackoverflow_0074652423_numpy_python_vector.txt |
Q:
Python Test Monkeypatch with Arguments
I try to create a mock test with monkeypatch. I have a typical service-repository class.
repository_class.py
find_by_id(id):
con.select(....);
service_class.py
get_details(id):
some pre-process...
item = repository_class.find_by_id(id)
post-process...
retu... | Python Test Monkeypatch with Arguments | I try to create a mock test with monkeypatch. I have a typical service-repository class.
repository_class.py
find_by_id(id):
con.select(....);
service_class.py
get_details(id):
some pre-process...
item = repository_class.find_by_id(id)
post-process...
return result
then I try to create a mock test ... | [
"monkeypatch couldn’t work for me. I used @patch or with patch functions.\n",
"Return value should be an (mock) object, so i would do it like this\ndef test_bid_on_brand_keyword(monkeypatch): \n monkeypatch.setattr(repository_class, 'find_by_id', lambda _:\"abc\")\n ans = service_class.get_details(id)\n ... | [
0,
0
] | [] | [] | [
"monkeypatching",
"pytest",
"python"
] | stackoverflow_0074516750_monkeypatching_pytest_python.txt |
Q:
cleaning date columns in python
Kindly assist me in cleaning my date types in python.
My sample data is as follows:
INITIATION DATE
DATE CUT
DATE GIVEN
1/July/2022
21 July 2022
11-July-2022
17-July-2022
16/July/2022
21/July/2022
16-July-2022
01-July-2022
09/July/2022
19-July-2022
31 July 2022
27 July 2022
Ho... | cleaning date columns in python | Kindly assist me in cleaning my date types in python.
My sample data is as follows:
INITIATION DATE
DATE CUT
DATE GIVEN
1/July/2022
21 July 2022
11-July-2022
17-July-2022
16/July/2022
21/July/2022
16-July-2022
01-July-2022
09/July/2022
19-July-2022
31 July 2022
27 July 2022
How do I remove all dashes/... | [
"to remove all dashes/slashes/hyphens from strings you can just use replace method:\ndf.apply(lambda x: x.str.replace('[/-]',' ',regex=True))\n\n>>>\n'''\n INITIATION DATE DATE CUT DATE GIVEN\n0 1 July 2022 21 July 2022 11 July 2022\n1 17 July 2022 16 July 2022 21 July 2022\n2 16 July 2022 0... | [
1,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074647975_python_python_3.x.txt |
Q:
How to get my program to read a text file properly?
Basically, I'm trying to get my program to read and display a list of grades from a file in the same folder called (grades.txt). Issue is, is the for some reason I keep getting an Index error no matter what I do. I've tried moving the text file in a different dir... | How to get my program to read a text file properly? | Basically, I'm trying to get my program to read and display a list of grades from a file in the same folder called (grades.txt). Issue is, is the for some reason I keep getting an Index error no matter what I do. I've tried moving the text file in a different directory, I tried changing the parameters of what the progr... | [
"the fileread function can be shortened a lot, as you can use \"normal\" string manipulation to do everything you're doing with your custom logic.\nand just to point out what is the problem with your current logic, the file you're reading does not end with a newline character, which is very common in files.\ndef fi... | [
0
] | [] | [] | [
"function",
"list",
"python",
"python_3.x",
"variables"
] | stackoverflow_0074653120_function_list_python_python_3.x_variables.txt |
Q:
Find out how much of a rectangle is filled with a color using OpenCV
I am using a webcam to segment a green piece of paper. I have tried different results using inRange and thresholding but have gotten a pretty good result so far.
I now have a rectangle in the middle of the screen which I want to check how much of... | Find out how much of a rectangle is filled with a color using OpenCV | I am using a webcam to segment a green piece of paper. I have tried different results using inRange and thresholding but have gotten a pretty good result so far.
I now have a rectangle in the middle of the screen which I want to check how much of it is filled with that green color because the camera will be moving, the... | [
"To check if the rectangle is filled with the green color, you can use the following steps:\n\nCreate a binary mask using the inRange method, with the range of the green color in the LAB color space. This will create a binary image where the green pixels are white, and the rest are black.\n\nUse the bitwise_and met... | [
1
] | [] | [] | [
"opencv",
"python",
"segment",
"threshold"
] | stackoverflow_0074653267_opencv_python_segment_threshold.txt |
Q:
The ScreenManager on my coding doesn't work on my program
I have a problem with my coding. I am trying to make ScreenManager work on my app. I have three button actions related to my project: a QR Code Scanner example on one screen, a checklist on one screen, and a hyperlink action button.
I am now trying to combi... | The ScreenManager on my coding doesn't work on my program | I have a problem with my coding. I am trying to make ScreenManager work on my app. I have three button actions related to my project: a QR Code Scanner example on one screen, a checklist on one screen, and a hyperlink action button.
I am now trying to combine all three into a single .py program, with a single .kv desig... | [
"This is were your problem is\nscreen_manager = ScreenManager(transition=\"SlideTransition()\")\n\nYou already created a WindowManager class which inherits from ScreenManager so you need to use WindowManager() instead of ScreenManager(). Also the qoutation marks must be removed\nLike this\nscreen_manager = WindowMa... | [
0
] | [] | [] | [
"kivy",
"pycharm",
"python"
] | stackoverflow_0074651294_kivy_pycharm_python.txt |
Q:
Finding anagrams of a specific word in a list
So, the problem is:
Given an array of m words and 1 other word, find all anagrams of that word in the array and print them.
Do y’all have any faster algorithm?:)
I’ve succesfully coded this one, but it seems rather slow ( i’ve been using sorted() with a for loop + chec... | Finding anagrams of a specific word in a list | So, the problem is:
Given an array of m words and 1 other word, find all anagrams of that word in the array and print them.
Do y’all have any faster algorithm?:)
I’ve succesfully coded this one, but it seems rather slow ( i’ve been using sorted() with a for loop + checking the length before). Found anagrams were added ... | [
"I think that counting characters and comparing it will be faster but im not sure. Just check it ;)\ndefaultdict will be helpful.\nfrom collections import defaultdict as dd\n\ndef char_counter(word: str)-> dict\n result = dd(int)\n for c in word:\n result[c]+=1\n return result\n\n"
] | [
0
] | [] | [] | [
"anagram",
"python"
] | stackoverflow_0074653326_anagram_python.txt |
Q:
How can you change the precision of the percentage field in tqdm?
I have a very large iterable which means a lot of iterations must pass before the bar updates by 1%. It populates a sqlite database from legacy excel sheets.
Minimum reproducible example is something like this.
from tqdm import tqdm, trange
import t... | How can you change the precision of the percentage field in tqdm? | I have a very large iterable which means a lot of iterations must pass before the bar updates by 1%. It populates a sqlite database from legacy excel sheets.
Minimum reproducible example is something like this.
from tqdm import tqdm, trange
import time
percentage = 0
total = 157834
l_bar = '{desc}: {percentage:.3f}%|... | [
"bar_format doesn't work like that - it's not going to look up values of l_bar or r_bar that you define in your own code. All format specifiers will be filled in with values provided on tqdm's end.\nUse a single layer of formatting, based on the variables tqdm provides:\nfor row in tqdm(whatever, bar_format='{desc}... | [
1,
0
] | [] | [] | [
"python",
"python_3.x",
"tqdm"
] | stackoverflow_0074650215_python_python_3.x_tqdm.txt |
Q:
Showing Levels end values on contourf
I'm using a contourf to plot my data (var) and I would like to have 20 levels going from -100 to 100, so this what I did.
plt.contourf(var, levels=np.linspace(-100, 100, 21))
But when I plot it it will miss the end values (-100 and 100), how can I solve it and show these valu... | Showing Levels end values on contourf | I'm using a contourf to plot my data (var) and I would like to have 20 levels going from -100 to 100, so this what I did.
plt.contourf(var, levels=np.linspace(-100, 100, 21))
But when I plot it it will miss the end values (-100 and 100), how can I solve it and show these values?
Thanks in advance.
Image
| [
"You can have a fine control of the values shown in the colorbar:\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nx, y = np.mgrid[-2:2:100j,-2:2:100j]\nz = 100 * np.cos(x**2 + y**2)\n\nfig, ax = plt.subplots()\nc = ax.contourf(x, y, z, levels=np.linspace(-100, 100, 21))\ncb = fig.colorbar(c)\nticks = np.lin... | [
0
] | [] | [] | [
"contourf",
"python"
] | stackoverflow_0074653337_contourf_python.txt |
Q:
Deleting immediately subsequent rows which are the exact same as the previous for specific columns
I have a dataframe similar to the following.
import pandas as pd
data = pd.DataFrame({'ind': [111,222,333,444,555,666,777,888,999,000],
'col1': [1,2,2,2,3,4,5,5,6,7],
'col... | Deleting immediately subsequent rows which are the exact same as the previous for specific columns | I have a dataframe similar to the following.
import pandas as pd
data = pd.DataFrame({'ind': [111,222,333,444,555,666,777,888,999,000],
'col1': [1,2,2,2,3,4,5,5,6,7],
'col2': [9,2,2,2,9,9,5,5,9,9],
'col3': [11,2,2,2,11,11,5,5,11,11],
... | [
"You can use shift and any for boolean indexing:\ncols = ['col1', 'col2', 'col3']\nout = data[data[cols].ne(data[cols].shift()).any(axis=1)]\n# DeMorgan's equivalent:\n# out = data[~data[cols].eq(data[cols].shift()).all(axis=1)]\n\nOutput:\n ind col1 col2 col3 val\n0 111 1 9 11 a\n1 222 2 ... | [
1,
1
] | [] | [] | [
"dataframe",
"duplicates",
"pandas",
"python"
] | stackoverflow_0074653428_dataframe_duplicates_pandas_python.txt |
Q:
Three lists within a tuple. How to make a dictionary?
I am trying to turn a list of tuples into a dictionary, but I keep on getting the same error: "'unhashable type: 'list'". I believe this might be the case due to having lists within the tuple itself.
An example of how the list looks now:
[([183, 'receiver', 'A'... | Three lists within a tuple. How to make a dictionary? | I am trying to turn a list of tuples into a dictionary, but I keep on getting the same error: "'unhashable type: 'list'". I believe this might be the case due to having lists within the tuple itself.
An example of how the list looks now:
[([183, 'receiver', 'A', '-', '67', '-', 'Amsterdam'],
[31, 'donor', '-', 'O', '... | [
"As @ShadowRanger mentioned already, mutable object cannot be an key of dictionary. Python uses hashes to efficiently manage dictionary keys and list allows in place modifications that can change its hash value. Supporting it would mean each list (or other mutable object) modification would require tracking if hash... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074615327_python.txt |
Q:
How to call a python built-in function in c++ with pybind11
I am using pybind11 to call a python built-in function like range in c++ code. But I only found way to call a function in module like this:
py::object os = py::module::import("os");
py::object makedirs = os.attr("makedirs");
makedirs("/tmp/path/to/somewhe... | How to call a python built-in function in c++ with pybind11 | I am using pybind11 to call a python built-in function like range in c++ code. But I only found way to call a function in module like this:
py::object os = py::module::import("os");
py::object makedirs = os.attr("makedirs");
makedirs("/tmp/path/to/somewhere");
But a python built-in function like range needn't import a... | [
"You could fetch range from the globals dict.\n",
"You can also import the builtins module which contains all the built-in python functions.\nIn your case it would be something like:\npy::object builtins = py::module_::import(\"builtins\");\npy::object range = builtins.attr(\"range\");\nrange(0, 10);\n\n"
] | [
1,
0
] | [] | [] | [
"c++",
"pybind11",
"python"
] | stackoverflow_0064135495_c++_pybind11_python.txt |
Q:
Is it possible to rename a json key name using its value in Python?
I have this nested json dictionary and I want to rename the key name 'Keys' with its equivalent value using Python. I wonder if this is possible?
Current - 'Keys': ['AWS Backup']
I want it to be - AWS Backup: ['AWS Backup']
Sample json dictionary... | Is it possible to rename a json key name using its value in Python? | I have this nested json dictionary and I want to rename the key name 'Keys' with its equivalent value using Python. I wonder if this is possible?
Current - 'Keys': ['AWS Backup']
I want it to be - AWS Backup: ['AWS Backup']
Sample json dictionary
{
"TimePeriod": {
"Start": "2022-11-28",
"End": "2022-1... | [
"Yes, it is possible to rename a JSON key name using its value in Python. Here is an example of how you can do this using the json module:\nimport json\n\n# Original JSON dictionary\ndata = {\n 'TimePeriod': {'Start': '2022-11-28', 'End': '2022-11-29'},\n 'Total': {},\n 'Groups': [\n {'Keys': ['AWS ... | [
0
] | [] | [] | [
"dataframe",
"json",
"nested_json",
"pandas",
"python"
] | stackoverflow_0074653523_dataframe_json_nested_json_pandas_python.txt |
Q:
Change Aspect Ratio of Video in Python
I have a video in 16:9 that I would like to be in 9:16. I have tried to use python libraries such as cv2, ffmpeg or MoviePy but some of them did it without the sound and others just compressed the whole video (it did not crop the left and right sides it just made the picture ... | Change Aspect Ratio of Video in Python | I have a video in 16:9 that I would like to be in 9:16. I have tried to use python libraries such as cv2, ffmpeg or MoviePy but some of them did it without the sound and others just compressed the whole video (it did not crop the left and right sides it just made the picture messy).
Is there a way to change the change ... | [
"I faced a similar problem to you and came up with the following solution using Moviepy. Moviepy will keep the sound.\nI'm going to assume your 16:9 videos are 1920w by 1080h and you don't want to resize / compress your video.\nThis means the maximum dimensions for your new 9:16 video can be 607.5w by 1080h.\n607.5... | [
0
] | [
"well try this\nimport cv2\nimport numpy as np\n\ncap = cv2.VideoCapture('C:/New folder/video.avi')\n\nfourcc = cv2.VideoWriter_fourcc(*'XVID')\nout = cv2.VideoWriter('output.avi',fourcc, 5, (1280,720))\n\nwhile True:\n ret, frame = cap.read()\n if ret == True:\n b = cv2.resize(frame,(1280,720),fx=0,fy... | [
-1
] | [
"edit",
"python",
"video"
] | stackoverflow_0073003948_edit_python_video.txt |
Q:
How do I plot excel time format with matplot?
I am trying to plot Formula 1 laptimes with matplotlib. I want the Y axis to show the laptimes, while the Xaxis shows the iD number of the race the laptimes belong to. The time is from a CSV file and the cell contains a date format, e.g., 01:22.0 reads as 12:01:24AM on... | How do I plot excel time format with matplot? | I am trying to plot Formula 1 laptimes with matplotlib. I want the Y axis to show the laptimes, while the Xaxis shows the iD number of the race the laptimes belong to. The time is from a CSV file and the cell contains a date format, e.g., 01:22.0 reads as 12:01:24AM on the excel cell.
`
raceId time millise... | [
"It looks like you're trying to plot the time column from your dataframe as the y-axis values of your plot. However, since you're using the pd.to_datetime function to convert the time column to datetime values, the y-axis of your plot will show dates instead of times.\nTo fix this, you can simply pass the time colu... | [
0
] | [] | [] | [
"jupyter_notebook",
"matplotlib",
"pandas",
"python"
] | stackoverflow_0074651416_jupyter_notebook_matplotlib_pandas_python.txt |
Q:
Lookup of Data from a CSV file in Python
How do I achieve this in Python. I know there is a vlookup function in excel but if there is a way in Python, I prefer to do it in Python. Basically my goal is to get data from CSV2 column Quantity and write the data to column Quantity of CSV1 based on Bin_Name. The script ... | Lookup of Data from a CSV file in Python | How do I achieve this in Python. I know there is a vlookup function in excel but if there is a way in Python, I prefer to do it in Python. Basically my goal is to get data from CSV2 column Quantity and write the data to column Quantity of CSV1 based on Bin_Name. The script should not copy all the value at once, it must... | [
"Hi you can simply iterate CSV2 first, then after gathering wanted value, you can search it in CSV1. I wrote a code below it might help you, but there can be much more efficient ways to do.\ndef func(wanted_rows: list,csv2df: pd.DataFrame):\n # Iterate csv2df\n for index,row in csv2df.iterrows():\n # C... | [
0,
0,
0,
0
] | [] | [] | [
"csv",
"lookup",
"python"
] | stackoverflow_0074652883_csv_lookup_python.txt |
Q:
"Discovering Python Interpreters" taking Infinite time in VS Code
I am new to Ubuntu, as well as to python.
( This problem has started just recently until now everything was fine.)
Whenever I am trying to start my VS Code to learn Django, the VS Code is showing the following issue for an infinite time
i.e., it is... | "Discovering Python Interpreters" taking Infinite time in VS Code | I am new to Ubuntu, as well as to python.
( This problem has started just recently until now everything was fine.)
Whenever I am trying to start my VS Code to learn Django, the VS Code is showing the following issue for an infinite time
i.e., it is not discovering Python interpreters.
The problem seems to be in the Py... | [
"I've recently started experiencing the same problem with VS Code (latest version), albeit on Windows 10. I'm using Python 3.10.4 from python.org, the latest Microsoft Python extension, and a virtual environment for the workspace in which I do Python development. The option to select the interpreter is dysfunctiona... | [
0,
0,
0,
0
] | [] | [] | [
"python",
"visual_studio_code"
] | stackoverflow_0071153859_python_visual_studio_code.txt |
Q:
print a one dictionary at a time to a table from a list of dictionaries
I want to print only Tom's recode to a table without using function
fe=[{"Name": "Tom", "age": 10,"group":"sdd","points":2,},
{"Name": "Mark", "age": 5,"group":"sdo","points":6,},
{"Name": "Pam", "age": 7,"group":"spp","points":4,}],
... | print a one dictionary at a time to a table from a list of dictionaries | I want to print only Tom's recode to a table without using function
fe=[{"Name": "Tom", "age": 10,"group":"sdd","points":2,},
{"Name": "Mark", "age": 5,"group":"sdo","points":6,},
{"Name": "Pam", "age": 7,"group":"spp","points":4,}],
dashes = "{:<20} + {:<8} + {:^14} + {:^11} \n".format("-"*20, "-"*8, "-"*10, ... | [
"value is 0.\nvalue = fe[0]\ninfo += \"{:<20} | {:<8} | {:^14} | {:^11} \\n\".format(value[\"Name\"],value[\"age\"],value[\"group\"],value[\"points\"])\n\n"
] | [
0
] | [] | [] | [
"dictionary",
"list",
"python",
"string"
] | stackoverflow_0074653317_dictionary_list_python_string.txt |
Q:
Optimizing script
I am working with high resolution raster data on a enormous land cover. I have achieved what I set out to (in terms of script result) and it works very well on a small raster file, however when applying it to a big raster file it takes ages.
The work flow is this:
Get aspect and slope raster fro... | Optimizing script | I am working with high resolution raster data on a enormous land cover. I have achieved what I set out to (in terms of script result) and it works very well on a small raster file, however when applying it to a big raster file it takes ages.
The work flow is this:
Get aspect and slope raster from a DEM raster file
Con... | [
"I managed to optimise it really well!\nFirst replacing all of\npv_apsect = aspect_layer.dataProvider()\npv_apsect.addAttributes([QgsField('ID', QVariant.Double)])\n\naspect_layer.updateFields()\n\nexpression = QgsExpression('$id')\n\ncontext = QgsExpressionContext()\ncontext.appendScopes(QgsExpressionContextUtils.... | [
0
] | [] | [] | [
"optimization",
"pyqgis",
"python",
"qgis"
] | stackoverflow_0074635048_optimization_pyqgis_python_qgis.txt |
Q:
Setting up Jupyter lab for python scripts on a cloud provider as a beginner
I have python scripts for automated trading for currency and I want to deploy them by running on Jupter Lab on a cloud instance. I have no experience with cloud computing or linux, so I have been trying weeks to get into this cloud computi... | Setting up Jupyter lab for python scripts on a cloud provider as a beginner | I have python scripts for automated trading for currency and I want to deploy them by running on Jupter Lab on a cloud instance. I have no experience with cloud computing or linux, so I have been trying weeks to get into this cloud computing mania, but I found it very difficult to participate in it.
My goal is to set u... | [] | [] | [
"\nFirst, you need to choose a cloud provider that offers the latest version of python and the necessary scientific packages. Some popular options include Amazon Web Services (AWS), Microsoft Azure, and Google Cloud Platform (GCP).\n\nOnce you have chosen a provider, you need to create an account and select a cloud... | [
-1
] | [
"cloud",
"devops",
"jupyter_notebook",
"python"
] | stackoverflow_0074625243_cloud_devops_jupyter_notebook_python.txt |
Q:
How i can fix Cannot resolve keyword 'pub-date' into field. Choices are: choice, id, pub_date, question_text
Python django
when I starting local sever,
I met only
Cannot resolve keyword 'pub-date' into field. Choices are: choice, id, pub_date, question_text
how can i fix?
window
error
at first the problem was abo... | How i can fix Cannot resolve keyword 'pub-date' into field. Choices are: choice, id, pub_date, question_text | Python django
when I starting local sever,
I met only
Cannot resolve keyword 'pub-date' into field. Choices are: choice, id, pub_date, question_text
how can i fix?
window
error
at first the problem was about direcotry, so read and search about django slash document.
and then i ment a new problem rn..
| [
"You got this error because you have written pub-date instead of pub_date somewhere in your code.\n"
] | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074653593_django_python.txt |
Q:
FastAPI decorators on endpoint
I'm trying to create role-based access control on endpoint and since fastAPI has this build-in Depends method with possibility to cache result I'm trying to create something like this
@router.get('/')
#decorator
@roles_decorator("admin")
async def get_items(user_id: str = Depends(ge... | FastAPI decorators on endpoint | I'm trying to create role-based access control on endpoint and since fastAPI has this build-in Depends method with possibility to cache result I'm trying to create something like this
@router.get('/')
#decorator
@roles_decorator("admin")
async def get_items(user_id: str = Depends(get_current_user)):
return await get_... | [
"Instead of trying to mix dependencies and decorators (which won't do anything good), you can instead use a dynamically configured dependency:\nasync def get_current_user_with_role(role):\n async def get_user_and_validate(user=Depends(get_current_user)):\n if not user.has_role(role):\n raise 40... | [
2
] | [] | [] | [
"fastapi",
"python"
] | stackoverflow_0074647143_fastapi_python.txt |
Q:
Mask an 2Darray row wise by another array
Consider the following 2d array:
>>> A = np.arange(2*3).reshape(2,3)
array([[0, 1, 2],
[3, 4, 5]])
>>> b = np.array([1, 2])
I would like to get the following mask from A as row wise condition from b as an upper index limit:
>>> mask
array([[True, False, False],
... | Mask an 2Darray row wise by another array | Consider the following 2d array:
>>> A = np.arange(2*3).reshape(2,3)
array([[0, 1, 2],
[3, 4, 5]])
>>> b = np.array([1, 2])
I would like to get the following mask from A as row wise condition from b as an upper index limit:
>>> mask
array([[True, False, False],
[True, True, False]])
Can numpy do this i... | [
"You can use array broadcasting:\nmask = np.arange(A.shape[1]) < b[:,None]\n\noutput:\narray([[ True, False, False],\n [ True, True, False]])\n\n",
"Another possible solution, based on the idea that the wanted mask corresponds to a boolean lower triangular matrix:\nmask = np.tril(np.ones(A.shape, dtype=boo... | [
3,
0
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0074653163_numpy_python.txt |
Q:
Why am I getting this error while installing pygame in pycharm
Command "python setup.py egg_info" failed with error code 1 in C:\Users\Eli Heist\AppData\Local\Temp\pip-install-fjf50xi9\pygame\
this is the full process
(venv) C:\Users\Eli Heist\PycharmProjects\Space Invaders Ultimate>pip install pygame
Collecting p... | Why am I getting this error while installing pygame in pycharm | Command "python setup.py egg_info" failed with error code 1 in C:\Users\Eli Heist\AppData\Local\Temp\pip-install-fjf50xi9\pygame\
this is the full process
(venv) C:\Users\Eli Heist\PycharmProjects\Space Invaders Ultimate>pip install pygame
Collecting pygame
Downloading https://files.pythonhosted.org/packages/c7/b8/06... | [
"You are seeing this error because pip is attempting to compile the complete SDL library for pygame, and your machine is missing the build requirements to do so. This is in your error message:\nMicrosoft Visual C++ 14.2 is required\n\nLuckily, pygame offers pre-compiled binaries for most operating systems so you do... | [
1,
0,
0
] | [] | [] | [
"pip",
"pycharm",
"pygame",
"python",
"python_3.x"
] | stackoverflow_0065858990_pip_pycharm_pygame_python_python_3.x.txt |
Q:
Get max key of dictionary based on ratio key:value
Here is my dictionary:
inventory = {60: 20, 100: 50, 120: 30}
Keys are total cost of goods [$] and values are available weight [lb].
I need to find a way to get key based on the highest cost per pound.
I have already tried using:
most_expensive = max(inventory, ke... | Get max key of dictionary based on ratio key:value | Here is my dictionary:
inventory = {60: 20, 100: 50, 120: 30}
Keys are total cost of goods [$] and values are available weight [lb].
I need to find a way to get key based on the highest cost per pound.
I have already tried using:
most_expensive = max(inventory, key={fucntion that calculates the ratio})
But cannot guess... | [
"What you are doing is correct. By using the key argument you can calculate the ratio. The thing you are missing is that you want to compare the key and values, therefore you can use the inventory.items().\nThe code would be:\nmax(inventory.items(), key=lambda x: x[0]/x[1])\n\nWhich will result in the following if ... | [
2,
1,
0
] | [] | [] | [
"dictionary",
"python",
"python_3.x"
] | stackoverflow_0074653677_dictionary_python_python_3.x.txt |
Q:
Python extract value from multiple substring
I have a dataframe named df which has a column named "text" consisting of each row which a string like this: This is the string of the MARC data format.
d20s 22 i2as¶001VNINDEA455133910000005¶008180529c 1996 frmmm wz 7b ¶009se z 1 m mm c¶008a ¶008at ¶008ap ¶008a ¶0441 $... | Python extract value from multiple substring | I have a dataframe named df which has a column named "text" consisting of each row which a string like this: This is the string of the MARC data format.
d20s 22 i2as¶001VNINDEA455133910000005¶008180529c 1996 frmmm wz 7b ¶009se z 1 m mm c¶008a ¶008at ¶008ap ¶008a ¶0441 $a2609-2565$c2609-2565¶0410 $afre$aeng$apor ¶0569 $... | [
"You could try splitting and then cleaning up strings as follows\nimport pandas as pd\ntext = ('d20s 22 i2as¶001VNINDEA455133910000005¶008180529c 1996 frmmm wz 7b ¶009se z 1 m mm c¶008a ¶008at ¶008ap ¶008a ¶0441 $a2609-2565$c2609-2565¶0410 $afre$aeng$apor ¶0569 $a2758-8965$c4578-7854¶0300 $a789$987$754 ¶051 $atxt$a... | [
0
] | [] | [] | [
"extract",
"lambda",
"python",
"substring"
] | stackoverflow_0074653580_extract_lambda_python_substring.txt |
Q:
OpenCV getting very slow when using cap.set(cv2.CAP_PROP_POS_FRAMES
I'm using the following code to create a simple video player but I've seen that when I introduce the
cap.set(cv2.CAP_PROP_POS_FRAMES,arg) line, the all process is getting very slow while playing the video. The player works correctly with its track... | OpenCV getting very slow when using cap.set(cv2.CAP_PROP_POS_FRAMES | I'm using the following code to create a simple video player but I've seen that when I introduce the
cap.set(cv2.CAP_PROP_POS_FRAMES,arg) line, the all process is getting very slow while playing the video. The player works correctly with its trackbar but the speed is very slow.
In general I noted that every time you us... | [
"I had the same problem using python3 with opencv-python 4.5.5.64 on an m1 mac. ( Last known version to work with trackbar, as of writing this article ) The best explanation i've found is that random access it is naturally slow. Though, I recall using older versions of opencv-python with your code with absolutely n... | [
0
] | [] | [] | [
"opencv",
"python"
] | stackoverflow_0059951178_opencv_python.txt |
Q:
How should i set DJANGO_SETTINGS_MODULE, django.core.exceptions.ImproperlyConfigured: Requested setting EMAIL_BACKEND
i'm just start to learn Django and during create a priject i get a problem: "django.core.exceptions.ImproperlyConfigured: Requested setting EMAIL_BACKEND..."
I met description fo this problem on St... | How should i set DJANGO_SETTINGS_MODULE, django.core.exceptions.ImproperlyConfigured: Requested setting EMAIL_BACKEND | i'm just start to learn Django and during create a priject i get a problem: "django.core.exceptions.ImproperlyConfigured: Requested setting EMAIL_BACKEND..."
I met description fo this problem on Staciverflow but i don't understand in which file i should set DJANGO_SETTINGS_MODULE???
Please, give me detail description
I... | [
"settings.py file is where you set your project configuration file. one of them is the email backend server. i dont what you have in your project to raise this issue, but django has a built in server for testing perpose.\nInclude this line on your settings.py file\nEMAIL_BACKEND = 'django.core.mail.backends.console... | [
0
] | [] | [] | [
"django",
"django_rest_framework",
"django_settings",
"python"
] | stackoverflow_0074646555_django_django_rest_framework_django_settings_python.txt |
Q:
UDP conformation, is it possible?
I am using python to send a udp command to a Tello edu drone. The problem I am having is that the drone doesn’t read anything past the 1st command i send.
Is there are a way to confirm sending the UDP so the drone reads it at all cost. Or send the command until the drone reads it?... | UDP conformation, is it possible? | I am using python to send a udp command to a Tello edu drone. The problem I am having is that the drone doesn’t read anything past the 1st command i send.
Is there are a way to confirm sending the UDP so the drone reads it at all cost. Or send the command until the drone reads it?
I tried sending the 2nd command repeat... | [
"UDP is an unreliable protocol, i.e. sending a message is basically fire and forget. Any acknowledgements for received messages or retransmissions in case packets are not acknowledged need to be implemented at the application level - both in sender and receiver.\nIf the protocol used to communicate with the drone d... | [
0
] | [] | [] | [
"python",
"tello_drone",
"udp"
] | stackoverflow_0074653675_python_tello_drone_udp.txt |
Q:
How to hide/mask sensitive data from airflow connections and variable section?
We have many AWS connection string in apache airflow and anyone can see our access keys and secret keys in airflow webserver connections section. How to hide or mask sensitive data in airflow webserver?
We have already enabled authent... | How to hide/mask sensitive data from airflow connections and variable section? | We have many AWS connection string in apache airflow and anyone can see our access keys and secret keys in airflow webserver connections section. How to hide or mask sensitive data in airflow webserver?
We have already enabled authentication true in airflow configuration so it won't allow unauthorized users. But I do... | [
"For the Airflow Variables section, Airflow will automatically hide any values if the variable name contains secret or password. The check for this value is case-insensitive, so the value of a variable with a name containing SECRET will also be hidden.\n",
"I found workaround for this use case. There is an optio... | [
6,
1,
0,
0,
0
] | [] | [] | [
"airflow",
"python"
] | stackoverflow_0049528230_airflow_python.txt |
Q:
Schedulling for Cloud Dataflow Job
So, I already finish to create a job in Dataflow. This job to process ETL from PostgreSQL to BigQuery. So, I don't know to create a schedulling using Airflow. Can share how to schedule job dataflow using Airflow?
Thank you
A:
You can schedule dataflow batch jobs using Cloud Sch... | Schedulling for Cloud Dataflow Job | So, I already finish to create a job in Dataflow. This job to process ETL from PostgreSQL to BigQuery. So, I don't know to create a schedulling using Airflow. Can share how to schedule job dataflow using Airflow?
Thank you
| [
"You can schedule dataflow batch jobs using Cloud Scheduler (fully managed cron job scheduler) / Cloud Composer (fully managed workflow orchestration service built on Apache Airflow).\nTo schedule using Cloud Scheduler refer Schedule Dataflow batch jobs with Cloud Scheduler\nTo schedule using Cloud Composer refer ... | [
1,
1
] | [] | [] | [
"airflow",
"google_bigquery",
"google_cloud_dataflow",
"python"
] | stackoverflow_0074653520_airflow_google_bigquery_google_cloud_dataflow_python.txt |
Q:
What does `ValueError: cannot reindex from a duplicate axis` mean?
I am getting a ValueError: cannot reindex from a duplicate axis when I am trying to set an index to a certain value. I tried to reproduce this with a simple example, but I could not do it.
Here is my session inside of ipdb trace. I have a DataFrame... | What does `ValueError: cannot reindex from a duplicate axis` mean? | I am getting a ValueError: cannot reindex from a duplicate axis when I am trying to set an index to a certain value. I tried to reproduce this with a simple example, but I could not do it.
Here is my session inside of ipdb trace. I have a DataFrame with string index, and integer columns, float values. However when I tr... | [
"This error usually rises when you join / assign to a column when the index has duplicate values. Since you are assigning to a row, I suspect that there is a duplicate value in affinity_matrix.columns, perhaps not shown in your question.\n",
"As others have said, you've probably got duplicate values in your origi... | [
305,
239,
65,
41,
40,
21,
11,
6,
2,
1,
1,
0,
0,
0,
0,
0,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0027236275_pandas_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.