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:
Looking for any matching terms from file
I have a file that has a large list of Countries, years, and ages of living expectancies. I cannot figure out how to make sure the user is only allowed to input a year that actually exists. After figuring this out, I will need to call only those years (with corresponding co... | Looking for any matching terms from file | I have a file that has a large list of Countries, years, and ages of living expectancies. I cannot figure out how to make sure the user is only allowed to input a year that actually exists. After figuring this out, I will need to call only those years (with corresponding country name, code, and living expectancies. How... | [
"One could use DataFrames to handle such cases. To know more information on dataframe, take a look into Pandas.DataFrame\nTo select specific column contents from the dataframe: df[[<col_1>, <col_2>]]\nConsidering the data fetched could produce the following.\nimport pandas as pd\n\ndf = pd.read_csv(\"Life Expectanc... | [
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074557873_python.txt |
Q:
How to match two dataframes precisely and get the output as 1 if matched and 0 if not matched?
The dataframe is as follows:
df1:
name | age | state | number | score
------------------------------------------------------
A 23 AZ 5434567 92.1
B 54 ... | How to match two dataframes precisely and get the output as 1 if matched and 0 if not matched? | The dataframe is as follows:
df1:
name | age | state | number | score
------------------------------------------------------
A 23 AZ 5434567 92.1
B 54 AZ 1234543 87.6
C 32 AZ 7654344 89.9
D ... | [
"direct comparison of the dataframes should work, just cast from bool to integer:\ndf1.eq(df2).astype(int)\n# or (df1 == df2).astype(int)\n\noutput:\n name age state number\n0 1 1 0 1\n1 0 1 1 1\n2 1 0 1 1\n3 1 0 1 1\n\n",
"Could your is... | [
1,
1,
1,
0
] | [] | [] | [
"dataframe",
"match",
"pandas",
"python"
] | stackoverflow_0074557900_dataframe_match_pandas_python.txt |
Q:
Jenkins - how to capture a Boolean value in groovy
I'm looking for a way to capture a boolean value based on the python script. Basically, I've a python script that is triggered from the Jenkins file, it searches out a few articles. If the article is not found it should print an error msg at Jenkins.
I've tried as... | Jenkins - how to capture a Boolean value in groovy | I'm looking for a way to capture a boolean value based on the python script. Basically, I've a python script that is triggered from the Jenkins file, it searches out a few articles. If the article is not found it should print an error msg at Jenkins.
I've tried as follows, here is my Jenkins file:
stage('running te... | [
"I'm not familiar with phyton, but if you are 100% sure that your returned value is a boolean, you can perform this (it will convert to boolean whatever you send):\ndef rslt = sh(script: \"python3 -u test.py config/desktop\", returnStd: true)\n/* Other code Here */\nif (!rslt.toBoolean()) {\n echo 'article is not... | [
0
] | [] | [] | [
"groovy",
"jenkins",
"jenkins_groovy",
"jenkins_pipeline",
"python"
] | stackoverflow_0074556651_groovy_jenkins_jenkins_groovy_jenkins_pipeline_python.txt |
Q:
How to extract a single row table data from a pdf using python?
I need to extract tabular data from pdfs. Some tables in the pdf comprise of only a single row.
I have been trying to extract the data using camelot library.
Code for extraction using Camelot:
pip install camelot-py[cv] tabula-py here
import camelot
f... | How to extract a single row table data from a pdf using python? | I need to extract tabular data from pdfs. Some tables in the pdf comprise of only a single row.
I have been trying to extract the data using camelot library.
Code for extraction using Camelot:
pip install camelot-py[cv] tabula-py here
import camelot
file = 'xyz.pdf'
tables = camelot.read_pdf(file,pages ="all")
tables[6... | [
"As you can understand from the docs,\nif you want to detect smaller lines, you should increase line_scale parameter (default: 15).\nIn your case, this command works fine:\ntables = camelot.read_pdf(file, pages =\"all\", line_scale=80)\n\n"
] | [
0
] | [] | [] | [
"ocr",
"pdf",
"python",
"python_camelot",
"tabula_py"
] | stackoverflow_0074533410_ocr_pdf_python_python_camelot_tabula_py.txt |
Q:
networkx subgraph does not return the correct order of the edges
Does anyone know if there is a built-in function that is similar to subgraph but gives the correct order of the edges?
I try to create subgraph = G.subgraph(path) but this returns me an incorrect order of the edges which later returns me an incorrect... | networkx subgraph does not return the correct order of the edges | Does anyone know if there is a built-in function that is similar to subgraph but gives the correct order of the edges?
I try to create subgraph = G.subgraph(path) but this returns me an incorrect order of the edges which later returns me an incorrect order of the edge attributes when I use nx.get_edge_attribute(subgrap... | [
"Using subgraph on a path does not guarantee that the edges will be returned in the same order as along the path.\nInstead of creating subgraphs, it's possible to get the edge attributes directly from the original graph:\nfor s, d in zip(path, path[1:]):\n print(s,d, G[s][d][0]['relation'])\n\n# P0 P1 friend\n# ... | [
0
] | [] | [] | [
"dictionary",
"networkx",
"python"
] | stackoverflow_0074553711_dictionary_networkx_python.txt |
Q:
What is the "if __name__ == '__main__'" block called?
I saw someone on a Python post refer to it in some way, but I cannot for the life of me find it again.
It was a pretty short, colloquial term, something like "gutter" or "blunk".
Is it a Python thing or do other languages call it something too?
A:
In the docu... | What is the "if __name__ == '__main__'" block called? | I saw someone on a Python post refer to it in some way, but I cannot for the life of me find it again.
It was a pretty short, colloquial term, something like "gutter" or "blunk".
Is it a Python thing or do other languages call it something too?
| [
"In the documentation up to Python 3.3 it's referred to as a \"conditional script\" stanza:\n\nIt is this environment in which the idiomatic “conditional script” stanza causes a script to run:\nif __name__ == \"__main__\":\n main()\n\n\nThis term is gone since 3.4:\n\na common idiom for conditionally executing c... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0074558528_python.txt |
Q:
When should I use dataclasses in Python?
This is what it says in the document:
This module provides a decorator and functions for automatically adding generated special methods such as __init__() and __repr__() to user-defined classes.
Accordingly, I can use dataclass in every class, but should I really use ?
I ... | When should I use dataclasses in Python? | This is what it says in the document:
This module provides a decorator and functions for automatically adding generated special methods such as __init__() and __repr__() to user-defined classes.
Accordingly, I can use dataclass in every class, but should I really use ?
I really don't understand when should I use it, ... | [
"To me, dataclasses are best for simple objects (sometimes called value objects) that have no logic to them, just data. For example:\n@dataclass\nclass StockItem:\n sku: str\n name: str\n quantity: int\n\nThis then benefits from not having to implement init, which is nice because it would be trivial. It al... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074558619_python.txt |
Q:
Calculate result without entering python shell
Is it possible to calculate an expression using python but without entering python shell? What I want to achieve is to use python in a following manner:
tail file.txt -n `python 123*456`
instead of having to calculate 123*456 in a separate step.
A:
I don't understa... | Calculate result without entering python shell | Is it possible to calculate an expression using python but without entering python shell? What I want to achieve is to use python in a following manner:
tail file.txt -n `python 123*456`
instead of having to calculate 123*456 in a separate step.
| [
"I don't understand your question: you say \"I would like to do something using Python\", but when you show what you want to do, Python seems not to be needed for achieving that.\nLet me show you: what you want to achieve, can be done as follows:\ntail -f file.txt -n $((123*456))\n\nThe $((...)) notation is capable... | [
3,
1
] | [] | [] | [
"linux",
"python",
"shell"
] | stackoverflow_0074558107_linux_python_shell.txt |
Q:
Print some of list by for in python
I have 4 lists and I want to print them, but it returns name of list.
list1 = ["a", "b", "c", "d"]
list2 = ["a", "b", "c"]
list3 = ["a", "b"]
list4 = ["a"]
for i in range(1,5):
print(list[i])
It shows:
list[1]
list[2]
list[3]
list[4]
I need, for example ["a", "b", "c", "d... | Print some of list by for in python | I have 4 lists and I want to print them, but it returns name of list.
list1 = ["a", "b", "c", "d"]
list2 = ["a", "b", "c"]
list3 = ["a", "b"]
list4 = ["a"]
for i in range(1,5):
print(list[i])
It shows:
list[1]
list[2]
list[3]
list[4]
I need, for example ["a", "b", "c", "d"] for list1.
| [
"You could make a list of lists if you want to print them like you are trying to do:\nlist1 = [\n [\"a\", \"b\", \"c\", \"d\"],\n [\"a\", \"b\", \"c\"],\n [\"a\", \"b\"],\n [\"a\"]\n]\n\nfor i in range(len(list1)):\n print(list1[i])\n\n",
"Variables don't work that way. If you need a similar kind o... | [
0,
0,
0
] | [] | [] | [
"for_loop",
"list",
"python"
] | stackoverflow_0074558443_for_loop_list_python.txt |
Q:
How to get uploaded file in views?
I'm trying to get uploaded data in my views. Firstly, I'm getting the path and after that I have to read the file but Django gives me an error
FileNotFoundError: [Errno 2] No such file or directory:
'/Users/edc/PycharmProjects/wl/SM/uploads/meetings notes (1).docx
but I have th... | How to get uploaded file in views? | I'm trying to get uploaded data in my views. Firstly, I'm getting the path and after that I have to read the file but Django gives me an error
FileNotFoundError: [Errno 2] No such file or directory:
'/Users/edc/PycharmProjects/wl/SM/uploads/meetings notes (1).docx
but I have that file. How can I fix that?
upload = Up... | [
"If you check your file path in error it's invalid if it's uploaded inside media directory.\n'/Users/edc/PycharmProjects/wl/SM/uploads/meetings notes (1).docx'\n\nJust change your code like this:\nimport os\nfrom django.conf import settings\n\n\nupload = Upload(file=f)\nfile_path = os.path.join(settings.MEDIA_ROOT,... | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074558552_django_python.txt |
Q:
Using Flask-SQLAlchemy without Flask
I had a small web service built using Flask and Flask-SQLAlchemy that only held one model. I now want to use the same database, but with a command line app, so I'd like to drop the Flask dependency.
My model looks like this:
class IPEntry(db.Model):
id = db.Column(db.Integ... | Using Flask-SQLAlchemy without Flask | I had a small web service built using Flask and Flask-SQLAlchemy that only held one model. I now want to use the same database, but with a command line app, so I'd like to drop the Flask dependency.
My model looks like this:
class IPEntry(db.Model):
id = db.Column(db.Integer, primary_key=True)
ip_address = db.... | [
"you can do this to replace db.Model:\nfrom sqlalchemy import orm\nfrom sqlalchemy.ext.declarative import declarative_base\nimport sqlalchemy as sa\n\nbase = declarative_base()\nengine = sa.create_engine(YOUR_DB_URI)\nbase.metadata.bind = engine\nsession = orm.scoped_session(orm.sessionmaker())(bind=engine)\n\n# af... | [
11,
4,
3,
1,
1,
0,
0,
0
] | [] | [] | [
"flask_sqlalchemy",
"python",
"sqlalchemy"
] | stackoverflow_0030115010_flask_sqlalchemy_python_sqlalchemy.txt |
Q:
Calculate cumulative ocupation from variable by date ranges (summation)
Let it be the following python pandas DataFrame where each row represents a person's stay in a hotel.
| entry_date | exit_date | days | other_columns |
| ---------- | ---------- | ------ | ------------- |
| 2022-02-01 | 2022-02-05 | 5 ... | Calculate cumulative ocupation from variable by date ranges (summation) | Let it be the following python pandas DataFrame where each row represents a person's stay in a hotel.
| entry_date | exit_date | days | other_columns |
| ---------- | ---------- | ------ | ------------- |
| 2022-02-01 | 2022-02-05 | 5 | ... |
| 2022-02-02 | 2022-02-03 | 2 | ... |
| 2022... | [
"You can use date_range and value_counts:\n# ensure datetime\n# for year-day-month\ndf[['entry_date', 'exit_date']] = df[['entry_date', 'exit_date']].apply(pd.to_datetime, dayfirst=True)\n# for year-month-day\ndf[['entry_date', 'exit_date']] = df[['entry_date', 'exit_date']].apply(pd.to_datetime, dayfirst=False)\n\... | [
4,
3
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074558578_dataframe_pandas_python.txt |
Q:
GCP Dataflow Kafka and missing SSL certificates
I'm trying to fetch the data from Kafka to Bigquery using GCP Dataflow.
My Dataflow template is based on Python SDK 2.42 + Container registry + apache_beam.io.kafka.
There is my pipeline:
def run(
bq_dataset,
bq_table_name,
project,
pi... | GCP Dataflow Kafka and missing SSL certificates | I'm trying to fetch the data from Kafka to Bigquery using GCP Dataflow.
My Dataflow template is based on Python SDK 2.42 + Container registry + apache_beam.io.kafka.
There is my pipeline:
def run(
bq_dataset,
bq_table_name,
project,
pipeline_options
):
with Pipeline(options=... | [
"I found the solution. You should ingest certificates into Java SDK, not into Python. So, I created one more docker image but based on Java SDK:\nFROM openjdk:11\n\nCOPY --from=apache/beam_java11_sdk:2.42.0 /opt/apache/beam /opt/apache/beam\n\nCOPY ./ca.txt /usr/src/ca.txt\nCOPY ./cert.txt /usr/src/cert.txt\nCOPY .... | [
0
] | [] | [] | [
"apache_kafka",
"google_cloud_dataflow",
"google_cloud_platform",
"python",
"ssl"
] | stackoverflow_0074335221_apache_kafka_google_cloud_dataflow_google_cloud_platform_python_ssl.txt |
Q:
Flask-SQLalchemy AttributeError: 'NoneType' object has no attribute ""
I am trying to query couple of tables , and using for loops I am adding filters to queries.
new_list = []
query = {
"search_word": "Home",
"exact": False,
"tags": ["N"],
"next_words": [
{"pos": 1, "tags": ["verb"]},
... | Flask-SQLalchemy AttributeError: 'NoneType' object has no attribute "" | I am trying to query couple of tables , and using for loops I am adding filters to queries.
new_list = []
query = {
"search_word": "Home",
"exact": False,
"tags": ["N"],
"next_words": [
{"pos": 1, "tags": ["verb"]},
{"pos": 2, "tags": ["anim"]}
]
}
if query["search_word"]:
if qu... | [
"The problem was in :\nfor words in query[\"next_words\"]:\n tagging = words['tags'] # list of values\n for rg in tagging:\n db_query = db_query.filter(Cases.pos.contains(rg))\n\nThis query was returning Empty Object for a reason, Queries done here was wrong.\n"
] | [
0
] | [] | [] | [
"attributeerror",
"flask_sqlalchemy",
"non_type",
"python",
"sqlalchemy"
] | stackoverflow_0074551733_attributeerror_flask_sqlalchemy_non_type_python_sqlalchemy.txt |
Q:
Python date string conversion fail
I am trying to convert the following string '1.12.22 14:16UTC+01:00' in Pandas to December 1st 2022
my_date = '1.12.22 14:16UTC+01:00'
new_date = pd.to_datetime(my_date)
Timestamp('2022-01-12 14:16:00-0100', tz='pytz.FixedOffset(-60)')
It inverts month with day only in specific ... | Python date string conversion fail | I am trying to convert the following string '1.12.22 14:16UTC+01:00' in Pandas to December 1st 2022
my_date = '1.12.22 14:16UTC+01:00'
new_date = pd.to_datetime(my_date)
Timestamp('2022-01-12 14:16:00-0100', tz='pytz.FixedOffset(-60)')
It inverts month with day only in specific cases. I am trying to use format="%d.%m.... | [
">>> pd.to_datetime('01.12.22 14:16UTC', format='%d.%m.%y %H:%M%Z')\nTimestamp('2022-12-01 14:16:00+0000', tz='UTC')\n\nI am not sure if this is what you are looking for, but your placeholders are wrong, check this page to know what they stand for.\n",
"have you tried adding a zero?\nmy_date = '01.12.22 14:16UTC+... | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0074558762_python.txt |
Q:
Scatterplots using csv files
I want to create a 3-D scatterplot using only two variables of the csv file, I tried plotting a simple 2-D one and I keep getting a KeyError. How can I fix my problem.
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("C:/Users/theet/Desktop/ITMLA/Assignment/merka_a... | Scatterplots using csv files | I want to create a 3-D scatterplot using only two variables of the csv file, I tried plotting a simple 2-D one and I keep getting a KeyError. How can I fix my problem.
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("C:/Users/theet/Desktop/ITMLA/Assignment/merka_agri_corn_experiment.csv")
df[:]
x... | [
"You're trying to find the key \"fertilizr addition\", which looks like a spelling mistake - I'm assuming you meant \"fertilizer addition\" which is why it's saying the key doesn't exist.\nAlso, please post your code in your question.\n"
] | [
0
] | [] | [] | [
"jupyter_notebook",
"python"
] | stackoverflow_0074558698_jupyter_notebook_python.txt |
Q:
Python + Selenium WebDriver, work with Pseudo-elements
Please help. I need to activate the checkbox, but I don't understand how to refer to this pseudo-element ::before.
Please, check this image
enter image description here
The checkbox should look like this, so you can go to the next page
enter image description ... | Python + Selenium WebDriver, work with Pseudo-elements | Please help. I need to activate the checkbox, but I don't understand how to refer to this pseudo-element ::before.
Please, check this image
enter image description here
The checkbox should look like this, so you can go to the next page
enter image description here
The item is there, but I don't know how to activate the... | [
"You do not need to access that pseudo element. Try clicking the label element there.\nAlso you have to improve your locators. Absolute locators are extremely breakable.\n"
] | [
0
] | [] | [] | [
"python",
"selenium",
"selenium_webdriver"
] | stackoverflow_0074558803_python_selenium_selenium_webdriver.txt |
Q:
Python benchmark: Why for in loop is faster than simple while?
I was trying to optimize simple character counting function. After few changes I decided to check the timings and expected the function using basic 'while' loop to be faster than 'for in' loop.
But to my surprise while loop was almost 30% slower than ... | Python benchmark: Why for in loop is faster than simple while? | I was trying to optimize simple character counting function. After few changes I decided to check the timings and expected the function using basic 'while' loop to be faster than 'for in' loop.
But to my surprise while loop was almost 30% slower than for in here! Shouldn't be simple 'while' loop which has lower abstra... | [
"While Loop\nWell in your while loop the interpreter has to check every iteration whether your expression is true therefore it has to access both elements i and size and compare them.\nFor Loop\nThe for loop on the other hand has no need for that since the for loop is optimized as Chris_Rands already pointed out\n"... | [
0,
0,
0
] | [] | [] | [
"benchmarking",
"performance",
"python"
] | stackoverflow_0053812334_benchmarking_performance_python.txt |
Q:
How to add a QVideoWidget in Qt Designer?
I want to insert video in blue box(ui image) but I don't know how to insert video file.
My code is here.
I don't know how to add video... Just know example that make video player ...
import sys
from PyQt5 import QtWidgets
from PyQt5 import QtGui
from PyQt5 import uic
fro... | How to add a QVideoWidget in Qt Designer? | I want to insert video in blue box(ui image) but I don't know how to insert video file.
My code is here.
I don't know how to add video... Just know example that make video player ...
import sys
from PyQt5 import QtWidgets
from PyQt5 import QtGui
from PyQt5 import uic
from PyQt5 import QtCore
from PyQt5.QtCore import ... | [
"Qt Designer does not show all the Qt widget, and often we want to add our own widget through Qt, for that there are at least 2 solutions, the first is to create a plugin and load it to Qt Designer, and the other is simpler. promote the widget, the latter is what I will show in this answer.\nFor this you must make ... | [
24,
0,
0
] | [] | [] | [
"pyqt",
"pyqt5",
"python",
"qt_designer",
"qvideowidget"
] | stackoverflow_0047259825_pyqt_pyqt5_python_qt_designer_qvideowidget.txt |
Q:
How to add python panel date range slider on_change event?
I am trying to use a dateRangeSlider to pick start and end dates and plot the graph accordingly using plotly in python.
Here, whenever I change the slider, how can I know that slider is updated (return currently selected date-range as tuple) and I need to ... | How to add python panel date range slider on_change event? | I am trying to use a dateRangeSlider to pick start and end dates and plot the graph accordingly using plotly in python.
Here, whenever I change the slider, how can I know that slider is updated (return currently selected date-range as tuple) and I need to update the plot X and Y axis ranges? Is there any event handler ... | [
"Please use ipywidgets instead of panel, it is easier and more powerful:\nimport datetime as dt\nimport pandas as pd\nimport yfinance as yf\nimport plotly.graph_objs as go\nfrom ipywidgets import interact\nfrom ipywidgets import widgets\n\n\n# Data part\nvix_tickers = ['AUDJPY=X']\n\ndf = yf.download(vix_tickers,\n... | [
1
] | [] | [] | [
"panel",
"plotly",
"python",
"python_3.x"
] | stackoverflow_0074557353_panel_plotly_python_python_3.x.txt |
Q:
How to delete class object in python
TypeError: 'employee' object cannot be interpreted as an integer
I AM GETTING THIS TYPE OF ERROR
name = input("Enter name you want to delete : ")
for i in lst:
if name in i.name:
lst.pop(i)
print("Employee deleted!")
I was expecting that the... | How to delete class object in python | TypeError: 'employee' object cannot be interpreted as an integer
I AM GETTING THIS TYPE OF ERROR
name = input("Enter name you want to delete : ")
for i in lst:
if name in i.name:
lst.pop(i)
print("Employee deleted!")
I was expecting that the object would get deleted But it Showing t... | [
"From python documentation the method list.pop except an integer as parameter with give the position of the element to remove in the list.\nFrom your code, the list lst seems to contain objects of the employee class and this isn't an integer. For your case, the list.remove function will be the one to use since it w... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074558820_python.txt |
Q:
Is there any way I can download the pre-trained models available in PyTorch to a specific path?
I am referring to the models that can be found here: https://pytorch.org/docs/stable/torchvision/models.html#torchvision-models
A:
As, @dennlinger mentioned in his answer : torch.utils.model_zoo, is being internally ... | Is there any way I can download the pre-trained models available in PyTorch to a specific path? | I am referring to the models that can be found here: https://pytorch.org/docs/stable/torchvision/models.html#torchvision-models
| [
"As, @dennlinger mentioned in his answer : torch.utils.model_zoo, is being internally called when you load a pre-trained model.\nMore specifically, the method: torch.utils.model_zoo.load_url() is being called every time a pre-trained model is loaded. The documentation for the same, mentions:\n\nThe default value of... | [
31,
8,
0
] | [
"TL;DR: No, it is not possible directly, but you can easily adapt it.\nI think what you want to do is to look at torch.utils.model_zoo, which is internally called when you load a pre-trained model:\nIf we look at the code for the pre-trained models, for example AlexNet here, we can see that it simply calls the prev... | [
-1
] | [
"deep_learning",
"pre_trained_model",
"python",
"pytorch",
"torchvision"
] | stackoverflow_0052628270_deep_learning_pre_trained_model_python_pytorch_torchvision.txt |
Q:
OpenGL Canvas. how to move an object inside a canvas
I want to move the following red cross in the canvas with the mouse events. it should only move when we click on it and drag it with the move. it should stop moving when we release the mouse.
I do get the events of the mouse. but I don't know how i can detect th... | OpenGL Canvas. how to move an object inside a canvas | I want to move the following red cross in the canvas with the mouse events. it should only move when we click on it and drag it with the move. it should stop moving when we release the mouse.
I do get the events of the mouse. but I don't know how i can detect that I clicked on the object to make it move.
also for examp... | [
"i found the solution for the ones who are interested.\nself.plot1.set_data(pos=...)\nwith this method we can move it easily\n"
] | [
0
] | [] | [] | [
"pyqt",
"pyside",
"python",
"vispy"
] | stackoverflow_0074557847_pyqt_pyside_python_vispy.txt |
Q:
AttributeError: 'NoneType' object has no attribute 'list_middleware' in masonite\routes\Route.py", line 166
Upon running python craft migration create_a_table --create a_table I received the following traceback:
Traceback (most recent call last):
File "SOMEPATH\craft", line 8, in <module>
from wsgi import ap... | AttributeError: 'NoneType' object has no attribute 'list_middleware' in masonite\routes\Route.py", line 166 | Upon running python craft migration create_a_table --create a_table I received the following traceback:
Traceback (most recent call last):
File "SOMEPATH\craft", line 8, in <module>
from wsgi import application
File "SOMEPATH\wsgi.py", line 11, in <module>
application.register_providers(Kernel, ApplicationK... | [
"It turns out that one of the dependencies I had somewhere had a missing dependency. I found out that the load function called in Kernel.register_routes silenced a ModuleNotFoundError. For some reason this error didn't get silenced in a fresh project that also was missing a dependency of a module. I am guessing tha... | [
0
] | [] | [] | [
"masonite",
"python"
] | stackoverflow_0074559042_masonite_python.txt |
Q:
I was using Python and If statement won't write ( < ) and keep writing ( > ) whether they are true or not
print("Welcome to Agurds. Before we begin can you tell me your name?")
Name = input("name: ")
print("Hello " + Name + " When were you born " + Name + "?")
year = int(input("Born year:"))
age = str(2022 - year)... | I was using Python and If statement won't write ( < ) and keep writing ( > ) whether they are true or not | print("Welcome to Agurds. Before we begin can you tell me your name?")
Name = input("name: ")
print("Hello " + Name + " When were you born " + Name + "?")
year = int(input("Born year:"))
age = str(2022 - year)
print("You must be " + age + " this year.")
if age < str(18):
print("You're too young to be here. Exiting ... | [
"When comparing two values to find the smallest, use int rather than str, such as using if age < 18 rather than if age < str(18). You problem was that it was comparing the string Pens rather than the int Pens\nprint(\"Welcome to Agurds. Before we begin can you tell me your name?\")\nName = input(\"name: \")\nprint(... | [
0,
0
] | [] | [] | [
"function",
"if_statement",
"project",
"python",
"windows"
] | stackoverflow_0074557176_function_if_statement_project_python_windows.txt |
Q:
Plotly: Create a Scatter with categorical x-axis jitter and multi level axis
I would like to make a graph with a multi-level x axis like in the following picture:
import plotly.graph_objects as go
fig = go.Figure()
fig.add_trace(
go.Scatter(
x = [df['x'], df['x1']],
y = df['y'],
mode='markers'
)
)... | Plotly: Create a Scatter with categorical x-axis jitter and multi level axis | I would like to make a graph with a multi-level x axis like in the following picture:
import plotly.graph_objects as go
fig = go.Figure()
fig.add_trace(
go.Scatter(
x = [df['x'], df['x1']],
y = df['y'],
mode='markers'
)
)
But also I would like to put jitter on the x-axis like in the next picture:
So ... | [
"Firstly - thanks for the challenge! There aren't many challenging Plotly questions these days.\nThe key elements to creating a scatter graph with jitter are:\n\nUsing mode: 'box' - to create a box-plot, not a scatter plot.\nSetting 'boxpoints': 'all' - so all points are plotted.\nUsing 'pointpos': 0 - to center th... | [
14,
1,
0
] | [] | [] | [
"graph",
"jitter",
"plotly",
"python",
"scatter_plot"
] | stackoverflow_0065044430_graph_jitter_plotly_python_scatter_plot.txt |
Q:
How to scrape only one price?
I'm trying to scrape product prices from a website and both real price and the monthly payment quota value has exactly the same class, so I can't figure it out how to only get main price.
and this is for the main price: "879.990"
this is for the monthly payment quota: "39.990",
this ... | How to scrape only one price? | I'm trying to scrape product prices from a website and both real price and the monthly payment quota value has exactly the same class, so I can't figure it out how to only get main price.
and this is for the main price: "879.990"
this is for the monthly payment quota: "39.990",
this is the URL: https://listado.mercado... | [
"You can filter out the other prices using CSS selectors\n# filsel = 'span.price-tag-fraction:not(span.ui-search-installments span):not(s.price-tag__disabled span)'\nemiSp_sel = 'span.ui-search-installments span' # monthly\ndisab_sel = 's.price-tag__disabled span' # crossed out\nfilsel = f'span.price-tag-fraction:n... | [
0
] | [] | [] | [
"beautifulsoup",
"jupyter_notebook",
"python"
] | stackoverflow_0074540266_beautifulsoup_jupyter_notebook_python.txt |
Q:
discord.py based bot doesn't work after 2.0 update
So I was used to use this bot about one year ago, now I wanted to launch it again but after discord.py 2.0 update it seems doesn't work propery
import discord
from keep_alive import keep_alive
class MyClient(discord.Client):
async def on_ready(self):
... | discord.py based bot doesn't work after 2.0 update | So I was used to use this bot about one year ago, now I wanted to launch it again but after discord.py 2.0 update it seems doesn't work propery
import discord
from keep_alive import keep_alive
class MyClient(discord.Client):
async def on_ready(self):
print('bot is online now', self.user)
async def on_... | [
"If it would be a syntax mistake you'd get a syntax error. The real issue is that you didn't enable the message_content intent, so you can't read the content of messages. Intents.default() doesn't include privileged intents.\nintents = discord.Intents.default()\nintents.message_content = True\n\nDon't forget to ena... | [
2
] | [
"Your code should be:\nimport discord\nfrom discord.ext import commands # you need to import this to be able to use commands and events\nfrom keep_alive import keep_alive\nclient = commands.Bot(intents=discord.Intents.default())\n\n@bot.event\nasync def on_ready(): # you don't need self in here\n print('bot is o... | [
-2
] | [
"discord.py",
"python"
] | stackoverflow_0074557378_discord.py_python.txt |
Q:
Get the count of Text, Numeric/Float, Blank and Nan values for each column in a Dataframe and extract using a filter
Assume the table below
Index
Col1
Col2
Col3
0
10.5
2.5
nan
1
s
2
2.9
3.2
a
3
#VAL
nan
2
4
3
5.6
4
Now what I'm trying to get is a summary dataframe which will give me a count of different da... | Get the count of Text, Numeric/Float, Blank and Nan values for each column in a Dataframe and extract using a filter | Assume the table below
Index
Col1
Col2
Col3
0
10.5
2.5
nan
1
s
2
2.9
3.2
a
3
#VAL
nan
2
4
3
5.6
4
Now what I'm trying to get is a summary dataframe which will give me a count of different datatypes/conditions as mentioned above
Index
Col1
Col2
Col3
Integer/Float
3
3
2
Blank
1
0
1
Nan
0... | [
"Use custom funstion for count each type separately:\ndef f(x):\n a = pd.to_numeric(x, errors='coerce').notna().sum()\n b = x.eq('').sum()\n c = x.isna().sum()\n d = len(x) - (a + b + c)\n return pd.Series([a,b,c,d], ['Integer/Float','Blank','Nan','Text'])\n\ndf = df.apply(f)\nprint (df)\n ... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074559093_dataframe_pandas_python.txt |
Q:
Why does the last letter doesn't add up where it belongs?
i am pretty new to coding in python and we have some programs to make for class.
The program needs to split without slicing or other functions the first part of a digit -> 12.5 becomes 12 and 5. I have so managed to make this which works only for the first ... | Why does the last letter doesn't add up where it belongs? | i am pretty new to coding in python and we have some programs to make for class.
The program needs to split without slicing or other functions the first part of a digit -> 12.5 becomes 12 and 5. I have so managed to make this which works only for the first part and then the last digit doesn't add up where it belongs. C... | [
"Try this?\ndef decoupage(word: str) -> tuple(str, str):\n entire_part = ''\n decimal_part = ''\n delimiters = [',','.']\n\n after = False # let's use a boolean to check if we are before or after the delimiter\n for letter in word:\n if not after: # if we are before\n after = letter... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074558957_python.txt |
Q:
Can anyone help me find out where I made a mistake?
I am trying to figure out how to print a requested amount of prime numbers but I am having problems.
I can't describe what I did so I'll just paste my code so far:
requested_primes = 3 #just for simplicity, i am going to request an input for how many prime intege... | Can anyone help me find out where I made a mistake? | I am trying to figure out how to print a requested amount of prime numbers but I am having problems.
I can't describe what I did so I'll just paste my code so far:
requested_primes = 3 #just for simplicity, i am going to request an input for how many prime integers they #want printed
found_primes = 0
examined_number =... | [
"Your for loop never runs due to i having the same starting value as examined_number (both are 2).\nTry using for in in range(1, examined_number) and that should get your loop to execute - you can verify it is running by adding a few print statements\n",
"There are 2 problems, both of which can potentially cause ... | [
0,
0
] | [] | [] | [
"loops",
"primes",
"python"
] | stackoverflow_0074559088_loops_primes_python.txt |
Q:
How do I change a variable's value with the command from a Tkinter button?
The command I set for a Tkinter button was a function that changed the text of a label. Yet the text does not seem to change!
The variable I attempted to change using the function "textChange()" is called "text", and the purpose of its valu... | How do I change a variable's value with the command from a Tkinter button? | The command I set for a Tkinter button was a function that changed the text of a label. Yet the text does not seem to change!
The variable I attempted to change using the function "textChange()" is called "text", and the purpose of its value is to be the text of a label called "finalText". But, the text of the label "f... | [
"You actually create a new label and assign to a local variable finalText inside textChange(). So the global finalText is not changed.\nYou need to use finalText.config(text=text) to update the text of the global finalText.\nAlso command=(textChange()) will execute textChange() immediately without clicking the but... | [
1
] | [] | [] | [
"button",
"command",
"label",
"python",
"tkinter"
] | stackoverflow_0074559149_button_command_label_python_tkinter.txt |
Q:
Extract very nested string-text between tags?
I'm trying to make list of minerals+prices. I Succeed at making first step (it shows list of minerals from 1st page), but I can't reach for Price values. I've tried with some other methods I've found on StackOverflow (with siblings/parents tags etc.) but I didn't succ... | Extract very nested string-text between tags? | I'm trying to make list of minerals+prices. I Succeed at making first step (it shows list of minerals from 1st page), but I can't reach for Price values. I've tried with some other methods I've found on StackOverflow (with siblings/parents tags etc.) but I didn't succeed... Also, can you later attach/add one list to an... | [
"Try this:\nimport requests\nfrom bs4 import BeautifulSoup\n\nURL = \"https://www.fabreminerals.com/search_results.php?LANG=EN&SearchTerms=&submit=Buscar&MineralSpeciment=&Country=&Locality=&PriceRange=&checkbox=enventa&First=0\"\n\nheaders = {\n \"User-Agent\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) ... | [
1
] | [] | [] | [
"beautifulsoup",
"html",
"python",
"web_scraping"
] | stackoverflow_0074559233_beautifulsoup_html_python_web_scraping.txt |
Q:
The same python binary in two different terminals sees a different environment
I tried to run a jupyter notebook cell in vscode today and got
"Running cells with 'Python 3.10.6 64-bit' requires ipykernel package".
This is very strange, as my Jupiter laptop environment was still working yesterday. Also, I see all ... | The same python binary in two different terminals sees a different environment | I tried to run a jupyter notebook cell in vscode today and got
"Running cells with 'Python 3.10.6 64-bit' requires ipykernel package".
This is very strange, as my Jupiter laptop environment was still working yesterday. Also, I see all the python packages in their place. The only thing that has changed is that last nig... | [
"Solution is to reinstall vscode with deb package from official website. See the edited part of the question.\n"
] | [
1
] | [] | [] | [
"gcc",
"python",
"visual_studio_code"
] | stackoverflow_0074545965_gcc_python_visual_studio_code.txt |
Q:
How to integrate a cursor in a QtWidgets app
I am new to QtWidgets and trying to build an app in QtWidgets and Python (3.x). the end goal of the app is to show images and a
superposed cursor (to be exact, a "plus" sign of 2cm) that can be moved along the image reacting to mouse events. I concentrate now first on t... | How to integrate a cursor in a QtWidgets app | I am new to QtWidgets and trying to build an app in QtWidgets and Python (3.x). the end goal of the app is to show images and a
superposed cursor (to be exact, a "plus" sign of 2cm) that can be moved along the image reacting to mouse events. I concentrate now first on this cursor. So far, I read examples on how to do i... | [
"You can use the QApplication.setOverrideCursor method to assign a .png image file as your cursor when it appears inside of the Qt program.\nHere is an example that is mostly based on the code in your question. And below is a gif that demonstrates the example. And the last image is the image I used in the code as ... | [
0
] | [] | [] | [
"matplotlib",
"pyside2",
"python",
"qtwidgets"
] | stackoverflow_0074490415_matplotlib_pyside2_python_qtwidgets.txt |
Q:
TypeError: 'type' object is not subscriptable, error when creating an trading bot with python
I am creating a trading bot. I have 2 files a settings.json file and a main.py file.
my settings.json file :
`{
"username": "51410030",
"password": "s5p3GI1zY",
"server": "Alpari-MT5-Demo",
"mt5Pathway": "... | TypeError: 'type' object is not subscriptable, error when creating an trading bot with python | I am creating a trading bot. I have 2 files a settings.json file and a main.py file.
my settings.json file :
`{
"username": "51410030",
"password": "s5p3GI1zY",
"server": "Alpari-MT5-Demo",
"mt5Pathway": "C://Program Files/Alpari MT5/terminal64.exe",
"symbols": ["USDJPY.a"],
"timeframe": "M30"
}... | [
"There are a few issues with your code:\n\nYou're trying to access fields in a list. That's not possible, you should keep your list a dictionary if you want access its fields.\n\nYou're returning an ImportError, if you want to raise an error, use raise ImportError(\"Your error message\"). Or if you want to catch th... | [
0
] | [] | [] | [
"json",
"metatrader5",
"python",
"trading"
] | stackoverflow_0074559282_json_metatrader5_python_trading.txt |
Q:
VS Code not detecting package in conda environment
I used conda install -c Quantopian zipline to install the zipline package in a new conda environment. I activated the conda environment from within VS Code and my settings.json reads as follows:
{
"python.pythonPath": "C:\\Anaconda3\\envs\\zipline\\python.exe"... | VS Code not detecting package in conda environment | I used conda install -c Quantopian zipline to install the zipline package in a new conda environment. I activated the conda environment from within VS Code and my settings.json reads as follows:
{
"python.pythonPath": "C:\\Anaconda3\\envs\\zipline\\python.exe"
}
The bottom bar in my VS Code shows that the 'zipline... | [
"As i can see you are using conda environment, you need to specify pythonPath of that specific conda environment instead of Base Conda path.\nIn your case its 'zipline' so in Command Palette, search for your conda environment and select it as pythonPath. Refer below image:\nYse the Python: Select Interpreter comman... | [
1,
0,
0
] | [] | [] | [
"conda",
"python",
"visual_studio_code",
"zipline"
] | stackoverflow_0063484377_conda_python_visual_studio_code_zipline.txt |
Q:
Quasi Random Number generation Scatter plot
Require python code for Quasi random number generation scatter plot. Tried this method but getting name not found error as shown below
[code](https://i.stack.imgur.com/Eg5og.png)
[code](https://i.stack.imgur.com/2a6o8.png)
[error](https://i.stack.imgur.com/... | Quasi Random Number generation Scatter plot | Require python code for Quasi random number generation scatter plot. Tried this method but getting name not found error as shown below
[code](https://i.stack.imgur.com/Eg5og.png)
[code](https://i.stack.imgur.com/2a6o8.png)
[error](https://i.stack.imgur.com/j2O04.png)
I tries to obtain quasi random number ... | [
"I can't find any examples on this site of plotting the output of Scipy's Quasi Monte-Carlo generators, so here's one that replicates the first plot of Wikipedia's entry on the Sobol sequence:\n# import generators from SciPy\nfrom scipy.stats import qmc\nimport matplotlib.pyplot as plt\n\n# create 2D Sobol sequence... | [
0
] | [] | [] | [
"cython",
"python",
"random"
] | stackoverflow_0074554924_cython_python_random.txt |
Q:
How to compact a dataset with empty rows in Python?
I have a data set formatted as follows:
sha
0_x
1_x
N_x
Sha1
rm
rm
Sha2
rw
rw
Sha3
rw
Sha4
tr
In particular, the dataset currently contains about 2000 columns.
I want to reduce the number of columns removing as many as possible the empty rows, as follow... | How to compact a dataset with empty rows in Python? | I have a data set formatted as follows:
sha
0_x
1_x
N_x
Sha1
rm
rm
Sha2
rw
rw
Sha3
rw
Sha4
tr
In particular, the dataset currently contains about 2000 columns.
I want to reduce the number of columns removing as many as possible the empty rows, as follows:
sha
0_x
1_x
Sha1
rm
rm
Sha2
rw... | [
"Assuming empty cells are NaN, if not, first replace('', np.nan).\nYou can stack and pivot:\ncols = df.columns[1:]\n# ['0_x', '1_x', 'N_x']\n\n(df.set_index('sha')\n .stack()\n .reset_index()\n .assign(cols=lambda d: d.groupby('sha')\n .cumcount()\n .map(dic... | [
2,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074558800_dataframe_pandas_python.txt |
Q:
Drawing Arabic Characters to bitmap
i have been trying to print arabic characters using SPRT thermal printer with the python-escpos package, but i cant seem to find any solution at all, so i decided to draw the arabic characters to a bitmap and then print it. But that also doesn't work..
this is the code used for ... | Drawing Arabic Characters to bitmap | i have been trying to print arabic characters using SPRT thermal printer with the python-escpos package, but i cant seem to find any solution at all, so i decided to draw the arabic characters to a bitmap and then print it. But that also doesn't work..
this is the code used for converting the text to bitmap:
`
from PIL... | [
"In this case you need to use a particular font.\nfrom PIL import Image, ImageFont, ImageDraw\n\nimage = Image.new(\"RGB\",[320,320])\ndraw = ImageDraw.Draw(image)\na = 'محمد'\nfont = ImageFont.truetype(\"arial-unicode-ms.ttf\", 14)\ndraw.text((50, 50), a, font=font)\nimage.save(\"image.png\")\n\n"
] | [
0
] | [] | [] | [
"escpos",
"python",
"thermal_printer"
] | stackoverflow_0074559180_escpos_python_thermal_printer.txt |
Q:
How to share the x axis in reverse between two subplots in matplotlib?
I want to show two different anatomical views of a subject, front and back, and I want the coordinates to be consistent between both while also showing them as you would naturally see them. This means that the X axis should increase to the righ... | How to share the x axis in reverse between two subplots in matplotlib? | I want to show two different anatomical views of a subject, front and back, and I want the coordinates to be consistent between both while also showing them as you would naturally see them. This means that the X axis should increase to the right in the front view and to the left in the back view.
I want the navigation ... | [
"Well, it does not look like there is a specific functionality already implemented for what I'm trying to achieve, so after a bit of tinkering this is the simplest that I was able to come up with.\nI am integrating this into a Qt application and I had already modified the navigation toolbar to hide some actions and... | [
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0074548808_matplotlib_python.txt |
Q:
Python Pandas Dataframe manipulation (Excel File)
I'm fairly new to Python and I have a issue with dataframe manipulation using EXCEL:
This is a snippet of the excel:
I was able to drop the duplicates for datetime rows, and get a dataframe with only the datatime rows and another with only the descriptions;
I was ... | Python Pandas Dataframe manipulation (Excel File) | I'm fairly new to Python and I have a issue with dataframe manipulation using EXCEL:
This is a snippet of the excel:
I was able to drop the duplicates for datetime rows, and get a dataframe with only the datatime rows and another with only the descriptions;
I was able to drop the last row as well:
What I wanted to do... | [
"Here is a proposition using standard pandas frame's functions :\nimport pandas as pd\nimport numpy as np\n\ndef flag_delete(df):\n df.insert(0, \"temp_col\", df.groupby(\"Col_A\")[\"Col_A\"].transform(\"count\"))\n df.loc[df.pop(\"temp_col\").eq(1), df.columns!=\"Col_A\"] = \"DELETE\"\n return df\n\ndef ... | [
0
] | [] | [] | [
"dataframe",
"excel",
"pandas",
"python"
] | stackoverflow_0074559111_dataframe_excel_pandas_python.txt |
Q:
Reading parquet file in pandas
I am trying to read a parquet files to pandas
data=pd.read_parquet('MyFiles.parquet', engine='pyarrow')
but I am getting the following error
ArrowInvalid: Casting from timestamp[us] to timestamp[ns] would result in out of bounds timestamp: 253402214400000000
If I change the engine ... | Reading parquet file in pandas | I am trying to read a parquet files to pandas
data=pd.read_parquet('MyFiles.parquet', engine='pyarrow')
but I am getting the following error
ArrowInvalid: Casting from timestamp[us] to timestamp[ns] would result in out of bounds timestamp: 253402214400000000
If I change the engine type to fastparquet
data=pd.read_pa... | [
"Problem with the column which has timestamp in different timezone. You might need to download the parquet file first, and modify it before convert to pandas DataFrame.\nSome related issues: Parquet File datetime value mismatch\n"
] | [
0
] | [] | [] | [
"dataframe",
"pandas",
"parquet",
"python",
"python_3.x"
] | stackoverflow_0072405974_dataframe_pandas_parquet_python_python_3.x.txt |
Q:
How to call methods in a different class
Confused on OOP in Python3:
main.py:
import ma as m1
r = m1.ma1()
r.doit()
print(r.m1avar)
print(r.m2var)
r.m2do()
ma.py:
import mb as m2
class ma1(m2.mclass2):
m1avar = 10
def doit(self):
self.logout("doit!")
def logout(self, a):
... | How to call methods in a different class | Confused on OOP in Python3:
main.py:
import ma as m1
r = m1.ma1()
r.doit()
print(r.m1avar)
print(r.m2var)
r.m2do()
ma.py:
import mb as m2
class ma1(m2.mclass2):
m1avar = 10
def doit(self):
self.logout("doit!")
def logout(self, a):
print(a+" <--- this is correct")
mb.p... | [
"Try this - mclass2 does not see it's parent class as super, just as itself. So it's self. that you need not super.\nclass mclass2():\n \n m2var = 5;\n m1avar = 5;\n \n def doit(self):\n super().logout(\"m2 do it\")\n \n def m2do(self):\n self.logout(\"child class\")\n\n",
"The ... | [
1,
0
] | [] | [] | [
"oop",
"python"
] | stackoverflow_0074559113_oop_python.txt |
Q:
Discord.py command to play audio in a VC and command to leave VC using interactions/slash commands. NOT ctx or 'discord.ext commands'
I am wanting to make my own personal/private bot join the voice channel I am in and play audio files. I have it able to join the VC but I can't figure out how to make the bot leave ... | Discord.py command to play audio in a VC and command to leave VC using interactions/slash commands. NOT ctx or 'discord.ext commands' | I am wanting to make my own personal/private bot join the voice channel I am in and play audio files. I have it able to join the VC but I can't figure out how to make the bot leave or play music/audio using slash commands/interactions. Everywhere I look it's just old & outdated examples. Even the discord.py github exam... | [
"Try doing\nguild = interaction.guild\nguild.voice_client.play\n\ninstead of\ninteraction.voice_client.play\n\n"
] | [
1
] | [] | [] | [
"discord.py",
"python"
] | stackoverflow_0074553794_discord.py_python.txt |
Q:
How to write json data(nested array) to file in one line format with Python?
I want to write json data to file, my expect as below, the nested array is very long
{
"test1": {
"key1": [[0, 40], [2, 42], [4, 44], [6, 46], [8, 48], [10, 50], [12, 52],......],
"key2": [[1, 41], [3, 43], [5, 45], [7, 47], [9,... | How to write json data(nested array) to file in one line format with Python? | I want to write json data to file, my expect as below, the nested array is very long
{
"test1": {
"key1": [[0, 40], [2, 42], [4, 44], [6, 46], [8, 48], [10, 50], [12, 52],......],
"key2": [[1, 41], [3, 43], [5, 45], [7, 47], [9, 49], [11, 51], [13, 53],......]
},
"test2": {
"key1": [[0, 52], [1, 53], ... | [
"with open(\"test.json\", 'w') as f:\n f.write(str(result))\n\n"
] | [
0
] | [] | [] | [
"file",
"json",
"python"
] | stackoverflow_0074559379_file_json_python.txt |
Q:
How can I access to the IP camera connected to a subnetwork of a router without port forwarding?
I'm struggling with some kind of connection problem.
Here's the problem that I wanted to resolve
What I want to do is getting video streaming data from a IP camera (RTSP)
The IP camera is attached to the router which ... | How can I access to the IP camera connected to a subnetwork of a router without port forwarding? | I'm struggling with some kind of connection problem.
Here's the problem that I wanted to resolve
What I want to do is getting video streaming data from a IP camera (RTSP)
The IP camera is attached to the router which has access to the internet
I want to connect to this IP camera from remote computer.
IP cam --- Router... | [
"I think a good idea would be to use a VPN. Install a VPN-Server (openvpn, wireguard, etc...) on your minicomputer in the same network as your camera. Than connect to your vpn from your computer. Now you should be able to access the camera.\nI have a few ideas how to view the camera stream, depending how you would ... | [
0
] | [] | [] | [
"connection",
"python",
"router",
"streaming"
] | stackoverflow_0074558953_connection_python_router_streaming.txt |
Q:
Convert CSV Blank cell to SQL NULL in Python
I'm trying to convert blank cells in a csv file to NULL and upload them in SQL Server table so it shows as NULL rather blank. below code works but they load NULL as a string. Can you please help me to modify the code so it loads NULL in SQL ?
reader = csv.reader(f_in) ... | Convert CSV Blank cell to SQL NULL in Python | I'm trying to convert blank cells in a csv file to NULL and upload them in SQL Server table so it shows as NULL rather blank. below code works but they load NULL as a string. Can you please help me to modify the code so it loads NULL in SQL ?
reader = csv.reader(f_in) # setup code
writer = csv.writer(f_out)
row = ... | [
"This should work\nimport pyodbc\nimport csv\ncnxn = pyodbc.connect(connection string)\ncur = cnxn.cursor()\nquery = \"insert into yourtable values(?, ?)\"\nwith open('yourfile.csv', 'rb') as csvfile:\n reader = csv.reader(csvfile, delimiter=',')\n for row in reader:\n for i in range(len(row)):\n ... | [
4,
0
] | [] | [] | [
"csv",
"null",
"python",
"python_3.x",
"sql_server"
] | stackoverflow_0041473612_csv_null_python_python_3.x_sql_server.txt |
Q:
pandas rolling apply function has slow performance
The source code in question is
import numpy as np
dd=lambda x: np.nanmax(1.0 - x / np.fmax.accumulate(x))
df.rolling(window=period, min_periods=1).apply(dd)
It takes an extremely long time to execute the above 2 lines of code.
It is with latest pandas version(1.4... | pandas rolling apply function has slow performance | The source code in question is
import numpy as np
dd=lambda x: np.nanmax(1.0 - x / np.fmax.accumulate(x))
df.rolling(window=period, min_periods=1).apply(dd)
It takes an extremely long time to execute the above 2 lines of code.
It is with latest pandas version(1.4.0).
The dataframe has 3000 rows and 2000 columns only.
... | [
"These are not a solution, at most workarounds for simple cases like the example function. But it confirms the suspicion that the processing speed of df.rolling.apply is anything but optimal.\nUsing a much smaller dataset for obvious reasons\nimport pandas as pd\nimport numpy as np\n\ndf = pd.DataFrame(\n np.ran... | [
0,
0
] | [] | [] | [
"apply",
"pandas",
"pandas_rolling",
"python"
] | stackoverflow_0071795937_apply_pandas_pandas_rolling_python.txt |
Q:
What is the most pythonic way to check if an object is a number?
Given an arbitrary python object, what's the best way to determine whether it is a number? Here is is defined as acts like a number in certain circumstances.
For example, say you are writing a vector class. If given another vector, you want to find t... | What is the most pythonic way to check if an object is a number? | Given an arbitrary python object, what's the best way to determine whether it is a number? Here is is defined as acts like a number in certain circumstances.
For example, say you are writing a vector class. If given another vector, you want to find the dot product. If given a scalar, you want to scale the whole vector.... | [
"Use Number from the numbers module to test isinstance(n, Number) (available since 2.6).\n>>> from numbers import Number\n... from decimal import Decimal\n... from fractions import Fraction\n... for n in [2, 2.0, Decimal('2.0'), complex(2, 0), Fraction(2, 1), '2']:\n... print(f'{n!r:>14} {isinstance(n, Number)}... | [
160,
33,
17,
4,
3,
3,
2,
1,
1,
0,
0,
0,
0,
0,
0
] | [
"You could use the isdigit() function.\n>>> x = \"01234\"\n>>> a.isdigit()\nTrue\n>>> y = \"1234abcd\"\n>>> y.isdigit()\nFalse\n\n"
] | [
-1
] | [
"numbers",
"python",
"types"
] | stackoverflow_0003441358_numbers_python_types.txt |
Q:
RecursionError: maximum recursion depth exceeded in comparison
I hope that this is not a duplicate, I apologise if so, but have done some googling and looking around stack overflow and not found anything as yet...
MCVE
I understand that if a function keeps calling itself, this can't keep happening indefinitely wit... | RecursionError: maximum recursion depth exceeded in comparison | I hope that this is not a duplicate, I apologise if so, but have done some googling and looking around stack overflow and not found anything as yet...
MCVE
I understand that if a function keeps calling itself, this can't keep happening indefinitely without a stack overflow, and so an error is raised after a certain lim... | [
"When a RecursionError is raised, the python interpreter may also offer you the context of the call that caused the error. This only serves for debugging, to give you a hint where in your code you should look in order to fix the problem.\nSee for example this circular str-call setup that leads to a different messag... | [
10,
7,
0
] | [] | [] | [
"python",
"python_3.x",
"recursion"
] | stackoverflow_0052873067_python_python_3.x_recursion.txt |
Q:
create multiple list from a list taking every nth item using for loop in python
test_list = ['a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9', 'a10',
'a11', 'a12', 'a13', 'a14', 'a15', 'a16', 'a17', 'a18']
my_result = {'list_a': ['a1', 'a4', 'a7', 'a10', 'a13', 'a16'],
'list_b': ['a2'... | create multiple list from a list taking every nth item using for loop in python | test_list = ['a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9', 'a10',
'a11', 'a12', 'a13', 'a14', 'a15', 'a16', 'a17', 'a18']
my_result = {'list_a': ['a1', 'a4', 'a7', 'a10', 'a13', 'a16'],
'list_b': ['a2', 'a5', 'a8', 'a11', 'a14', 'a17'],
'list_c': ['a3', 'a6', 'a9', 'a12', ... | [
"You can use mod:\nlist_a = []\nlist_b = []\nlist_c = []\n\n\nfor i in range(len(test_list)):\n if i % 3 == 0:\n list_a.append(test_list[i])\n if i % 3 == 1:\n list_b.append(test_list[i])\n if i % 3 == 2:\n list_c.append(test_list[i])\n\n",
"num_list = 3\n\nout = dict(zip([f'list_{i}... | [
1,
0,
0,
0
] | [] | [] | [
"dictionary",
"list",
"python",
"set"
] | stackoverflow_0074559692_dictionary_list_python_set.txt |
Q:
How to validate the enum values for python dataclass attributes
I have a dataclass and enum values which are as below:
@dataclass
class my_class:
id: str
dataType: CheckTheseDataTypes
class CheckTheseDataTypes(str,Enum):
FIRST="int"
SECOND="float"
THIRD = "string"
I want to check whenever this dataclass is calle... | How to validate the enum values for python dataclass attributes | I have a dataclass and enum values which are as below:
@dataclass
class my_class:
id: str
dataType: CheckTheseDataTypes
class CheckTheseDataTypes(str,Enum):
FIRST="int"
SECOND="float"
THIRD = "string"
I want to check whenever this dataclass is called it should have the datatype values only from the given enum list. I... | [
"You can use the post_init() method to do that.\nfrom enum import Enum\nfrom dataclasses import dataclass\n\n\nclass CheckTheseDataTypes(str, Enum):\n FIRST = \"int\"\n SECOND = \"float\"\n THIRD = \"string\"\n\n\n@dataclass\nclass MyClass:\n id: str\n data_type: CheckTheseDataTypes\n\n def __post... | [
2
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074559603_python_python_3.x.txt |
Q:
Visualizing multiple all point clouds with .bin format as a video from Lidar - Open3d
I generated several point clouds in .bin files through velodyne and would like to view the various point clouds as a video or animation.
My files 000000.bin to 007480.bin are from a route with a LIDAR turned on until the end of t... | Visualizing multiple all point clouds with .bin format as a video from Lidar - Open3d | I generated several point clouds in .bin files through velodyne and would like to view the various point clouds as a video or animation.
My files 000000.bin to 007480.bin are from a route with a LIDAR turned on until the end of the path and they are all in a directory called ../velodyne/ and I'm running a Deep learning... | [
"You can modify the demo.py script to achive that.\nMayavi is capable of saving the images as .png-s in a specific folders.\nInsert the following under the plot:\n#import\nimport mayavi.mlab as mlab\n\n#The draw scene plot already in demo.py, just to show where to insert\nV.draw_scenes(points=data_dict['points'][:,... | [
0
] | [] | [] | [
"lidar_data",
"linux",
"open3d",
"python",
"python_3.x"
] | stackoverflow_0074184928_lidar_data_linux_open3d_python_python_3.x.txt |
Q:
Switch rows and columns of a multindex dataframe created from nested dictionary
I converted the following nested dictionary into a data frame:
dic = {'US':{'Traffic':{'new':1415, 'repeat':670}, 'Sales':{'new':67068, 'repeat':105677}},
'UK': {'Traffic':{'new':230, 'repeat':156}, 'Sales':{'new':4568, 'repeat':... | Switch rows and columns of a multindex dataframe created from nested dictionary | I converted the following nested dictionary into a data frame:
dic = {'US':{'Traffic':{'new':1415, 'repeat':670}, 'Sales':{'new':67068, 'repeat':105677}},
'UK': {'Traffic':{'new':230, 'repeat':156}, 'Sales':{'new':4568, 'repeat':10738}}}
df = pd.DataFrame.from_dict({(i,j): dic[i][j]
f... | [
"Use collections.defaultdict:\nfrom collections import defaultdict\n\nd1 = defaultdict(dict)\n\nfor k, v in dic.items():\n for k1, v1 in v.items():\n for k2, v2 in v1.items():\n d1[(k, k2)].update({k1: v2})\n\ndf = pd.DataFrame(d1)\nprint(df)\n US UK \n new... | [
3
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074559739_pandas_python.txt |
Q:
I'm getting an Atribute Error in the following Question, can someone help me to figure out the problem
import re
phonenumregex=re.compile(r'ddd-ddd-dddd')
mo=phonenumregex.search("My number is 415-555-4242")
print("Phone Number found: " + mo.group())
#it gives me this error.
AttributeError: 'NoneType' object has... | I'm getting an Atribute Error in the following Question, can someone help me to figure out the problem | import re
phonenumregex=re.compile(r'ddd-ddd-dddd')
mo=phonenumregex.search("My number is 415-555-4242")
print("Phone Number found: " + mo.group())
#it gives me this error.
AttributeError: 'NoneType' object has no attribute 'group'
I gave the format as ddd-ddd-dddd in raw string. and was expecting to get the numbe... | [
"Your regec should be correct, \\d not d\nimport re\n# phonenumregex=re.compile(r'\\d\\d\\d-\\d\\d\\d-\\d\\d\\d\\d')\nphonenumregex=re.compile(r'\\d{3}-\\d{3}-\\d{4}')\nmo=phonenumregex.search(\"My number is 415-555-4242\")\nprint(\"Phone Number found: \" + mo.group())\n\n",
"For regex \\d is for digit so you can... | [
0,
0
] | [] | [] | [
"python",
"python_re"
] | stackoverflow_0074558031_python_python_re.txt |
Q:
Can I get a sub-DataFrame according to first letter in columns names?
I want to get only columns whose names start with 'Q1' and those starting with 'Q3', I know that this is possible by doing:
new_df=df[['Q1_1', 'Q1_2', 'Q1_3','Q3_1', 'Q3_2', 'Q3_3']]
But since my real df is too large (more than 70 variables) I ... | Can I get a sub-DataFrame according to first letter in columns names? | I want to get only columns whose names start with 'Q1' and those starting with 'Q3', I know that this is possible by doing:
new_df=df[['Q1_1', 'Q1_2', 'Q1_3','Q3_1', 'Q3_2', 'Q3_3']]
But since my real df is too large (more than 70 variables) I search a way to get the new_df by using only desired first letters in the... | [
"You can use pd.DataFrame.filter for this:\ndf.filter(regex = r'Q1_\\d|Q3_\\d')\n\n Q1_1 Q1_2 Q1_3 Q3_1 Q3_2 Q3_3\n0 5 0.631041 0 46 0.768563 0\n1 32 0.594106 1 46 0.982396 1\n2 78 0.703139 1 38 0.252107 0\n3 98 0.353230 0 35 0.324079 0... | [
4,
3
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074559691_dataframe_pandas_python.txt |
Q:
Show another image while showing one image in loop in opencv python
I am trying to show an image, named "Result", And if a person clicks on the image then, it should show another image, named "Result image", but after clicking, the image Result which has to be live input from webcam freezes. Can anyone help me wit... | Show another image while showing one image in loop in opencv python | I am trying to show an image, named "Result", And if a person clicks on the image then, it should show another image, named "Result image", but after clicking, the image Result which has to be live input from webcam freezes. Can anyone help me with this ?
Here is my code :
import cv2
cap = cv2.VideoCapture(0)
def sho... | [
"This code worked for me:\nimport cv2\n\ndef showImage(event,x,y,flags,param):\n if event == 1:\n\n cv2.imshow('Result Image', img)\n\ncv2.namedWindow('Result')\ncv2.setMouseCallback('Result', showImage)\ncv2.namedWindow('Result Image')\n\ncap = cv2.VideoCapture(0)\n\nwhile True:\n _, img = cap.read()\... | [
0
] | [] | [] | [
"cv2",
"python"
] | stackoverflow_0074547237_cv2_python.txt |
Q:
Can't generate Python docstring with autoDocstring extension in VS Code when multiline string in the function body
To generate documentation with Python Sphinx I have to use a specific docstring format.
VS Code extension autoDocstring is capable to generate this specific format, but if the function contains multil... | Can't generate Python docstring with autoDocstring extension in VS Code when multiline string in the function body | To generate documentation with Python Sphinx I have to use a specific docstring format.
VS Code extension autoDocstring is capable to generate this specific format, but if the function contains multiline string then it doesn't work.
Example in this case works:
def func(param1, param2, param3):
# docstring nicely ge... | [
"Keyboard shortcut: ctrl+shift+2 or cmd+shift+2 for mac\n",
"I figured out the solution and I post it here, maybe will help somebody.\nActually the solution is pretty straightforward.\nI changed the triple apostrophes to triple single quotes in the function/class/whatever string variable and now autoDocstring's p... | [
0,
0
] | [] | [] | [
"docstring",
"python",
"visual_studio_code"
] | stackoverflow_0071211181_docstring_python_visual_studio_code.txt |
Q:
Cythonize Package & Tox Testing
I am developing a pypi-package (*.py-files), which is being tested via tox. Since compiling the package might yield some performance improvements, I'd like to cythonize it, and also verify using tox that the package is compiled.
For this purpose, I have made the following adjustment... | Cythonize Package & Tox Testing | I am developing a pypi-package (*.py-files), which is being tested via tox. Since compiling the package might yield some performance improvements, I'd like to cythonize it, and also verify using tox that the package is compiled.
For this purpose, I have made the following adjustments:
setup.py additions:
import pathlib... | [
"I activated a virtualenv created by tox and ran the code manually:\n$ . Minimal-Example-Cythonize-Package-Tox/.tox/py310/bin/activate\n$ python\nPython 3.10.8 (main, Oct 25 2022, 01:00:56) [GCC 10.2.1 20210110] on linux\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> from mypac... | [
0
] | [] | [] | [
"cythonize",
"pip",
"python",
"tox"
] | stackoverflow_0074558388_cythonize_pip_python_tox.txt |
Q:
Install mysqlclient for Django Python on Mac OS X Sierra
I have already installed
Python 2.7.13
Django 1.11
MySQL 5.7.17
I want use MySQL with Django, but after install mysql connector I was try to install mysqlclient for Python on $ pip install mysqlclient, but I have this issue:
Collecting mysqlclient
Using... | Install mysqlclient for Django Python on Mac OS X Sierra | I have already installed
Python 2.7.13
Django 1.11
MySQL 5.7.17
I want use MySQL with Django, but after install mysql connector I was try to install mysqlclient for Python on $ pip install mysqlclient, but I have this issue:
Collecting mysqlclient
Using cached mysqlclient-1.3.10.tar.gz
Complete output from com... | [
"I needed the following to build / install mysqlclient\nbrew install mysql-client\n# mysql-client is not on the `PATH` by default\nexport PATH=\"/usr/local/opt/mysql-client/bin:$PATH\"\n# openssl is not on the link path by default\nexport LIBRARY_PATH=\"$LIBRARY_PATH:/usr/local/opt/openssl/lib/\"\n\nThen I could pi... | [
53,
24,
15,
13,
7,
3,
2,
0,
0
] | [] | [] | [
"django",
"macos",
"mysql",
"python"
] | stackoverflow_0043612243_django_macos_mysql_python.txt |
Q:
imaplib.error: b'LOGIN failed' when trying to login using imaplib
I got that error, credentials is ok and was working in the morning. Reset password did not change,
logging into OWA works fine, login using imaplib fails with "LOGIN failed" after 1 minute or so!
def get_otp():
# sleeping for 20 seconds
time... | imaplib.error: b'LOGIN failed' when trying to login using imaplib | I got that error, credentials is ok and was working in the morning. Reset password did not change,
logging into OWA works fine, login using imaplib fails with "LOGIN failed" after 1 minute or so!
def get_otp():
# sleeping for 20 seconds
time.sleep(20)
# username for mail id
user = '***********'
# pa... | [
"Microsoft has disabled basic authentication in Office 365:\nhttps://techcommunity.microsoft.com/t5/exchange-team-blog/basic-authentication-deprecation-in-exchange-online-september/ba-p/3609437\nHowever, there might be a method to authenticate using oauth2.\nI'm personally working on a solution that might be using:... | [
0
] | [] | [] | [
"gmail_imap",
"imap",
"python"
] | stackoverflow_0074023368_gmail_imap_imap_python.txt |
Q:
These two strings are supposed to be the same length but when printed they do not appear that way
a="|:watch:️ :mobile phone: :mobile phone with arrow: :laptop: :keyboard: :desktop computer: |"
b="|:printer: :computer mouse: :trackball: :joystick: :clamp: :computer disk: :floppy disk: :optical|"
both of th... | These two strings are supposed to be the same length but when printed they do not appear that way | a="|:watch:️ :mobile phone: :mobile phone with arrow: :laptop: :keyboard: :desktop computer: |"
b="|:printer: :computer mouse: :trackball: :joystick: :clamp: :computer disk: :floppy disk: :optical|"
both of these strings should be 98 characters, but when printing with a monospaced font (in my terminal) it shows... | [
"I was guessing that one of the chars in a is strange. We can see this if we print them:\nIn [4]: for i, char in enumerate(a):\n ...: print((i, char))\n ...:\n(0, '|')\n(1, ':')\n(2, 'w')\n(3, 'a')\n(4, 't')\n(5, 'c')\n(6, 'h')\n(7, ':')\n(8, '️')\n(9, ' ')\n(10, ':')\n(11, 'm')\n(12, 'o')\n(13, 'b')\n(14, ... | [
1,
0
] | [] | [] | [
"ascii_art",
"python",
"visual_studio_code"
] | stackoverflow_0074559938_ascii_art_python_visual_studio_code.txt |
Q:
How to read a file which in CSV format, but different extension?
I have a dataset which has a good dataframe structure starting from row 3. For the first rows, unfortunately separators are diverse, and there is a few information to be included in my dataframe. The files are in CSV strcture mostly, but they have ex... | How to read a file which in CSV format, but different extension? | I have a dataset which has a good dataframe structure starting from row 3. For the first rows, unfortunately separators are diverse, and there is a few information to be included in my dataframe. The files are in CSV strcture mostly, but they have extensions like WOC, WOL, WPL, and so on.
The WOC file first rows look l... | [
"Base on additional info from your comments above I think you can start build your solution with following:\n`# I created a file 'data.woc' with data as stream from your question:`\nimport pandas as pd\nfrom io import StringIO\nimport re\nstack_data = '''Person:?,?;F dob. ? MT: ? Z:C NewYork Mon.:S St.?\n\n144 cm/... | [
1
] | [] | [] | [
"csv",
"pandas",
"python"
] | stackoverflow_0074558525_csv_pandas_python.txt |
Q:
for loop: applying a, b in two lists
I am trying to modify the following script so that my legends are changed to that list in speeds. How can I do this without changing the iterator list?
x = np.arange(10)
iterator = [1, 2, 3]
speeds =[*range(100,300,500)]
for a in iterator:
plt.plot(x, a*x, label=f'{a}rpm')
... | for loop: applying a, b in two lists | I am trying to modify the following script so that my legends are changed to that list in speeds. How can I do this without changing the iterator list?
x = np.arange(10)
iterator = [1, 2, 3]
speeds =[*range(100,300,500)]
for a in iterator:
plt.plot(x, a*x, label=f'{a}rpm')
plt.legend(loc='best')
Modified scrip... | [
"and is a logical operator, not a general connective as in English.\nCombine the lists first with zip and then iterate:\n>>> x = [1,2,3]\n>>> y = [4,5,6]\n>>> for a, b in zip(x, y): print(a, b)\n...\n1 4\n2 5\n3 6\n\n",
"Not so sure, what's the usage of\n[*range(100, 300, 500)]\n>>> [100]\n\nFrom your question if... | [
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0074559896_python.txt |
Q:
is this the right way to apply softmax?
self.classifier = nn.Sequential(
nn.Flatten(),
nn.Linear(in_features = 32*8*8, out_features = 26),
nn.ReLU(),
nn.Linear(in_features = 26, out_features = output_shape),
nn.Softmax(dim=1)
)
and my loss fn is
loss_fn = nn.CrossEntrop... | is this the right way to apply softmax? | self.classifier = nn.Sequential(
nn.Flatten(),
nn.Linear(in_features = 32*8*8, out_features = 26),
nn.ReLU(),
nn.Linear(in_features = 26, out_features = output_shape),
nn.Softmax(dim=1)
)
and my loss fn is
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(params =... | [
"No, CrossEntropyLoss doesn't require Softmax as it already includes it (or actually LogSoftmax): https://pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html?highlight=crossentropy#torch.nn.CrossEntropyLoss.\n"
] | [
0
] | [] | [] | [
"activation_function",
"deep_learning",
"python",
"pytorch"
] | stackoverflow_0074554945_activation_function_deep_learning_python_pytorch.txt |
Q:
Pandas Apply transformation to multiple columns but do not discard other columns?
I have a table of an "Id" column and multiple integer columns that I want to convert to categorical variables. Therefore, I want to apply this transformation only to those multiple integer columns, but leave the ID column unchanged.
... | Pandas Apply transformation to multiple columns but do not discard other columns? | I have a table of an "Id" column and multiple integer columns that I want to convert to categorical variables. Therefore, I want to apply this transformation only to those multiple integer columns, but leave the ID column unchanged.
All the other methods involve dropping the ID column. How do I do this without dropping... | [
"One way to do this is by isolating the Id column and then joining the converted columns:\ndf = df[['Id']].join(\n df.loc[:, df.columns != 'Id'].astype('category')\n)\n\n",
"Another way is to try:\ndf = df.groupby('Id').transform(lambda x: pd.Categorical(x)).reset_index(names = 'id')\n\n",
"I think the easie... | [
1,
1,
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074330370_dataframe_pandas_python.txt |
Q:
Improving Weighted Moving Average Performance
I have been playing around with a pandas data frame with 414,000 rows.
Built into pandas is an exponential moving average computed by:
series.ewm(span=period).mean()
The above executes in < 0.3 seconds. I am however in search of trying to use a weighted moving average... | Improving Weighted Moving Average Performance | I have been playing around with a pandas data frame with 414,000 rows.
Built into pandas is an exponential moving average computed by:
series.ewm(span=period).mean()
The above executes in < 0.3 seconds. I am however in search of trying to use a weighted moving average (which has a linear linear weighting of each eleme... | [
"You can use the np sliding window function docs, then it looks like this:\nimport numpy as np\nimport pandas as pd\n\nd1 = pd.DataFrame(np.random.randint(0, 10, size=(500_000))) # x=500_000\n\np = 50\nw = np.arange(p)+1\nw_s = w.sum()\n\n########## for comparison purpose ##########\n# 1.47 s ± 12.5 ms per loop (me... | [
1,
1,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074518386_dataframe_pandas_python.txt |
Q:
Using Usb Camera with Opencv Python
I am developing a neural network with python opencv. It works when I turn on the laptop's own camera. When I plug in an external usb camera, I don't get any response. Independent of the program, only if I write opencv camera opening codes, it hangs. The program does not clos... | Using Usb Camera with Opencv Python | I am developing a neural network with python opencv. It works when I turn on the laptop's own camera. When I plug in an external usb camera, I don't get any response. Independent of the program, only if I write opencv camera opening codes, it hangs. The program does not close, it seems to be running, but nothing ha... | [
" The device index is just a number to determine which camera. Usually one camera will be connected (as in my case my camera id is 0). You can choose a second camera by changing camera id : 1 to camera id : 0 or camera id : 2. Camera id can be changed to index 0 - 9.\nhope this can help you\n"
] | [
0
] | [] | [] | [
"opencv",
"python",
"python_3.x"
] | stackoverflow_0074543478_opencv_python_python_3.x.txt |
Q:
groupby in pandas with custom function over a subset of rows in each group
I have a pandas DataFrame of the following format:
Input:
X [OTHER_COLUMNS]
version branch
v0 overall 2475.0 -1 .
v1 overall 2475.0 ... | groupby in pandas with custom function over a subset of rows in each group | I have a pandas DataFrame of the following format:
Input:
X [OTHER_COLUMNS]
version branch
v0 overall 2475.0 -1 .
v1 overall 2475.0 -1 .
A 1712.5 1 .
B ... | [
"Use:\n#select overalls only\noverall = df['N'].xs('overall', level=1)\n#select all rows without overalls\ndf1 = df.drop('overall', level=1)\n\n#multiple and aggregate sum, divide overalls \ns = df1['N'].mul(df1['X']).groupby(level=0).sum().div(overall)\n\n#create MultiIndex and assign back\ndf.loc[pd.IndexSlice[... | [
1
] | [] | [] | [
"aggregate",
"group_by",
"pandas",
"python"
] | stackoverflow_0074560070_aggregate_group_by_pandas_python.txt |
Q:
How to truncate the time on a datetime object?
What is a classy way to way truncate a python datetime object?
In this particular case, to the day. So basically setting hour, minute, seconds, and microseconds to 0.
I would like the output to also be a datetime object, not a string.
A:
I think this is what you're ... | How to truncate the time on a datetime object? | What is a classy way to way truncate a python datetime object?
In this particular case, to the day. So basically setting hour, minute, seconds, and microseconds to 0.
I would like the output to also be a datetime object, not a string.
| [
"I think this is what you're looking for...\n>>> import datetime\n>>> dt = datetime.datetime.now()\n>>> dt = dt.replace(hour=0, minute=0, second=0, microsecond=0) # Returns a copy\n>>> dt\ndatetime.datetime(2011, 3, 29, 0, 0)\n\nBut if you really don't care about the time aspect of things, then you should really on... | [
498,
96,
48,
24,
24,
12,
10,
4,
3,
3,
3,
2,
1,
1,
1,
1,
0
] | [
"What does truncate mean?\nYou have full control over the formatting by using the strftime() method and using an appropriate format string.\nhttp://docs.python.org/library/datetime.html#strftime-strptime-behavior\n"
] | [
-3
] | [
"datetime",
"python"
] | stackoverflow_0005476065_datetime_python.txt |
Q:
python Remembering the list for another use
suppose we have a main.py file and a_file.py that has a list
like this :
main.py
from a_file import *
while true:
example = input("Enter Something : ")
a_list.append(example)
if example == 'showlist':
print(a_list)
a_file.py
a_list = []
so as yo... | python Remembering the list for another use | suppose we have a main.py file and a_file.py that has a list
like this :
main.py
from a_file import *
while true:
example = input("Enter Something : ")
a_list.append(example)
if example == 'showlist':
print(a_list)
a_file.py
a_list = []
so as you can see the main.py file has a input that wh... | [
"instead of putting the data in a list try using file handling methods to save your input in a permanent file like:\nfile = open(\"FILE PATH\\\\FILE NAME.txt\", \"w\")\nwhile True:\n example = input(\"Enter Something : \")\n\n file.write(example)\n\n if example == 'showlist':\n\n for line in file:\n... | [
0,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0074559770_list_python.txt |
Q:
Flatten nested dictionaries, compressing keys
Suppose you have a dictionary like:
{'a': 1,
'c': {'a': 2,
'b': {'x': 5,
'y' : 10}},
'd': [1, 2, 3]}
How would you go about flattening that into something like:
{'a': 1,
'c_a': 2,
'c_b_x': 5,
'c_b_y': 10,
'd': [1, 2, 3]}
A:
Basically the sa... | Flatten nested dictionaries, compressing keys | Suppose you have a dictionary like:
{'a': 1,
'c': {'a': 2,
'b': {'x': 5,
'y' : 10}},
'd': [1, 2, 3]}
How would you go about flattening that into something like:
{'a': 1,
'c_a': 2,
'c_b_x': 5,
'c_b_y': 10,
'd': [1, 2, 3]}
| [
"Basically the same way you would flatten a nested list, you just have to do the extra work for iterating the dict by key/value, creating new keys for your new dictionary and creating the dictionary at final step.\nimport collections\n\ndef flatten(d, parent_key='', sep='_'):\n items = []\n for k, v in d.item... | [
312,
182,
80,
50,
36,
30,
16,
8,
8,
7,
6,
6,
4,
4,
3,
3,
3,
3,
3,
3,
3,
2,
2,
2,
2,
1,
1,
0,
0,
0,
0,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0006027558_dictionary_python.txt |
Q:
Values replacement in python pandas
I need to replace each cell containing values like number1(number2) with number2 (the value inside the parenthesis). For example: 56(3) -> 3, 33(5) -> 5
These values can appear in different columns.
The problem is that with pandas function
df.replace(to_replace=..., value=...)
... | Values replacement in python pandas | I need to replace each cell containing values like number1(number2) with number2 (the value inside the parenthesis). For example: 56(3) -> 3, 33(5) -> 5
These values can appear in different columns.
The problem is that with pandas function
df.replace(to_replace=..., value=...)
i cannot use as value something that depe... | [
"Have you tried df.apply instead?\nA caveat is that using apply on a dataFrame sends the entire row as input to the lambda function, so you will have to do something like this:\nfor col in df.columns:\n df[col] = df[col].apply(<insert lambda function here>)\n\n"
] | [
0
] | [] | [] | [
"lambda",
"pandas",
"python",
"regex",
"replace"
] | stackoverflow_0074560157_lambda_pandas_python_regex_replace.txt |
Q:
Connecting with Blob Container in one specific notebook in DataBricks
I work under one cluster in DataBricks which has mounted blob container. I'd like to keep that one container for the whole cluster, but mount another already created cluster for one specific notebook (or repo, that would be awesome) to load data... | Connecting with Blob Container in one specific notebook in DataBricks | I work under one cluster in DataBricks which has mounted blob container. I'd like to keep that one container for the whole cluster, but mount another already created cluster for one specific notebook (or repo, that would be awesome) to load data from there. How can I make it?
Example:
Repo 1 - blob 1:
notebooks blob 1... | [
"You can use the following procedure load the data into storage account.\nI reproduce same in my environment with two repro's\nRepro 1:\nContainer name: input Mount_point:/mnt/hffj\n\nRepro 2:\nContainer name: output Mount_point:/mnt/output\n\nAs per above scenario you can do in this way:\nFirst of all read the dat... | [
0
] | [] | [] | [
"azure",
"azure_blob_storage",
"azure_databricks",
"databricks",
"python"
] | stackoverflow_0074557236_azure_azure_blob_storage_azure_databricks_databricks_python.txt |
Q:
python requests vs bash curl for session cookies
I have a bash script that logs in to a website and fetches the json data from a URL and does other stuffs after that. I am trying to re-write the script using python but I am stuck at the log in part itself.
Below is a function from the bash script that I wrote, to ... | python requests vs bash curl for session cookies | I have a bash script that logs in to a website and fetches the json data from a URL and does other stuffs after that. I am trying to re-write the script using python but I am stuck at the log in part itself.
Below is a function from the bash script that I wrote, to login to the site and fetch the status
get_status() {... | [
"To anyone having same issue hope this would help.\nI was able to get this working with the below code.\nsession = requests.session()\nsession.get(url + \"/target/app1/login\")\nlogin = session.post(url + \"/target/app1/login\", data)\ndata = session.get(url)\n\n"
] | [
0
] | [] | [] | [
"bash",
"cookies",
"curl",
"python",
"python_requests"
] | stackoverflow_0073232869_bash_cookies_curl_python_python_requests.txt |
Q:
Optimizing a funcation using Scipy to estimate fitting parameters
I am trying to optimize a function by finding its minimum value using Scipy.
The code must find the values of the variables g and tau that will give the minimum value of MSE.
However, These values must be arrays not scalars. Below is the code
import... | Optimizing a funcation using Scipy to estimate fitting parameters | I am trying to optimize a function by finding its minimum value using Scipy.
The code must find the values of the variables g and tau that will give the minimum value of MSE.
However, These values must be arrays not scalars. Below is the code
import numpy as np
import numpy as np
import pandas as pd
import math
import ... | [
"Im not seeing how you are using the input of your objective function SE. You convert that into g and tau, but those are not used either. Your objective function returns an output that is simply based on some values in a panda array, which stay the same every time. Your optimisation parameters simply have no impact... | [
0,
0
] | [] | [] | [
"function_fitting",
"minimization",
"optimization",
"python",
"scipy"
] | stackoverflow_0074558712_function_fitting_minimization_optimization_python_scipy.txt |
Q:
Extract time from a column in given
The time column in my dataframe df looks like
Date_UTC
1998-05-02T00:00:00
1998-05-02T00:01:00
1998-05-02T00:02:00
1998-05-02T00:03:00
1998-05-02T00:04:00
1998-05-02T00:05:00
1998-05-02T00:06:00
1998-05-02T00:07:00
1998-05-02T00:08:00
1998-05-02T00:09:00
1998-05-02T00:10:00
I w... | Extract time from a column in given | The time column in my dataframe df looks like
Date_UTC
1998-05-02T00:00:00
1998-05-02T00:01:00
1998-05-02T00:02:00
1998-05-02T00:03:00
1998-05-02T00:04:00
1998-05-02T00:05:00
1998-05-02T00:06:00
1998-05-02T00:07:00
1998-05-02T00:08:00
1998-05-02T00:09:00
1998-05-02T00:10:00
I want to extract time values from it. Pleas... | [
"you can use:\ndf['time']=pd.to_datetime(df['Date_UTC']).dt.time\n\n#if you want to only dates\ndf['Date_UTC']=pd.to_datetime(['Date_UTC']).dt.date```\n\n"
] | [
0
] | [] | [] | [
"jupyter_notebook",
"numpy",
"pandas",
"python"
] | stackoverflow_0074560292_jupyter_notebook_numpy_pandas_python.txt |
Q:
Why is my code returning the address of the variable instead of the value?
I am finding it difficult to understand why my code is returning my memory address. I have tried to use __str__ and __repr__ respectively but maybe I am unfamiliar with how these work exactly.
import random
class Card:
def __init__(sel... | Why is my code returning the address of the variable instead of the value? | I am finding it difficult to understand why my code is returning my memory address. I have tried to use __str__ and __repr__ respectively but maybe I am unfamiliar with how these work exactly.
import random
class Card:
def __init__(self, suit, value):
self.suit = suit #['H','D','C','S']
self.value ... | [
"it seems that you have forgotten to define the __repr__ method for the Card class. Should be something like:\n def __repr__(self):\n return f\"Card({self.value})\"\n\nwhereas for the Deck I would define it as:\n def __repr__(self):\n return f'Deck(\"{self.cards}\")'\n\nthe resulting output will... | [
3,
3
] | [] | [] | [
"output",
"python",
"python_3.x"
] | stackoverflow_0074560234_output_python_python_3.x.txt |
Q:
Why do I have to use parantheses in (x > 0) & (x < 2) to avoid "The truth value of an array with more than one element is ambiguous"?
Having:
import numpy as np
x = np.ndarray([0,1,2])
This doesn't work:
x > 0 & x < 2
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or... | Why do I have to use parantheses in (x > 0) & (x < 2) to avoid "The truth value of an array with more than one element is ambiguous"? | Having:
import numpy as np
x = np.ndarray([0,1,2])
This doesn't work:
x > 0 & x < 2
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
This works:
(x > 0) & (x < 2)
Out[32]: array([False, True, False])
So maybe the reason is operator precedence. But all of thes... | [
"It seems that x > 0 & x < 2 is more like (x > (0 & x)) and ((0 & x) < 2), and the error is raised for the operation and.\nI believe it's caused by that & will be calculated before comparison, and python has a syntactic sugar to translate x > y < z into (x > y) and (y < z).\n"
] | [
3
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0074560194_numpy_python.txt |
Q:
How to get the return value from a thread?
The function foo below returns a string 'foo'. How can I get the value 'foo' which is returned from the thread's target?
from threading import Thread
def foo(bar):
print('hello {}'.format(bar))
return 'foo'
thread = Thread(target=foo, args=('world!',))
thread.st... | How to get the return value from a thread? | The function foo below returns a string 'foo'. How can I get the value 'foo' which is returned from the thread's target?
from threading import Thread
def foo(bar):
print('hello {}'.format(bar))
return 'foo'
thread = Thread(target=foo, args=('world!',))
thread.start()
return_value = thread.join()
The "one obv... | [
"One way I've seen is to pass a mutable object, such as a list or a dictionary, to the thread's constructor, along with a an index or other identifier of some sort. The thread can then store its results in its dedicated slot in that object. For example:\ndef foo(bar, result, index):\n print 'hello {0}'.format(b... | [
409,
334,
260,
107,
92,
47,
34,
29,
26,
8,
7,
6,
6,
5,
4,
2,
2,
2,
1,
1,
0,
0,
0,
0
] | [
"I know this thread is old.... but I faced the same problem... If you are willing to use thread.join()\nimport threading\n\nclass test:\n\n def __init__(self):\n self.msg=\"\"\n\n def hello(self,bar):\n print('hello {}'.format(bar))\n self.msg=\"foo\"\n\n\n def main(self):\n thr... | [
-2,
-3
] | [
"multithreading",
"python",
"return_value"
] | stackoverflow_0006893968_multithreading_python_return_value.txt |
Q:
Python strftime days without ZERO
Why doesn't the codes from this page work?: http://strftime.org/.
I want to output date and months without leading zeroes, like 'm/d/yyyy'
e.g.:
'4/5/1992' YES
'04/05/1992' NO
from datetime import datetime, timedelta, date
yest = datetime.strftime(datetime.now() - timedelta(21), '... | Python strftime days without ZERO | Why doesn't the codes from this page work?: http://strftime.org/.
I want to output date and months without leading zeroes, like 'm/d/yyyy'
e.g.:
'4/5/1992' YES
'04/05/1992' NO
from datetime import datetime, timedelta, date
yest = datetime.strftime(datetime.now() - timedelta(21), '%-m-%-d-%Y')
print(yest)
ValueError ... | [
"That %-m option does state that the format is platform specific, so mileage may vary.\nYou can simply use f-strings in Python 3.\nyest = datetime.now() - timedelta(21)\nyest = f'{yest.month}/{yest.day}/{yest.year}'\n>>> yest\n'10/9/2019'\n\nIn the case of your dataframe explained in the comments:\ndf = pd.DataFram... | [
2,
1
] | [] | [] | [
"date",
"python",
"string"
] | stackoverflow_0058634685_date_python_string.txt |
Q:
How can I handle missing values in the dictionary when I use the function eval(String dictionary) -> dictionary PYTHON?
I need to convert the ‘content’ column from a string dictionary to a dictionary in python. After that I will use the following line of code:
df[‘content’].apply(pd.Series).
To have the dictionary... | How can I handle missing values in the dictionary when I use the function eval(String dictionary) -> dictionary PYTHON? | I need to convert the ‘content’ column from a string dictionary to a dictionary in python. After that I will use the following line of code:
df[‘content’].apply(pd.Series).
To have the dictionary values as a column name and the dictionary value in a cell.
I can’t do this now because there are missing values in the dict... | [
"you can use json.loads in lambda function. if row value is nan, pass, if not, apply json.loads:\n:\nimport json\nimport numpy as np\ndf['content']=df['content'].apply(lambda x: json.loads(x) if pd.notna(x) else np.nan)\n\n\nnow you can use pd.Series.\nv1 = df['Content'].apply(pd.Series)\ndf = df.drop(['Content'],a... | [
0
] | [
"I cannot see what the missing values look like in your screenshot, but i tested the following code and got what seems to be a good result. The simple explanation in to use str.replace() to fix the null values before parsing the string to dict.\nimport pandas as pd\nimport numpy as np\nimport json\n\n## setting up ... | [
-1
] | [
"dictionary",
"eval",
"json",
"pandas",
"python"
] | stackoverflow_0074559959_dictionary_eval_json_pandas_python.txt |
Q:
Adjusting Values in one dataframe using balance from another dataframe in Python
I have two tables:
Table A
Employee ID Date Data Used
1 01-01-2020 2
1 02-01-2020 5
1 03-01-2020 6
1 04-01-2020 4
2 05-01-2020 1
2 06-01-2020 2
2 07-01-2020 2
Table B
Employee ID Date Data Balance
1 01-01... | Adjusting Values in one dataframe using balance from another dataframe in Python | I have two tables:
Table A
Employee ID Date Data Used
1 01-01-2020 2
1 02-01-2020 5
1 03-01-2020 6
1 04-01-2020 4
2 05-01-2020 1
2 06-01-2020 2
2 07-01-2020 2
Table B
Employee ID Date Data Balance
1 01-01-2020 6
1 02-01-2020 9
1 03-01-2020 5
1 04-01-2020 3
2 05-01-2020 7
2 0... | [
"You essentially want to index the dataframes using two columns.\ndf = df.set_index([\"Employee ID\",\"Date\"]) on both dataframes should achieve this. You can now loop through one dataframe and match their indices.\nTo take it further, you can join both dataframes with new_df = df1.join(df2,on=[\"Employee ID\",\"D... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074560258_python.txt |
Q:
Using pandas how can i find a string from every row in a excel A in another excel B(from all columns) and if it matches, return column from B
I have two excel. Excel A and Excel B.
Excel A has 2 columns. Excel B has 5 columns
I want to find value each from Column2 in A in All 5 columns of Excel B(it may not be exa... | Using pandas how can i find a string from every row in a excel A in another excel B(from all columns) and if it matches, return column from B | I have two excel. Excel A and Excel B.
Excel A has 2 columns. Excel B has 5 columns
I want to find value each from Column2 in A in All 5 columns of Excel B(it may not be exact match, its just may just contain that vaule)
Example
Excel A
Column A1
Column A2
405
121h
496
156b
456
325v
ExcelB
Column B1... | [
"Assuming ExcelA and ExcelB are DataFrames.\nYou can melt and use str.extract with a pattern made from ExcelA to use as a key for the merge:\nimport re\n\nto_merge = ['Column B4'] # use here all columns to merge\n\ntmp = ExcelB.melt(to_merge)\npattern = '|'.join(map(re.escape, ExcelA['Column A2']))\n# '121h|156b|32... | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074559194_pandas_python.txt |
Q:
python calculator indentation error (cant seem to get the program working)
I just started python yesterday so I was trying to make this python code to make a calculator that adds, multiplies, divides, and subtracts. When I started testing the code just wasn't working even though I did similar things and to me, the... | python calculator indentation error (cant seem to get the program working) | I just started python yesterday so I was trying to make this python code to make a calculator that adds, multiplies, divides, and subtracts. When I started testing the code just wasn't working even though I did similar things and to me, the code looked right this is the code:
op =input("which operation would you like t... | [
"This should resolve the indentation error.\nop =input(\"which operation would you like to use (type m for multiply d for divide s for subtract a for addition): \")\nfirst_number =float(input(\"please enter your first number: \"))\nsecond_number =float(input(\"please enter your second number: \"))\nif op.upper()==\... | [
0
] | [
"It should look like this:\nop =input(\"which operation would you like to use (type m for multiply d for divide s for subtract a for addition): \")\nfirst_number =float(input(\"please enter your first number: \"))\nsecond_number =float(input(\"please enter your second number: \"))\nif op.upper()==\"m\" or op.lower(... | [
-1
] | [
"calculator",
"indentation",
"python"
] | stackoverflow_0074560435_calculator_indentation_python.txt |
Q:
accessing python dict values with line-breaking (PEP-8)
I'm trying to access the values of a python dictionary, but the line is too long so it doesn't match PEP-8 rules. (I'm using flake8 linter on vscode)
example:
class GoFirstSpider():
def __init__(self, flight_search_request):
self.name = 'goFirst'
... | accessing python dict values with line-breaking (PEP-8) | I'm trying to access the values of a python dictionary, but the line is too long so it doesn't match PEP-8 rules. (I'm using flake8 linter on vscode)
example:
class GoFirstSpider():
def __init__(self, flight_search_request):
self.name = 'goFirst'
-> self.date = flight_search_request["FlightSearchReques... | [
"You can use \\ to break lines.\nclass GoFirstSpider():\n def __init__(self, flight_search_request):\n self.name = 'goFirst'\n self.date = flight_search_request[\"FlightSearchRequest\"] \\\n [\"FlightDetails\"][\"DepartureDate\"]\n\n",
"You can use \\ to break multiple lines as stated in t... | [
0,
0
] | [] | [] | [
"flake8",
"pep8",
"python"
] | stackoverflow_0074560371_flake8_pep8_python.txt |
Q:
How do I update the current animated line graph every time I draw a new one?
I've been new to python, and recently I am trying with the FuncAnimation recently. I was trying to make a graph that shows the diffusion graphs for every different p and q values, so each time it's supposed to mutate on the current line g... | How do I update the current animated line graph every time I draw a new one? | I've been new to python, and recently I am trying with the FuncAnimation recently. I was trying to make a graph that shows the diffusion graphs for every different p and q values, so each time it's supposed to mutate on the current line graph with different p and q as parameters for a fixed amount of t. I've been tryin... | [
"The problem is that func argument should be a callable that updates the plot. Currently you plot a new line in your update function. There are some simple examples with good explanation on this page showing how to use the animation feature. Below I slightly modify a few lines of your code to get your desired outpu... | [
0
] | [] | [] | [
"animation",
"graph",
"matplotlib",
"python"
] | stackoverflow_0074557632_animation_graph_matplotlib_python.txt |
Q:
How to get a tree of all xpaths in a website using Python?
Approach I
While trying to get a hierarchical tree of all the xpaths in a website (https://startpagina.nl) using Python, I first tried to get the xpath for the branch: /html/body using:
from selenium import webdriver
url = 'https://startpagina.nl'
driver... | How to get a tree of all xpaths in a website using Python? | Approach I
While trying to get a hierarchical tree of all the xpaths in a website (https://startpagina.nl) using Python, I first tried to get the xpath for the branch: /html/body using:
from selenium import webdriver
url = 'https://startpagina.nl'
driver = webdriver.Firefox()
driver.get(url)
test = driver.find_eleme... | [
"The total number of XPaths that select one or more elements is infinite (for example it will include paths like /a/b/../b/../b/../b), but if you restrict yourself to paths of the form /a[i]/b[j]/c[k] then the number of paths is equal to the number of elements, and the \"tree\" of XPaths is isomorphic with the orig... | [
2,
1
] | [] | [] | [
"html",
"python",
"selenium",
"tree",
"xpath"
] | stackoverflow_0074560320_html_python_selenium_tree_xpath.txt |
Q:
How to get function value outside the function in python?
Code:
import logging
def main(name: str) -> str:
return f"Hello {name}!"
print({name})
I wanna get main function output store in variable and use in outside the function. I'm new in python, I cannot see exact same example on net, Check multiple ways ... | How to get function value outside the function in python? | Code:
import logging
def main(name: str) -> str:
return f"Hello {name}!"
print({name})
I wanna get main function output store in variable and use in outside the function. I'm new in python, I cannot see exact same example on net, Check multiple ways but not getting value.
There is no any value getting inside the... | [
"def main(name: str) -> str:\n return f\"Hello {name}!\"\n\n# You can use\nprint(main(\"world\"))\n# or\nvar = main(\"world\")\nprint(var)\n# or Under the current file\nif __name__ == '__main__':\n var = main(\"world\")\n print(var)\n\n",
"import logging\n\ndef main(name: str) -> str:\n return f\"Hell... | [
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074560395_python.txt |
Q:
How to track the current user in flask-login?
I m trying to use the current user in my view from flask-login. So i tried to g object
I m assigning flask.ext.login.current_user to g object
@pot.before_request
def load_users():
g.user = current_user.username
It works if the user is correct. But when i do sign-u... | How to track the current user in flask-login? | I m trying to use the current user in my view from flask-login. So i tried to g object
I m assigning flask.ext.login.current_user to g object
@pot.before_request
def load_users():
g.user = current_user.username
It works if the user is correct. But when i do sign-up or login as with wrong credentials
I get this err... | [
"Thanks for your answer @Joe and @pjnola, as you all suggested i referred flask-login docs\nI found that we can customize the anonymous user class, so i customized for my requirement,\nAnonymous class\n#!/usr/bin/python\n#flask-login anonymous user class\nfrom flask.ext.login import AnonymousUserMixin\nclass Anonym... | [
20,
11,
6,
0
] | [] | [] | [
"flask",
"flask_extensions",
"flask_login",
"python",
"python_2.7"
] | stackoverflow_0019274226_flask_flask_extensions_flask_login_python_python_2.7.txt |
Q:
Map column values by ID based on multiple conditions
df = pd.DataFrame({'ID' : ['ID 1', 'ID 1', 'ID 1', 'ID 2', 'ID 2', 'ID 3', 'ID 3'],
'Code' : ['Apple', 'A123', 'Apple', 'Banana', 'Banana', 'K123', 'K123'],
'Code_Type' : ['Code name', 'Code ID', 'Code name', 'Code name', 'C... | Map column values by ID based on multiple conditions | df = pd.DataFrame({'ID' : ['ID 1', 'ID 1', 'ID 1', 'ID 2', 'ID 2', 'ID 3', 'ID 3'],
'Code' : ['Apple', 'A123', 'Apple', 'Banana', 'Banana', 'K123', 'K123'],
'Code_Type' : ['Code name', 'Code ID', 'Code name', 'Code name', 'Code name', 'Code ID', 'Code ID']}
)
df
... | [
"Try df.query(\"ID == Code_Type\") this will output only the rows whith the condition you want. Then you can convert it to a dictionary.\n",
"Here, my logic is to get the last row of each ID and then just selecting Code column turning it to the dictionary.\nCode:\ndf.groupby(['ID']).last()['Code'].T.to_dict()\n\n... | [
0,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074560023_dataframe_pandas_python.txt |
Q:
Logs are missing from commands run via `heroku run`
When I use heroku run to run a command, stdout and stderr only seem to go to the terminal where I ran the command. They can't be viewed with heroku logs or via logdrain.
Is there a way to get output from heroku run to be treated the same way as logs coming from, ... | Logs are missing from commands run via `heroku run` | When I use heroku run to run a command, stdout and stderr only seem to go to the terminal where I ran the command. They can't be viewed with heroku logs or via logdrain.
Is there a way to get output from heroku run to be treated the same way as logs coming from, say, the scheduler?
Repro steps
In one terminal, run:
$ h... | [
"This behaviour is documented:\n\nOne-off dynos run attached to your terminal, with a character-by-character TCP connection for STDIN and STDOUT. This allows you to use interactive processes like a console. Since STDOUT is going to your terminal, the only thing recorded in the app’s logs is the startup and shutdown... | [
1
] | [] | [] | [
"heroku",
"logging",
"python"
] | stackoverflow_0074553942_heroku_logging_python.txt |
Q:
Is there any way to stream the data to the server using Python requests module?
Lets' say that I'm sending very large (but finite) amount of data that keeps growing in real time.
I'd like to stream it to the server to prevent myself from running out of memory.
When there's no more data to be send, I'm leaving 'End... | Is there any way to stream the data to the server using Python requests module? | Lets' say that I'm sending very large (but finite) amount of data that keeps growing in real time.
I'd like to stream it to the server to prevent myself from running out of memory.
When there's no more data to be send, I'm leaving 'EndOfBatch' line in the body, so my server gonna know when it should stop listening for ... | [
"Using chunk encoded requests helps.\nimport time\nimport requests as requests\n\n\ndef data_generator():\n yield b\"Foo\"\n time.sleep(5)\n yield b\"Bar\"\n\n\nrequests.post(\"http://127.0.0.1:8085\", data=data_generator())\n\n"
] | [
1
] | [] | [] | [
"python",
"python_requests"
] | stackoverflow_0074560304_python_python_requests.txt |
Q:
IterableWrapper is not defined when using WikiText2
I am trying to follow along this tutorial https://pytorch.org/tutorials/beginner/transformer_tutorial.html
I am getting the following error when calling this function.
----> 6 train_iter = WikiText2(split='train')
/usr/local/lib/python3.7/dist-packages/torchtext/... | IterableWrapper is not defined when using WikiText2 | I am trying to follow along this tutorial https://pytorch.org/tutorials/beginner/transformer_tutorial.html
I am getting the following error when calling this function.
----> 6 train_iter = WikiText2(split='train')
/usr/local/lib/python3.7/dist-packages/torchtext/datasets/wikitext2.py in WikiText2(root, split)
75 ... | [
"I tried running the snippet of code you provided. I don't see\nNameError: name 'IterableWrapper' is not defined\nbut I have a different error which says,\nNo module named 'torchdata'\nI don't have torchdata installed.\nSo in your case, I would make sure if the torchdata is installed correctly.\nYou can look at thi... | [
1
] | [] | [] | [
"python",
"pytorch"
] | stackoverflow_0073590391_python_pytorch.txt |
Q:
Django override save method with changing field value
I need some help with overriding save method with changing field value.
I have such structure:
models.py
class Category(models.Model):
name = models.CharField(max_length=255, validators=[MinLengthValidator(3)])
parent = models.ForeignKey('self', blank=T... | Django override save method with changing field value | I need some help with overriding save method with changing field value.
I have such structure:
models.py
class Category(models.Model):
name = models.CharField(max_length=255, validators=[MinLengthValidator(3)])
parent = models.ForeignKey('self', blank=True, null=True,
related_name... | [
"I found a sollution.\nadmin.py:\nclass ProductAdmin(admin.ModelAdmin):\n ...\n\n def save_related(self, request, form, formsets, change):\n super(ProductAdmin, self).save_related(request, form, formsets, change)\n category = Category.objects.get(id=form.instance.to_category.id)\n form.inst... | [
1
] | [] | [] | [
"django",
"django_admin",
"django_models",
"python"
] | stackoverflow_0074560581_django_django_admin_django_models_python.txt |
Q:
Cannot replace special characters in a Python pandas dataframe
I'm working with Python 3.5 in Windows. I have a dataframe where a 'titles' str type column contains titles of headlines, some of which have special characters such as â,€,˜.
I am trying to replace these with a space '' using pandas.replace. I have t... | Cannot replace special characters in a Python pandas dataframe | I'm working with Python 3.5 in Windows. I have a dataframe where a 'titles' str type column contains titles of headlines, some of which have special characters such as â,€,˜.
I am trying to replace these with a space '' using pandas.replace. I have tried various iterations and nothing works. I am able to replace regu... | [
"We can only assume that you refer to non-ASCI as 'special' characters. \nTo remove all non-ASCI characters in a pandas dataframe column, do the following:\ndf['clean_titles'] = df['titles'].str.replace(r'[^\\x00-\\x7f]', '')\n\nNote that this is a scalable solution as it works for any non-ASCI char. \n",
"How to... | [
4,
0
] | [] | [] | [
"dataframe",
"pandas",
"python",
"regex",
"string"
] | stackoverflow_0050846719_dataframe_pandas_python_regex_string.txt |
Q:
Serializers not working on multiple levels as expected in Django
I have 4 models and 3 serializers.
1 model is a simple through table containing information about which user posted which reaction about which article.
models.py
class User(AbstractUser):
id = models.CharField(max_length=36, default=generate_uni... | Serializers not working on multiple levels as expected in Django | I have 4 models and 3 serializers.
1 model is a simple through table containing information about which user posted which reaction about which article.
models.py
class User(AbstractUser):
id = models.CharField(max_length=36, default=generate_unique_id, primary_key=True)
username = models.CharField(max_length=2... | [
"related_name is useful when you are trying to access reverse relations. For example if you need to acces Reaction from Article object. But in your case you just want to access article details defined inside Reaction model. So you need to use acticle_id field name instead of article_details:\nclass ReactedSerialize... | [
1
] | [] | [] | [
"django",
"python",
"serialization"
] | stackoverflow_0074560615_django_python_serialization.txt |
Q:
BeautifulSoup can't read HTML of the webpage
I want to get real estate data from https://www.realtor.com/
I use this code:
from bs4 import BeautifulSoup as bs
import requests
main_url='https://www.realtor.com/realestateandhomes-search/New-York_NY'
page=requests.get(main_url).content
bs(page,'html.parser')
It do... | BeautifulSoup can't read HTML of the webpage | I want to get real estate data from https://www.realtor.com/
I use this code:
from bs4 import BeautifulSoup as bs
import requests
main_url='https://www.realtor.com/realestateandhomes-search/New-York_NY'
page=requests.get(main_url).content
bs(page,'html.parser')
It does not output the full HTML of the page, so can't ... | [] | [] | [
"import requests\n\nmain_url='https://www.realtor.com/realestateandhomes-search/New-York_NY'\n\npage=requests.get(main_url)\nresults = bs(page.content,'html.parser')\nprint(results)\n\nThis should work\n"
] | [
-2
] | [
"beautifulsoup",
"python",
"web_scraping"
] | stackoverflow_0074560840_beautifulsoup_python_web_scraping.txt |
Q:
Error when joining two time columns with the + operator
Be the following python pandas DataFrame. I want to merge the two columns into one to create the full datetime format.
num_plate_ID cam entry_date entry_time other_columns
0 XYA 2 2022-02-14 23:20:21 ...
1 JDS ... | Error when joining two time columns with the + operator | Be the following python pandas DataFrame. I want to merge the two columns into one to create the full datetime format.
num_plate_ID cam entry_date entry_time other_columns
0 XYA 2 2022-02-14 23:20:21 ...
1 JDS 2 2022-02-12 23:20:21 ...
2 OAP ... | [
"you can use:\ndf['entry'] = pd.to_datetime(df['entry_date'].astype(str) + \" \" + df['entry_time'])\n\n\n"
] | [
1
] | [] | [] | [
"dataframe",
"datetime",
"pandas",
"python"
] | stackoverflow_0074560891_dataframe_datetime_pandas_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.