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:
Pyinstaller is not recognized as an external or internal command, an executable program or a command file
I'm trying to compile a python program that prints "hello world !" with the Pyinstaller module. But when I type the command pyinstaller HelloWorld.pyin my command prompt, it told me "pyinstaller is not recognized as an internal or external command, an executable program or a command file". How can I make compilation works correctly ?
Thank you !
In the HelloWorld.py file, I typed the following command :
print("Hello World !")
In the command prompt, I typed :
pyinstaller HelloWorld.py
This is when I hit the "Enter" key that the error happens.
A:
Simply you can install it using pip.
pip install pyinstaller
Requirements:
3.7-3.11. Note that Python 3.10.0 contains a bug making it unsupportable by PyInstaller. PyInstaller will also not work with beta releases of Python 3.12.
PyInstaller should work on Windows 7 or newer, but it only officially support Windows 8+.
Support for Python installed from the Windows store without using virtual environments requires PyInstaller 4.4 or later.
Note that Windows on arm64 is not yet supported.
|
Pyinstaller is not recognized as an external or internal command, an executable program or a command file
|
I'm trying to compile a python program that prints "hello world !" with the Pyinstaller module. But when I type the command pyinstaller HelloWorld.pyin my command prompt, it told me "pyinstaller is not recognized as an internal or external command, an executable program or a command file". How can I make compilation works correctly ?
Thank you !
In the HelloWorld.py file, I typed the following command :
print("Hello World !")
In the command prompt, I typed :
pyinstaller HelloWorld.py
This is when I hit the "Enter" key that the error happens.
|
[
"Simply you can install it using pip.\npip install pyinstaller\n\nRequirements:\n\n3.7-3.11. Note that Python 3.10.0 contains a bug making it unsupportable by PyInstaller. PyInstaller will also not work with beta releases of Python 3.12.\n\nPyInstaller should work on Windows 7 or newer, but it only officially support Windows 8+.\n\nSupport for Python installed from the Windows store without using virtual environments requires PyInstaller 4.4 or later.\n\nNote that Windows on arm64 is not yet supported.\n\n\n"
] |
[
0
] |
[] |
[] |
[
"pyinstaller",
"python"
] |
stackoverflow_0074499205_pyinstaller_python.txt
|
Q:
Create a scatterplot from the data of two dataframes?
I have two dataframes in python. The content of them is the following:
Table=conn
A B relevance
1 3 0.7
2 7 0.1
5 20 2
6 2 7
table=point
Point Lat Lon
1 45.3 -65.2
2 34.4 -60.2
3 40.2 -60.1
20 40.4 -63.1
In the first table, column A represents an origin, column B a destination and the relevance of the link.
On the other hand, in the second table we have for each point (origin or destination) its coordinates.
The problem is that I want to create a visualization in Python that allows to query the coordinates of each origin or destination (column A and B of the first table) in the second table and make a scatterplot with it. Then, link each of the origins and destinations of the first column taking into account the relevance with thicker lines as it has more relevance.
link refers to the line that joins the points in the graphic representation.
Any idea? I've started with a very basic code approach but I'm really having trouble following along.
for row in conn.interrows():
row[1][0]
row[1][1]
row[1][3]
A:
Do you have two DataFrames: point and conn, right?
# To set indexes of "point" equal to "Points"
point.set_index(point.Point, inplace=True)
# config width of lines
min_width = 0.5
max_width = 4.0
min_relevance = conn.relevance.min()
max_relevance = conn.relevance.max()
slope = (max_width - min_width)/(max_relevance - min_relevance)
widths = min_width + slope*(conn.relevance - min_relevance)
# plot lines
for i in range(len(conn)):
origin = conn.loc[i, 'A']
destin = conn.loc[i, 'B']
lat = point.loc[[origin, destin], 'Lat']
lon = point.loc[[origin, destin], 'Lon']
plt.plot(lat, lon, c='red', lw=widths[i])
# plot points
plt.plot(point.Lat, point.Lon, ls='', marker='o', c='blue')
|
Create a scatterplot from the data of two dataframes?
|
I have two dataframes in python. The content of them is the following:
Table=conn
A B relevance
1 3 0.7
2 7 0.1
5 20 2
6 2 7
table=point
Point Lat Lon
1 45.3 -65.2
2 34.4 -60.2
3 40.2 -60.1
20 40.4 -63.1
In the first table, column A represents an origin, column B a destination and the relevance of the link.
On the other hand, in the second table we have for each point (origin or destination) its coordinates.
The problem is that I want to create a visualization in Python that allows to query the coordinates of each origin or destination (column A and B of the first table) in the second table and make a scatterplot with it. Then, link each of the origins and destinations of the first column taking into account the relevance with thicker lines as it has more relevance.
link refers to the line that joins the points in the graphic representation.
Any idea? I've started with a very basic code approach but I'm really having trouble following along.
for row in conn.interrows():
row[1][0]
row[1][1]
row[1][3]
|
[
"Do you have two DataFrames: point and conn, right?\n# To set indexes of \"point\" equal to \"Points\"\npoint.set_index(point.Point, inplace=True)\n\n# config width of lines\nmin_width = 0.5\nmax_width = 4.0\n\nmin_relevance = conn.relevance.min()\nmax_relevance = conn.relevance.max()\nslope = (max_width - min_width)/(max_relevance - min_relevance)\nwidths = min_width + slope*(conn.relevance - min_relevance)\n\n# plot lines\nfor i in range(len(conn)):\n origin = conn.loc[i, 'A']\n destin = conn.loc[i, 'B']\n lat = point.loc[[origin, destin], 'Lat']\n lon = point.loc[[origin, destin], 'Lon']\n plt.plot(lat, lon, c='red', lw=widths[i])\n\n# plot points\nplt.plot(point.Lat, point.Lon, ls='', marker='o', c='blue')\n\n"
] |
[
0
] |
[] |
[] |
[
"matplotlib",
"python"
] |
stackoverflow_0074496855_matplotlib_python.txt
|
Q:
How to generate SQL using pandas without a database connection?
The pandas package have a method called .to_sql that help to insert the current data frame on to the database.
.to_sql doc:
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_sql.html
The second parameter is con
sqlalchemy.engine.(Engine or Connection) or sqlite3.Connection
Is it possible to generate the SQL query without passing a database connection?
A:
We actually cannot print the query without a database connection, but we can use sqlalchemy create_mock_engine method and pass "memory" as the database URI to trick pandas, e.g:
from sqlalchemy import create_mock_engine, Metadata
def dump(sql, *multiparams, **params):
print(sql.compile(dialect=engine.dialect))
engine = create_mock_engine("sqlite://:memory:", echo=True)
Metadata.create_all(engine, checkfirst=False)
frame.to_sql(engine)
|
How to generate SQL using pandas without a database connection?
|
The pandas package have a method called .to_sql that help to insert the current data frame on to the database.
.to_sql doc:
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_sql.html
The second parameter is con
sqlalchemy.engine.(Engine or Connection) or sqlite3.Connection
Is it possible to generate the SQL query without passing a database connection?
|
[
"We actually cannot print the query without a database connection, but we can use sqlalchemy create_mock_engine method and pass \"memory\" as the database URI to trick pandas, e.g:\nfrom sqlalchemy import create_mock_engine, Metadata\n\ndef dump(sql, *multiparams, **params):\n print(sql.compile(dialect=engine.dialect))\n\nengine = create_mock_engine(\"sqlite://:memory:\", echo=True)\nMetadata.create_all(engine, checkfirst=False)\n\nframe.to_sql(engine)\n\n"
] |
[
0
] |
[] |
[] |
[
"pandas",
"python"
] |
stackoverflow_0074478112_pandas_python.txt
|
Q:
How to find the root of a function within a range in python
I need to find the alpha value in [0,1] of a linear combination alpha*Id+(1-alpha)*M, where Id is the identity matrix, M is a given matrix, such that this linear combination has given mean.
At the moment I am using scipyt.optimize.fsolve but it does not admit the range [0,1] as an input. Any suggestion ?
A:
You can define alpha using a sigmoid function:
alpha = 1/(1+exp(-x))
https://en.wikipedia.org/wiki/Sigmoid_function
Based on this definition, alpha will always be in the range [0, 1]. Then, you can change the target of the optimization in scipy.optimize.fsolve to calibrate the value of x instead of alpha directly.
The variable x is free of constraints, so any optimization method works.
PS. This technique is very common in machine learning.
PS2. Adding constraints to an optimizer is only important when they are not being fulfilled. So for example, if your alpha solution is already in the range [0,1], then you can keep the optimizer as it is.
|
How to find the root of a function within a range in python
|
I need to find the alpha value in [0,1] of a linear combination alpha*Id+(1-alpha)*M, where Id is the identity matrix, M is a given matrix, such that this linear combination has given mean.
At the moment I am using scipyt.optimize.fsolve but it does not admit the range [0,1] as an input. Any suggestion ?
|
[
"You can define alpha using a sigmoid function:\nalpha = 1/(1+exp(-x))\n\nhttps://en.wikipedia.org/wiki/Sigmoid_function\nBased on this definition, alpha will always be in the range [0, 1]. Then, you can change the target of the optimization in scipy.optimize.fsolve to calibrate the value of x instead of alpha directly.\nThe variable x is free of constraints, so any optimization method works.\n\nPS. This technique is very common in machine learning.\n\nPS2. Adding constraints to an optimizer is only important when they are not being fulfilled. So for example, if your alpha solution is already in the range [0,1], then you can keep the optimizer as it is.\n"
] |
[
0
] |
[] |
[] |
[
"fsolve",
"python",
"scipy"
] |
stackoverflow_0074499258_fsolve_python_scipy.txt
|
Q:
Regular expression to find from the end of string
I have a few strings, like:
address1 = 'Красноярский край, г Красноярск, ул Академика Вавилова, 2Д, кв. 311'
address2 = 'Москва г, ул Ольховская, 45 стр. 1, квартира 3'
address3 = 'Красноярский край, г Красноярск, ул Академика Вавилова, 2Д, квартира 311'
So I need to cut that piece of string, which start from кв.
I use regular expression and this my code:
import re
flat_template = r"кв(.*)$"
flat1 = re.search(flat_template, address1)
flat2 = re.search(flat_template, address2)
flat3 = re.search(flat_template, address3)
cut_flat1 = addresses[flat.start():flat.end()]
cut_flat2 = addresses[flat.start():flat.end()]
cut_flat3 = addresses[flat.start():flat.end()]
Output:
cut_flat1 = 'кв. 311'
cut_flat2 = 'ква г, ул Ольховская, 45 стр. 1, квартира 3'
cut_flat3 = 'квартира 311'
But I want to get:
cut_flat1 = 'кв. 311'
cut_flat2 = 'квартира 3'
cut_flat3 = 'квартира 311'
All what I want to is search from end of string
A:
Regular expressions usually are "greedy": they try to match as many characters as possible. That is what you see in your results.
You can make them non-greedy instead:
flat_template = r"кв(.*?)$"
Note the use of .*? for the non-greedy variant of .*. This will match the minum number of characters possible.
To make sure "кв" matches the beginning of a word, use a word boundary: '\b':
flat_template = r"\bкв(.*?)$"
A:
I solve especially my problem. I have added space before ' кв'.
So my code
flat_template = r" кв(.*?)$"
|
Regular expression to find from the end of string
|
I have a few strings, like:
address1 = 'Красноярский край, г Красноярск, ул Академика Вавилова, 2Д, кв. 311'
address2 = 'Москва г, ул Ольховская, 45 стр. 1, квартира 3'
address3 = 'Красноярский край, г Красноярск, ул Академика Вавилова, 2Д, квартира 311'
So I need to cut that piece of string, which start from кв.
I use regular expression and this my code:
import re
flat_template = r"кв(.*)$"
flat1 = re.search(flat_template, address1)
flat2 = re.search(flat_template, address2)
flat3 = re.search(flat_template, address3)
cut_flat1 = addresses[flat.start():flat.end()]
cut_flat2 = addresses[flat.start():flat.end()]
cut_flat3 = addresses[flat.start():flat.end()]
Output:
cut_flat1 = 'кв. 311'
cut_flat2 = 'ква г, ул Ольховская, 45 стр. 1, квартира 3'
cut_flat3 = 'квартира 311'
But I want to get:
cut_flat1 = 'кв. 311'
cut_flat2 = 'квартира 3'
cut_flat3 = 'квартира 311'
All what I want to is search from end of string
|
[
"Regular expressions usually are \"greedy\": they try to match as many characters as possible. That is what you see in your results.\nYou can make them non-greedy instead:\nflat_template = r\"кв(.*?)$\"\n\nNote the use of .*? for the non-greedy variant of .*. This will match the minum number of characters possible.\nTo make sure \"кв\" matches the beginning of a word, use a word boundary: '\\b':\nflat_template = r\"\\bкв(.*?)$\"\n\n",
"I solve especially my problem. I have added space before ' кв'.\nSo my code\nflat_template = r\" кв(.*?)$\"\n\n"
] |
[
1,
0
] |
[] |
[] |
[
"python",
"qregularexpression",
"search"
] |
stackoverflow_0074498977_python_qregularexpression_search.txt
|
Q:
pydantic root validation get inconsistent data
I write some project on FastAPI + ormar, and there is a problem with PATCH method of my API endpoint. Briafly (without try-excepts and checks for ids), my PATCH logic is the following:
new_product_values = new_product.dict(
exclude_unset=True,
exclude_none=True,
)
db_product = await Product.objects.get_or_none(pk=product_id)
product = await db_product.update(**new_product_values) # update cause validation and inside it cause ValidationError
product_id is query_parameter and new_product is pydantic model (optional version of my ormar model) from request body.
So, Product model has the following validator, in which ValidationError is raised in my case:
@validator("fat", "protein", "carbohyd")
@classmethod
def nutrients_min_value(cls, value: float) -> float:
"""Check nutrient 0 < value < product_base_weight.
Args:
value (float): nutrient (fat, protein or carbohyd) of product.
Returns:
float: nutrient (fat, protein or carbohyd) of product.
"""
assert (
0 <= value <= PRODUCT_BASE_WEIGHT
), f"Nutrient amount must be in range [0...{PRODUCT_BASE_WEIGHT}]"
return value
@root_validator
@classmethod
def nutrient_sum_constraint(cls, values: dict[str, int | str | float | bool]):
"""Validate nutrient sum.
Args:
values (dict): Product as dict.
Returns:
dict: Product as dict.
"""
fat: float = values.get("fat") # type: ignore
protein: float = values.get("protein") # type: ignore
carbohyd: float = values.get("carbohyd") # type: ignore
assert (
0 <= fat + protein + carbohyd <= PRODUCT_BASE_WEIGHT
), f"Total weight of fat, protein and carbohyd must be in range [0...{PRODUCT_BASE_WEIGHT}]"
return values
This root_validator is needed to check, if sum of nutrients in product (always 100g weight) is bigger and equal than 0 and less and equal than 100. (it is impossible to have weight of nutrients bigger than product weight itself). (+ I've added one another validator, because it will be needed below).
I passed the following json in my patch endpoint: {"fat": 26, "carbohyd": 49} (initial values of product was the following {"fat": 25, "carbohyd": 50, "protein": 25}, which sum is equal to 100, and its correct), but patch request fail, because carbohyd value, when it checks in root_validator still equal to 50, but fat value is already equal to 26, and further sum will be 101, that is bigger than 100.
It means, that root_validation triggers inside pydantic model logic too early, so not all values were passed in it.
debug show me, that update method cause all model validation, but root_validation causes not after all other validations (nutrients_min_value for all nutrients), but right after fat validation in nutrient_min_value. What should I do?
A:
You are right, the problem stems from the fact that update calls the update_from_dict method, which just calls setattr in a loop for each key-value-pair.
Whether or not this should be considered a bug depends on the goals behind the Pydantic integration. I am not particularly familiar with ormar. I suppose this may be worth a feature request though.
A workaround for the time being is initializing an entirely new instance of your model with the updated data and using the upsert method. This should accomplish, what you want.
Here is a full working example:
from asyncio import run
from databases import Database
from ormar import Integer, Model, NoMatch
from pydantic import ValidationError, root_validator
from sqlalchemy import MetaData, create_engine
DB_URL = "sqlite:///test.db"
_db = Database(DB_URL)
_meta = MetaData()
class Foo(Model):
class Meta:
metadata = _meta
database = _db
tablename = "foo"
id: int = Integer(primary_key=True)
a: int = Integer(minimum=0, maximum=100)
b: int = Integer(minimum=0, maximum=100)
c: int = Integer(minimum=0, maximum=100)
@root_validator
def sum_constraint(cls, values: dict[str, int]) -> dict[str, int]:
assert 0 <= sum((
values["a"],
values["b"],
values["c"],
)) <= 100, "Sum of `a`, `b`, and `c` must be in [0..100]"
return values
async def patch_handler(pk: int, data: dict[str, int]) -> Foo:
try:
obj = await Foo.objects.get(pk=pk)
except NoMatch:
pass
else:
data = obj.dict() | data
new_obj = Foo(**data)
await new_obj.upsert()
return new_obj
async def main() -> None:
engine = create_engine(DB_URL)
_meta.drop_all(engine)
_meta.create_all(engine)
await Foo.objects.create(a=25, b=50, c=25)
data = {"a": 26, "b": 49}
new_obj = await patch_handler(1, data)
print(new_obj)
data = {"a": 27}
try:
await patch_handler(1, data)
except ValidationError as e:
print(e)
if __name__ == "__main__":
run(main())
The output:
id=1 a=26 b=49 c=25
1 validation error for Foo
__root__
Sum of `a`, `b`, and `c` must be in [0..100] (type=assertion_error)
A few more things to note:
The classmethod decorator is redundant, when you are using Pydantic validator or root_validator decorators.
Unless there are other things you are doing with that first field validator in your example, you may be better off simply using the built-in maximum and minimum parameters for the Integer field class. Also that docstring description is not congruent with your assertion since you write about <, but actually use <=.
The order of dictionary merging (via |) inside the patch_handler function is important because data = obj.dict() | data ensures that the values passed via data overwrite what is returned by the dict method from the existing object. This is why we cannot just do data |= obj.dict().
Instead of using that try-except-else-construct, you can also use the get_or_none method as before and then do an if ... is None-check or something to that effect. Matter of personal preference.
|
pydantic root validation get inconsistent data
|
I write some project on FastAPI + ormar, and there is a problem with PATCH method of my API endpoint. Briafly (without try-excepts and checks for ids), my PATCH logic is the following:
new_product_values = new_product.dict(
exclude_unset=True,
exclude_none=True,
)
db_product = await Product.objects.get_or_none(pk=product_id)
product = await db_product.update(**new_product_values) # update cause validation and inside it cause ValidationError
product_id is query_parameter and new_product is pydantic model (optional version of my ormar model) from request body.
So, Product model has the following validator, in which ValidationError is raised in my case:
@validator("fat", "protein", "carbohyd")
@classmethod
def nutrients_min_value(cls, value: float) -> float:
"""Check nutrient 0 < value < product_base_weight.
Args:
value (float): nutrient (fat, protein or carbohyd) of product.
Returns:
float: nutrient (fat, protein or carbohyd) of product.
"""
assert (
0 <= value <= PRODUCT_BASE_WEIGHT
), f"Nutrient amount must be in range [0...{PRODUCT_BASE_WEIGHT}]"
return value
@root_validator
@classmethod
def nutrient_sum_constraint(cls, values: dict[str, int | str | float | bool]):
"""Validate nutrient sum.
Args:
values (dict): Product as dict.
Returns:
dict: Product as dict.
"""
fat: float = values.get("fat") # type: ignore
protein: float = values.get("protein") # type: ignore
carbohyd: float = values.get("carbohyd") # type: ignore
assert (
0 <= fat + protein + carbohyd <= PRODUCT_BASE_WEIGHT
), f"Total weight of fat, protein and carbohyd must be in range [0...{PRODUCT_BASE_WEIGHT}]"
return values
This root_validator is needed to check, if sum of nutrients in product (always 100g weight) is bigger and equal than 0 and less and equal than 100. (it is impossible to have weight of nutrients bigger than product weight itself). (+ I've added one another validator, because it will be needed below).
I passed the following json in my patch endpoint: {"fat": 26, "carbohyd": 49} (initial values of product was the following {"fat": 25, "carbohyd": 50, "protein": 25}, which sum is equal to 100, and its correct), but patch request fail, because carbohyd value, when it checks in root_validator still equal to 50, but fat value is already equal to 26, and further sum will be 101, that is bigger than 100.
It means, that root_validation triggers inside pydantic model logic too early, so not all values were passed in it.
debug show me, that update method cause all model validation, but root_validation causes not after all other validations (nutrients_min_value for all nutrients), but right after fat validation in nutrient_min_value. What should I do?
|
[
"You are right, the problem stems from the fact that update calls the update_from_dict method, which just calls setattr in a loop for each key-value-pair.\nWhether or not this should be considered a bug depends on the goals behind the Pydantic integration. I am not particularly familiar with ormar. I suppose this may be worth a feature request though.\nA workaround for the time being is initializing an entirely new instance of your model with the updated data and using the upsert method. This should accomplish, what you want.\nHere is a full working example:\nfrom asyncio import run\nfrom databases import Database\nfrom ormar import Integer, Model, NoMatch\nfrom pydantic import ValidationError, root_validator\nfrom sqlalchemy import MetaData, create_engine\n\n\nDB_URL = \"sqlite:///test.db\"\n_db = Database(DB_URL)\n_meta = MetaData()\n\n\nclass Foo(Model):\n class Meta:\n metadata = _meta\n database = _db\n tablename = \"foo\"\n\n id: int = Integer(primary_key=True)\n a: int = Integer(minimum=0, maximum=100)\n b: int = Integer(minimum=0, maximum=100)\n c: int = Integer(minimum=0, maximum=100)\n\n @root_validator\n def sum_constraint(cls, values: dict[str, int]) -> dict[str, int]:\n assert 0 <= sum((\n values[\"a\"],\n values[\"b\"],\n values[\"c\"],\n )) <= 100, \"Sum of `a`, `b`, and `c` must be in [0..100]\"\n return values\n\n\nasync def patch_handler(pk: int, data: dict[str, int]) -> Foo:\n try:\n obj = await Foo.objects.get(pk=pk)\n except NoMatch:\n pass\n else:\n data = obj.dict() | data\n new_obj = Foo(**data)\n await new_obj.upsert()\n return new_obj\n\n\nasync def main() -> None:\n engine = create_engine(DB_URL)\n _meta.drop_all(engine)\n _meta.create_all(engine)\n await Foo.objects.create(a=25, b=50, c=25)\n data = {\"a\": 26, \"b\": 49}\n new_obj = await patch_handler(1, data)\n print(new_obj)\n data = {\"a\": 27}\n try:\n await patch_handler(1, data)\n except ValidationError as e:\n print(e)\n\n\nif __name__ == \"__main__\":\n run(main())\n\nThe output:\n\nid=1 a=26 b=49 c=25\n1 validation error for Foo\n__root__\n Sum of `a`, `b`, and `c` must be in [0..100] (type=assertion_error)\n\nA few more things to note:\n\nThe classmethod decorator is redundant, when you are using Pydantic validator or root_validator decorators.\nUnless there are other things you are doing with that first field validator in your example, you may be better off simply using the built-in maximum and minimum parameters for the Integer field class. Also that docstring description is not congruent with your assertion since you write about <, but actually use <=.\nThe order of dictionary merging (via |) inside the patch_handler function is important because data = obj.dict() | data ensures that the values passed via data overwrite what is returned by the dict method from the existing object. This is why we cannot just do data |= obj.dict().\nInstead of using that try-except-else-construct, you can also use the get_or_none method as before and then do an if ... is None-check or something to that effect. Matter of personal preference.\n\n"
] |
[
0
] |
[] |
[] |
[
"fastapi",
"pydantic",
"python",
"validation"
] |
stackoverflow_0074477395_fastapi_pydantic_python_validation.txt
|
Q:
Python - set attributes dynamically in for loop
I have the following code:
class Test:
pass
test = Test()
for x in ["a", "b", "c"]:
test.x = x
print(test.__dict__)
{'x': 'c'}
This is not what I want. What I want is to set the name of the attribute corresponding to the value of the iteration:
Desired:
print(test.__dict__)
{'a': 'a', 'b': 'b', 'c': 'c'}
How can I do that?
A:
Use setattr
class Test:
pass
test = Test()
for x in ["a", "b", "c"]:
setattr(test,x,x)
print(test.__dict__)
|
Python - set attributes dynamically in for loop
|
I have the following code:
class Test:
pass
test = Test()
for x in ["a", "b", "c"]:
test.x = x
print(test.__dict__)
{'x': 'c'}
This is not what I want. What I want is to set the name of the attribute corresponding to the value of the iteration:
Desired:
print(test.__dict__)
{'a': 'a', 'b': 'b', 'c': 'c'}
How can I do that?
|
[
"Use setattr\nclass Test:\n pass\n\ntest = Test()\n\nfor x in [\"a\", \"b\", \"c\"]:\n setattr(test,x,x)\n \nprint(test.__dict__)\n\n"
] |
[
2
] |
[] |
[] |
[
"oop",
"python"
] |
stackoverflow_0074499396_oop_python.txt
|
Q:
Get more speed in pandas Dataframe
I wrote this code to get the stock market data and after getting the data, I save it in the Mongo database, then I get the required data from the Mongo database and convert it into a dataframe.
Using the data in the rows, I calculate the values I need. This operation takes about 35 seconds. I need this operation to be done in the shortest possible time, the less the better.
Thank you for your guidance
%%time
from scipy.stats import norm
import numpy as np
import math
import requests
import pandas as pd
import jdatetime
import json
import time
import pymongo
start = time.time()
client = pymongo.MongoClient()
database = client['raw']
cursor = database.list_collection_names()
cursor.sort()`your text`
Raw = database[cursor[-1]]
data = pd.DataFrame(Raw.find())
df = data[["tse_url", "l18", "l30", 'pc', 'pl', 'tno', 'tvol', 'tval', 'py', 'stock']]
option = df.loc[df['stock'].isin(['311', '312', '320', '321'])]
db = client['transaction']
dbCol = db.list_collection_names()
dbCol.sort()
Trans = db[dbCol[-1]]
trans = pd.DataFrame(Trans.find({}, {"tse_url", "row", "buy", 'sell'}))
trans = trans.drop('_id',axis=1)
trans = trans.loc[trans['row'] == '1']
binazir = client['binazir']
lst = binazir.list_collection_names()
lst.sort()
latest = binazir[lst[-1]]
OC = pd.DataFrame(latest.find({}, {"tse_url", "open_positions", "contract_size"}))
option.insert(3, 'contract', '')
option.insert(3, 'blackscholes', '')
option.insert(3, 'open', '')
option.insert(3, '%t', '')
option.insert(3, 'through', '')
option.insert(3, '%pc', '')
option.insert(3, '%pl', '')
option.insert(3, 's1', '')
option.insert(3, 'b1', '')
option.insert(3, 'mature', '')
option.insert(3, 'status', '')
option.insert(3, 'bp', '')
option.insert(3, 'strike', '')
option.insert(3, 'volatility', '')
option.insert(3, 'SellBS', '')
option.insert(3, 'BuyBS', '')
option.insert(3, 'lever', '')
option.insert(3, 'delta', '')
option.insert(3, 'deltaLever', '')
option.insert(3, 'vega', '')
option.insert(3, 'theta', '')
option.insert(3, 'gamma', '')
option.insert(3, 'rho', '')
option.insert(3, 'margin', '')
option.insert(3, 'undif', '')
for a in zip(option['tse_url'], option.index):
for b in zip(trans['tse_url'], trans['buy'], trans['sell']):
if a[0] == b[0]:
option.at[a[1], 's1'] = b[2]
option.at[a[1], 'b1'] = b[1]
for a in zip(option['l30'], option.index):
x = a[0].split('-')
option.at[a[1], 'strike'] = x[1]
namad = x[0][8:]
if x[2].startswith('00'):
date = x[2].replace('00', '1400')
elif x[2].startswith('01'):
date = x[2].replace('01', '1401')
else:
date = x[2]
if date[4] == '/':
today = jdatetime.datetime.strptime(jdatetime.datetime.now().strftime("%Y%m%d"), "%Y%m%d")
mature = (jdatetime.datetime.strptime((date.replace('/', '')), "%Y%m%d") - today).days
option.at[a[1], 'mature'] = mature
else:
today = jdatetime.datetime.strptime(jdatetime.datetime.now().strftime("%Y%m%d"), "%Y%m%d")
mature = (jdatetime.datetime.strptime(date, "%Y%m%d") - today).days
option.at[a[1], 'mature'] = mature
x = namad.replace("هموزن", "هم وزن")
y = x.replace("حافرين", "حآفرين")
z = y.replace("ص.دارا", "دارا")
for d in zip(data['l18'], data['pc'], data['tse_url']):
if z == d[0]:
option.at[a[1], 'bp'] = d[1]
option.at[a[1], 'StockName'] = z
option.at[a[1], 'StockURL'] = d[2]
for a in zip(option['bp'], option['strike'], option['stock'], option.index):
if a[2] == '311' or a[2] == '320':
if int(a[0]) > int(a[1]):
option.at[a[3], 'status'] = 'ITM'
elif int(a[0]) < int(a[1]):
option.at[a[3], 'status'] = 'OTM'
else:
option.at[a[3], 'status'] = 'ATM'
else:
if int(a[0]) < int(a[1]):
option.at[a[3], 'status'] = 'ITM'
elif int(a[0]) > int(a[1]):
option.at[a[3], 'status'] = 'OTM'
else:
option.at[a[3], 'status'] = 'ATM'
for a in zip(option['pl'], option['strike'], option['s1'], option.index, option['bp'], option['stock']):
if a[5] == '311' or a[5] == '320':
if a[2] == '0':
t = (int(a[0]) + int(a[1]))
option.at[a[3], 'through'] = t
else:
t = (int(a[2]) + int(a[1]))
option.at[a[3], 'through'] = t
else:
if a[2] == '0':
t = (int(a[1]) - int(a[0]))
option.at[a[3], 'through'] = t
else:
t = (int(a[1]) - int(a[2]))
option.at[a[3], 'through'] = t
pt = (t - int(a[4])) / int(a[4]) * 100
option.at[a[3], '%t'] = round(pt, 2)
for a in zip(option['tse_url'], option.index):
for b in zip(OC['tse_url'],OC["open_positions"], OC["contract_size"]):
if a[0] == b[0]:
option.at[a[1], 'open'] = b[1]
option.at[a[1], 'contract'] = b[2]
else:
option.at[a[1], 'open'] = 0
option.at[a[1], 'contract'] = 1000
for a in zip(option['pl'], option['pc'], option['py'], option.index):
option.at[a[3], '%pl'] = round((int(a[0]) - int(a[2])) / int(a[2]) * 100, 2)
option.at[a[3], '%pc'] = round((int(a[1]) - int(a[2])) / int(a[2]) * 100, 2)
_list = set()
for a in zip(option['StockURL']):
_list.add(a[0])
for b in _list:
col = {
0: 'ticker',
1: 'date',
2: 'first',
3: 'high',
4: 'low',
5: 'close',
6: 'value',
7: 'vol',
8: 'openint',
9: 'per',
10: 'open',
11: 'last',
}
url = 'http://www.tsetmc.com/tsev2/data/Export-txt.aspx?t=i&a=1&b=0&i=%s' % str(b)
r = requests.get(url)
main_text = r.text
df = pd.DataFrame([x.split(',') for x in main_text.split('\r\n')]).drop(0, axis=0)
data = df.rename(columns=col)
dd = data.drop(['ticker',
'date',
'first',
'high',
'low',
'value',
'vol',
'openint',
'per',
'open',
'last', ], axis=1)
dd['close'] = dd['close'].astype('float')
dd.at[dd.index, 'closen'] = dd['close'].shift(-1).astype('float')
for i in zip(dd['close'], dd['closen'], dd.index):
ln = 100 * math.log(i[0] / i[1])
dd.at[i[2], 'ln'] = ln
dd.drop(dd.loc[dd['ln'] >= 10].index, inplace=True)
dd.drop(dd.loc[dd['ln'] <= -10].index, inplace=True)
cc = dd.dropna(axis=0, how='any', thresh=None, subset=None, inplace=False)
ff = cc.iloc[:132]
volatility = (np.std(ff['ln'], ddof=1)) * math.sqrt(245)
for p in zip(option['StockURL'], option.index):
if p[0] == b:
option.at[p[1], 'volatility'] = round(volatility, 1)
for a in zip(option['strike'], option['bp'], option['mature'], option['volatility'], option['stock'], option.index,option['pl'], option['s1']):
S = int(a[1])
K = int(a[0])
T = int(a[2])
r = 0.25
sigma = float(a[3]) / 100
q = 0
if T == 0:
d1 = 0
else:
d1 = (math.log(S / K) + ((r - q + (0.5 * (sigma ** 2))) * T / 365)) / (sigma * math.sqrt(T / 365))
d2 = (d1 - sigma * math.sqrt(T / 365))
if T == 0:
t1 = 0
else:
t1 = (np.log(S/K) + (r + sigma**2/2)* T)/(sigma*np.sqrt(T))
t2 = d1 - sigma * np.sqrt(T)
Nd1 = math.exp(-(d1**2) / 2)/math.sqrt(2*3.14)
option.at[a[5], 'gamma'] = round(Nd1 * math.exp(-q*T)/S*sigma*T**0.5)
option.at[a[5], 'vega'] = round(S*T**0.5*Nd1)
if a[2] == 0 and K >= S:
option.at[a[5], 'blackscholes'] = 0
elif a[2] == 0 and K < S:
option.at[a[5], 'blackscholes'] = S - K
else:
if a[4] == '311' or a[4] == '320':
call = (S * math.exp(-q * T / 365) * norm.cdf(d1) - K * math.exp(-r * T / 365) * norm.cdf(d2))
deltaCall = norm.cdf(d1)
option.at[a[5], 'blackscholes'] = round(call)
option.at[a[5], 'delta'] = round(deltaCall, 4)
option.at[a[5], 'rho'] = round(K*T*math.exp(-r*T)*norm.cdf(d2), 4)
option.at[a[5], 'theta'] = round(1/365*(-(S*sigma*math.exp(-q*T)*Nd1/2*T**0.5)-r*K*math.exp(-r*T)*norm.cdf(d2)+q*S*math.exp(-q*T)*norm.cdf(d1)), 4)
if int(a[7]) == 0:
option.at[a[5], 'deltaLever'] = round(S*deltaCall - int(a[6])/int(a[6]),2)
else:
option.at[a[5], 'deltaLever'] = round(S*deltaCall - int(a[7])/int(a[7]),2)
else:
put = (K * math.exp(-r * T / 365) * norm.cdf(-1 * d2) - S * math.exp(-q * T / 365) * norm.cdf(-1 * d1))
deltaPut = norm.cdf(d1)-1
option.at[a[5], 'blackscholes'] = round(put)
option.at[a[5], 'delta'] = round(deltaPut, 4)
option.at[a[5], 'rho'] = round(-K*T*math.exp(-r*T)*norm.cdf(-d2), 4)
option.at[a[5], 'theta'] = round(1/365*(-(S*sigma*math.exp(-q*T)*Nd1/2*T**0.5)+r*K*math.exp(-r*T)*norm.cdf(-d2)-q*S*math.exp(-q*T)*norm.cdf(-d1)), 4)
if int(a[7]) == 0:
option.at[a[5], 'deltaLever'] = round(S*deltaPut - int(a[6])/int(a[6]),2)
else:
option.at[a[5], 'deltaLever'] = round(S*deltaPut - int(a[7])/int(a[7]),2)
for a in zip(option['s1'], option['blackscholes'], option['pl'], option.index):
if int(a[0]) == 0 and int(a[1]) == 0:
option.at[a[3], 'SellBS'] = 0
elif int(a[0]) == 0 and int(a[1]) != 0:
option.at[a[3], 'SellBS'] = "بدون فروشنده"
elif int(a[0]) != 0 and int(a[1]) == 0:
option.at[a[3], 'SellBS'] = round(int(a[0]) * 100, 2)
else:
option.at[a[3], 'SellBS'] = round(((int(a[0]) - int(a[1])) / int(a[1])) * 100, 2)
for a in zip(option['b1'], option['blackscholes'], option['pl'], option.index):
if int(a[0]) == 0 and int(a[1]) == 0:
option.at[a[3], 'BuyBS'] = 0
elif int(a[0]) == 0 and int(a[1]) != 0:
option.at[a[3], 'BuyBS'] = "بدون خریدار"
elif int(a[0]) != 0 and int(a[1]) == 0:
option.at[a[3], 'BuyBS'] = round(int(a[0]) * 100, 2)
else:
option.at[a[3], 'BuyBS'] = round(((int(a[0]) - int(a[1])) / int(a[1])) * 100, 2)
for a in zip(option['s1'], option['strike'], option['pl'], option.index):
if int(a[0]) == 0:
option.at[a[3], 'lever'] = round((int(a[1]) / int(a[2])), 2)
else:
option.at[a[3], 'lever'] = round((int(a[1]) / int(a[0])), 2)
for a in zip(option['strike'], option['bp'], option['stock'], option.index,option['pl'], option['s1'], option['contract']):
if a[2] == '311' or a[2] == '320':
l = abs(min(int(a[1]) - int(a[0]), 0)) * int(a[6])
I1 = 0.2 * int(a[1]) * int(a[6]) - l
I2 = 0.1 * int(a[0]) * int(a[6])
V1 = (math.floor(max(I1, I2) / 100000) + 1) * 100000
if a[5] != '0':
V2 = int(a[5]) * int(a[6])
M = V1 + V2
option.at[a[3],'margin']=round(M)
option.at[a[3],'undif']= round(int(a[0])/int(a[5])-int(a[1]) - 1, 4)*100
else:
V2 = int(a[4]) * int(a[6])
M = V1 + V2
option.at[a[3],'margin']=round(M)
option.at[a[3],'undif']= round(int(a[0])/int(a[4])-int(a[1]) - 1, 4)*100
else:
l = abs(int(a[0]) - min(int(a[1]), 0)) * int(a[6])
I1 = 0.2 * int(a[1]) * int(a[6]) - l
I2 = 0.1 * int(a[0]) * int(a[6])
V1 = (math.floor(max(I1, I2) / 100000) + 1) * 100000
if a[5] != '0':
V2 = int(a[5]) * int(a[6])
M = V1 + V2
option.at[a[3],'margin']=round(M)
option.at[a[3],'undif']= round(int(a[0])/int(a[5])-int(a[1]) - 1, 4)*100
else:
V2 = int(a[4]) * int(a[6])
M = V1 + V2
option.at[a[3],'margin']=round(M)
option.at[a[3],'undif']= round(int(a[0])/int(a[4])-int(a[1]) - 1, 4)*100
end = time.time()
print(end - start)
I need to reduce the execution time of this code to the lowest possible time, but currently it takes about 35 seconds.
A:
Your code is slow because of all those loops. It is way outside the scope of a single question and answer to actually fix all that code, but I can tell you how to fix it:
Profile each part. Break the code down into steps, perhaps into functions or just time each outer loop. This will tell you where to spend your time optimizing.
Figure out how to use Pandas and NumPy in a "vectorized" way. This means instead of looping over each row of a DataFrame, find an equivalent operation you can apply to all rows at once. For example if you need to multiply one column by another, just say df['A'] * df['B'] to get the entire resulting series at once, instead of using a for loop to populate one cell at a time. By using vectorized operations, your program will mostly execute compiled library code which is highly optimized, rather than slow Python code.
If there is a part which is not amenable to vectorization, use Numba. Numba is a just-in-time compiler for NumPy, and it can wrap a Python function into a callable object which compiles the code the first time it's called so that it will execute as quickly as possible (as if you wrote the code in C or C++, in some cases).
Walk before you run. Isolate the smallest piece of your code which takes a significant amount of time, put its inputs into a text file so you can easily reload them, and experiment. Don't try to optimize the entire program at once, if it takes 35 seconds every time you try something, you'll never finish. Separating your code into well-defined functions will help.
|
Get more speed in pandas Dataframe
|
I wrote this code to get the stock market data and after getting the data, I save it in the Mongo database, then I get the required data from the Mongo database and convert it into a dataframe.
Using the data in the rows, I calculate the values I need. This operation takes about 35 seconds. I need this operation to be done in the shortest possible time, the less the better.
Thank you for your guidance
%%time
from scipy.stats import norm
import numpy as np
import math
import requests
import pandas as pd
import jdatetime
import json
import time
import pymongo
start = time.time()
client = pymongo.MongoClient()
database = client['raw']
cursor = database.list_collection_names()
cursor.sort()`your text`
Raw = database[cursor[-1]]
data = pd.DataFrame(Raw.find())
df = data[["tse_url", "l18", "l30", 'pc', 'pl', 'tno', 'tvol', 'tval', 'py', 'stock']]
option = df.loc[df['stock'].isin(['311', '312', '320', '321'])]
db = client['transaction']
dbCol = db.list_collection_names()
dbCol.sort()
Trans = db[dbCol[-1]]
trans = pd.DataFrame(Trans.find({}, {"tse_url", "row", "buy", 'sell'}))
trans = trans.drop('_id',axis=1)
trans = trans.loc[trans['row'] == '1']
binazir = client['binazir']
lst = binazir.list_collection_names()
lst.sort()
latest = binazir[lst[-1]]
OC = pd.DataFrame(latest.find({}, {"tse_url", "open_positions", "contract_size"}))
option.insert(3, 'contract', '')
option.insert(3, 'blackscholes', '')
option.insert(3, 'open', '')
option.insert(3, '%t', '')
option.insert(3, 'through', '')
option.insert(3, '%pc', '')
option.insert(3, '%pl', '')
option.insert(3, 's1', '')
option.insert(3, 'b1', '')
option.insert(3, 'mature', '')
option.insert(3, 'status', '')
option.insert(3, 'bp', '')
option.insert(3, 'strike', '')
option.insert(3, 'volatility', '')
option.insert(3, 'SellBS', '')
option.insert(3, 'BuyBS', '')
option.insert(3, 'lever', '')
option.insert(3, 'delta', '')
option.insert(3, 'deltaLever', '')
option.insert(3, 'vega', '')
option.insert(3, 'theta', '')
option.insert(3, 'gamma', '')
option.insert(3, 'rho', '')
option.insert(3, 'margin', '')
option.insert(3, 'undif', '')
for a in zip(option['tse_url'], option.index):
for b in zip(trans['tse_url'], trans['buy'], trans['sell']):
if a[0] == b[0]:
option.at[a[1], 's1'] = b[2]
option.at[a[1], 'b1'] = b[1]
for a in zip(option['l30'], option.index):
x = a[0].split('-')
option.at[a[1], 'strike'] = x[1]
namad = x[0][8:]
if x[2].startswith('00'):
date = x[2].replace('00', '1400')
elif x[2].startswith('01'):
date = x[2].replace('01', '1401')
else:
date = x[2]
if date[4] == '/':
today = jdatetime.datetime.strptime(jdatetime.datetime.now().strftime("%Y%m%d"), "%Y%m%d")
mature = (jdatetime.datetime.strptime((date.replace('/', '')), "%Y%m%d") - today).days
option.at[a[1], 'mature'] = mature
else:
today = jdatetime.datetime.strptime(jdatetime.datetime.now().strftime("%Y%m%d"), "%Y%m%d")
mature = (jdatetime.datetime.strptime(date, "%Y%m%d") - today).days
option.at[a[1], 'mature'] = mature
x = namad.replace("هموزن", "هم وزن")
y = x.replace("حافرين", "حآفرين")
z = y.replace("ص.دارا", "دارا")
for d in zip(data['l18'], data['pc'], data['tse_url']):
if z == d[0]:
option.at[a[1], 'bp'] = d[1]
option.at[a[1], 'StockName'] = z
option.at[a[1], 'StockURL'] = d[2]
for a in zip(option['bp'], option['strike'], option['stock'], option.index):
if a[2] == '311' or a[2] == '320':
if int(a[0]) > int(a[1]):
option.at[a[3], 'status'] = 'ITM'
elif int(a[0]) < int(a[1]):
option.at[a[3], 'status'] = 'OTM'
else:
option.at[a[3], 'status'] = 'ATM'
else:
if int(a[0]) < int(a[1]):
option.at[a[3], 'status'] = 'ITM'
elif int(a[0]) > int(a[1]):
option.at[a[3], 'status'] = 'OTM'
else:
option.at[a[3], 'status'] = 'ATM'
for a in zip(option['pl'], option['strike'], option['s1'], option.index, option['bp'], option['stock']):
if a[5] == '311' or a[5] == '320':
if a[2] == '0':
t = (int(a[0]) + int(a[1]))
option.at[a[3], 'through'] = t
else:
t = (int(a[2]) + int(a[1]))
option.at[a[3], 'through'] = t
else:
if a[2] == '0':
t = (int(a[1]) - int(a[0]))
option.at[a[3], 'through'] = t
else:
t = (int(a[1]) - int(a[2]))
option.at[a[3], 'through'] = t
pt = (t - int(a[4])) / int(a[4]) * 100
option.at[a[3], '%t'] = round(pt, 2)
for a in zip(option['tse_url'], option.index):
for b in zip(OC['tse_url'],OC["open_positions"], OC["contract_size"]):
if a[0] == b[0]:
option.at[a[1], 'open'] = b[1]
option.at[a[1], 'contract'] = b[2]
else:
option.at[a[1], 'open'] = 0
option.at[a[1], 'contract'] = 1000
for a in zip(option['pl'], option['pc'], option['py'], option.index):
option.at[a[3], '%pl'] = round((int(a[0]) - int(a[2])) / int(a[2]) * 100, 2)
option.at[a[3], '%pc'] = round((int(a[1]) - int(a[2])) / int(a[2]) * 100, 2)
_list = set()
for a in zip(option['StockURL']):
_list.add(a[0])
for b in _list:
col = {
0: 'ticker',
1: 'date',
2: 'first',
3: 'high',
4: 'low',
5: 'close',
6: 'value',
7: 'vol',
8: 'openint',
9: 'per',
10: 'open',
11: 'last',
}
url = 'http://www.tsetmc.com/tsev2/data/Export-txt.aspx?t=i&a=1&b=0&i=%s' % str(b)
r = requests.get(url)
main_text = r.text
df = pd.DataFrame([x.split(',') for x in main_text.split('\r\n')]).drop(0, axis=0)
data = df.rename(columns=col)
dd = data.drop(['ticker',
'date',
'first',
'high',
'low',
'value',
'vol',
'openint',
'per',
'open',
'last', ], axis=1)
dd['close'] = dd['close'].astype('float')
dd.at[dd.index, 'closen'] = dd['close'].shift(-1).astype('float')
for i in zip(dd['close'], dd['closen'], dd.index):
ln = 100 * math.log(i[0] / i[1])
dd.at[i[2], 'ln'] = ln
dd.drop(dd.loc[dd['ln'] >= 10].index, inplace=True)
dd.drop(dd.loc[dd['ln'] <= -10].index, inplace=True)
cc = dd.dropna(axis=0, how='any', thresh=None, subset=None, inplace=False)
ff = cc.iloc[:132]
volatility = (np.std(ff['ln'], ddof=1)) * math.sqrt(245)
for p in zip(option['StockURL'], option.index):
if p[0] == b:
option.at[p[1], 'volatility'] = round(volatility, 1)
for a in zip(option['strike'], option['bp'], option['mature'], option['volatility'], option['stock'], option.index,option['pl'], option['s1']):
S = int(a[1])
K = int(a[0])
T = int(a[2])
r = 0.25
sigma = float(a[3]) / 100
q = 0
if T == 0:
d1 = 0
else:
d1 = (math.log(S / K) + ((r - q + (0.5 * (sigma ** 2))) * T / 365)) / (sigma * math.sqrt(T / 365))
d2 = (d1 - sigma * math.sqrt(T / 365))
if T == 0:
t1 = 0
else:
t1 = (np.log(S/K) + (r + sigma**2/2)* T)/(sigma*np.sqrt(T))
t2 = d1 - sigma * np.sqrt(T)
Nd1 = math.exp(-(d1**2) / 2)/math.sqrt(2*3.14)
option.at[a[5], 'gamma'] = round(Nd1 * math.exp(-q*T)/S*sigma*T**0.5)
option.at[a[5], 'vega'] = round(S*T**0.5*Nd1)
if a[2] == 0 and K >= S:
option.at[a[5], 'blackscholes'] = 0
elif a[2] == 0 and K < S:
option.at[a[5], 'blackscholes'] = S - K
else:
if a[4] == '311' or a[4] == '320':
call = (S * math.exp(-q * T / 365) * norm.cdf(d1) - K * math.exp(-r * T / 365) * norm.cdf(d2))
deltaCall = norm.cdf(d1)
option.at[a[5], 'blackscholes'] = round(call)
option.at[a[5], 'delta'] = round(deltaCall, 4)
option.at[a[5], 'rho'] = round(K*T*math.exp(-r*T)*norm.cdf(d2), 4)
option.at[a[5], 'theta'] = round(1/365*(-(S*sigma*math.exp(-q*T)*Nd1/2*T**0.5)-r*K*math.exp(-r*T)*norm.cdf(d2)+q*S*math.exp(-q*T)*norm.cdf(d1)), 4)
if int(a[7]) == 0:
option.at[a[5], 'deltaLever'] = round(S*deltaCall - int(a[6])/int(a[6]),2)
else:
option.at[a[5], 'deltaLever'] = round(S*deltaCall - int(a[7])/int(a[7]),2)
else:
put = (K * math.exp(-r * T / 365) * norm.cdf(-1 * d2) - S * math.exp(-q * T / 365) * norm.cdf(-1 * d1))
deltaPut = norm.cdf(d1)-1
option.at[a[5], 'blackscholes'] = round(put)
option.at[a[5], 'delta'] = round(deltaPut, 4)
option.at[a[5], 'rho'] = round(-K*T*math.exp(-r*T)*norm.cdf(-d2), 4)
option.at[a[5], 'theta'] = round(1/365*(-(S*sigma*math.exp(-q*T)*Nd1/2*T**0.5)+r*K*math.exp(-r*T)*norm.cdf(-d2)-q*S*math.exp(-q*T)*norm.cdf(-d1)), 4)
if int(a[7]) == 0:
option.at[a[5], 'deltaLever'] = round(S*deltaPut - int(a[6])/int(a[6]),2)
else:
option.at[a[5], 'deltaLever'] = round(S*deltaPut - int(a[7])/int(a[7]),2)
for a in zip(option['s1'], option['blackscholes'], option['pl'], option.index):
if int(a[0]) == 0 and int(a[1]) == 0:
option.at[a[3], 'SellBS'] = 0
elif int(a[0]) == 0 and int(a[1]) != 0:
option.at[a[3], 'SellBS'] = "بدون فروشنده"
elif int(a[0]) != 0 and int(a[1]) == 0:
option.at[a[3], 'SellBS'] = round(int(a[0]) * 100, 2)
else:
option.at[a[3], 'SellBS'] = round(((int(a[0]) - int(a[1])) / int(a[1])) * 100, 2)
for a in zip(option['b1'], option['blackscholes'], option['pl'], option.index):
if int(a[0]) == 0 and int(a[1]) == 0:
option.at[a[3], 'BuyBS'] = 0
elif int(a[0]) == 0 and int(a[1]) != 0:
option.at[a[3], 'BuyBS'] = "بدون خریدار"
elif int(a[0]) != 0 and int(a[1]) == 0:
option.at[a[3], 'BuyBS'] = round(int(a[0]) * 100, 2)
else:
option.at[a[3], 'BuyBS'] = round(((int(a[0]) - int(a[1])) / int(a[1])) * 100, 2)
for a in zip(option['s1'], option['strike'], option['pl'], option.index):
if int(a[0]) == 0:
option.at[a[3], 'lever'] = round((int(a[1]) / int(a[2])), 2)
else:
option.at[a[3], 'lever'] = round((int(a[1]) / int(a[0])), 2)
for a in zip(option['strike'], option['bp'], option['stock'], option.index,option['pl'], option['s1'], option['contract']):
if a[2] == '311' or a[2] == '320':
l = abs(min(int(a[1]) - int(a[0]), 0)) * int(a[6])
I1 = 0.2 * int(a[1]) * int(a[6]) - l
I2 = 0.1 * int(a[0]) * int(a[6])
V1 = (math.floor(max(I1, I2) / 100000) + 1) * 100000
if a[5] != '0':
V2 = int(a[5]) * int(a[6])
M = V1 + V2
option.at[a[3],'margin']=round(M)
option.at[a[3],'undif']= round(int(a[0])/int(a[5])-int(a[1]) - 1, 4)*100
else:
V2 = int(a[4]) * int(a[6])
M = V1 + V2
option.at[a[3],'margin']=round(M)
option.at[a[3],'undif']= round(int(a[0])/int(a[4])-int(a[1]) - 1, 4)*100
else:
l = abs(int(a[0]) - min(int(a[1]), 0)) * int(a[6])
I1 = 0.2 * int(a[1]) * int(a[6]) - l
I2 = 0.1 * int(a[0]) * int(a[6])
V1 = (math.floor(max(I1, I2) / 100000) + 1) * 100000
if a[5] != '0':
V2 = int(a[5]) * int(a[6])
M = V1 + V2
option.at[a[3],'margin']=round(M)
option.at[a[3],'undif']= round(int(a[0])/int(a[5])-int(a[1]) - 1, 4)*100
else:
V2 = int(a[4]) * int(a[6])
M = V1 + V2
option.at[a[3],'margin']=round(M)
option.at[a[3],'undif']= round(int(a[0])/int(a[4])-int(a[1]) - 1, 4)*100
end = time.time()
print(end - start)
I need to reduce the execution time of this code to the lowest possible time, but currently it takes about 35 seconds.
|
[
"Your code is slow because of all those loops. It is way outside the scope of a single question and answer to actually fix all that code, but I can tell you how to fix it:\n\nProfile each part. Break the code down into steps, perhaps into functions or just time each outer loop. This will tell you where to spend your time optimizing.\nFigure out how to use Pandas and NumPy in a \"vectorized\" way. This means instead of looping over each row of a DataFrame, find an equivalent operation you can apply to all rows at once. For example if you need to multiply one column by another, just say df['A'] * df['B'] to get the entire resulting series at once, instead of using a for loop to populate one cell at a time. By using vectorized operations, your program will mostly execute compiled library code which is highly optimized, rather than slow Python code.\nIf there is a part which is not amenable to vectorization, use Numba. Numba is a just-in-time compiler for NumPy, and it can wrap a Python function into a callable object which compiles the code the first time it's called so that it will execute as quickly as possible (as if you wrote the code in C or C++, in some cases).\nWalk before you run. Isolate the smallest piece of your code which takes a significant amount of time, put its inputs into a text file so you can easily reload them, and experiment. Don't try to optimize the entire program at once, if it takes 35 seconds every time you try something, you'll never finish. Separating your code into well-defined functions will help.\n\n"
] |
[
2
] |
[] |
[] |
[
"dataframe",
"numpy",
"pandas",
"python"
] |
stackoverflow_0074498348_dataframe_numpy_pandas_python.txt
|
Q:
I want to split into train/test my numpy array files
I have 12000 files each in .npy format. Im doing this because my images are grayscaled. Each file is (64,64). I want to know if there is a way to split into test and train to use for an Autoencoder.
(64,64) numpy image
My Autoencoder will be trained with (64,64) images. If someone has experience with Autoencoders:
Is it better to train with (3,64,64) or (64,64)?
Is png, jpg format better than npy?
A:
You can use sklearn's train_test_split.
import numpy as np
from sklearn.model_selection import train_test_split
list_of_images = # a list containing the paths of all your data files
# or a numpy array of shape (12000, 64, 64)
train_list, test_list = train_test_list(list_of_images, test_size=0.1, random_state=0, shuffle=True)
The above snippet should divide your data into 90% and 10% for train and test.
If you apply it on a list of paths, it should return two lists of paths.
If you load all your images in advance into a large array of size (12000, 64, 64), then it will return two smaller arrays of (10800, 64, 64) and (1200, 64, 64) respectively.
As your images are grayscale, there is no need to use (3, 64, 64), autoencoders will work fine with (64, 64)---or (1, 64, 64), to be precise.
|
I want to split into train/test my numpy array files
|
I have 12000 files each in .npy format. Im doing this because my images are grayscaled. Each file is (64,64). I want to know if there is a way to split into test and train to use for an Autoencoder.
(64,64) numpy image
My Autoencoder will be trained with (64,64) images. If someone has experience with Autoencoders:
Is it better to train with (3,64,64) or (64,64)?
Is png, jpg format better than npy?
|
[
"You can use sklearn's train_test_split.\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\n\nlist_of_images = # a list containing the paths of all your data files\n # or a numpy array of shape (12000, 64, 64)\n\ntrain_list, test_list = train_test_list(list_of_images, test_size=0.1, random_state=0, shuffle=True)\n\nThe above snippet should divide your data into 90% and 10% for train and test.\n\nIf you apply it on a list of paths, it should return two lists of paths.\nIf you load all your images in advance into a large array of size (12000, 64, 64), then it will return two smaller arrays of (10800, 64, 64) and (1200, 64, 64) respectively.\n\nAs your images are grayscale, there is no need to use (3, 64, 64), autoencoders will work fine with (64, 64)---or (1, 64, 64), to be precise.\n"
] |
[
1
] |
[] |
[] |
[
"autoencoder",
"numpy",
"numpy_ndarray",
"python"
] |
stackoverflow_0074496132_autoencoder_numpy_numpy_ndarray_python.txt
|
Q:
How to fix? TypeError: argument of type 'PasswordManager' is not iterable
I keep getting the following error and I can't seem to find a solution for it.
if password not in old_passwords:
TypeError: argument of type 'PasswordManager' is not iterable
For clarity, I needed to create a class called 'PasswordManager'. The class should have a list called 'old_passwords'. The list contains all past passwords, the last index of the list should be the current password. The required methods are 'set_password', 'get_password' and 'is_correct'.
'get_password' should return the current password.
'set_password' sets a new password. It should only change the password if the attempted password is different from all the user’s past passwords.
'is_correct' receives a string and returns a boolean True or False depending on whether the string is equal to the current password or not.
class PasswordManager():
old_passwords = []
def get_password(old_passwords):
return old_passwords[len(old_passwords-1)]
def set_password(old_passwords, password):
if password not in old_passwords:
old_passwords.append(password)
def is_correct(old_passwords, password):
if password == old_passwords[len(old_passwords-1)]:
return True
else:
return False
Does anyone have an idea that could help me? Thanks in advance!
A:
I think you need to review how to use classes in python.
Your class needs a constructor, where you can instantiate your class attributes (in your case old_passwords) and you can access them with self.
An example of your use case could be
class PasswordManager():
def __init__(self):
self.old_passwords = []
def get_password(self):
return self.old_passwords[-1]
def set_password(self, password):
if password not in self.old_passwords:
self.old_passwords.append(password)
def is_correct(self, password):
return password == self.old_passwords[-1]
With [-1] you can access the last element of a list.
__init__ is the constructor method in python.
A:
python class methods require first argument as class itself. moreover, you cannot directly access class variables or methods in its methods. need to use something like self.somemethod() or self.somevariable
class PasswordManager():
old_passwords = []
def get_password(self):
return self.old_passwords[-1]
def set_password(self, password):
if password not in self.old_passwords:
self.old_passwords.append(password)
def is_correct(self, password):
if password == self.old_passwords[-1]:
return True
else:
return False
also, you are accessing last item in list wrong way.old_passwords[len(old_passwords-1)] should be old_passwords[len(old_passwords)-1]. but, old_passwords[-1] is better choice.
|
How to fix? TypeError: argument of type 'PasswordManager' is not iterable
|
I keep getting the following error and I can't seem to find a solution for it.
if password not in old_passwords:
TypeError: argument of type 'PasswordManager' is not iterable
For clarity, I needed to create a class called 'PasswordManager'. The class should have a list called 'old_passwords'. The list contains all past passwords, the last index of the list should be the current password. The required methods are 'set_password', 'get_password' and 'is_correct'.
'get_password' should return the current password.
'set_password' sets a new password. It should only change the password if the attempted password is different from all the user’s past passwords.
'is_correct' receives a string and returns a boolean True or False depending on whether the string is equal to the current password or not.
class PasswordManager():
old_passwords = []
def get_password(old_passwords):
return old_passwords[len(old_passwords-1)]
def set_password(old_passwords, password):
if password not in old_passwords:
old_passwords.append(password)
def is_correct(old_passwords, password):
if password == old_passwords[len(old_passwords-1)]:
return True
else:
return False
Does anyone have an idea that could help me? Thanks in advance!
|
[
"I think you need to review how to use classes in python.\nYour class needs a constructor, where you can instantiate your class attributes (in your case old_passwords) and you can access them with self.\nAn example of your use case could be\nclass PasswordManager():\n \n def __init__(self):\n self.old_passwords = []\n\n def get_password(self):\n return self.old_passwords[-1]\n\n def set_password(self, password):\n if password not in self.old_passwords:\n self.old_passwords.append(password)\n\n def is_correct(self, password):\n return password == self.old_passwords[-1]\n\nWith [-1] you can access the last element of a list.\n__init__ is the constructor method in python.\n",
"python class methods require first argument as class itself. moreover, you cannot directly access class variables or methods in its methods. need to use something like self.somemethod() or self.somevariable\n\nclass PasswordManager():\n old_passwords = []\n def get_password(self):\n return self.old_passwords[-1]\n\n def set_password(self, password):\n if password not in self.old_passwords:\n self.old_passwords.append(password)\n\n def is_correct(self, password):\n if password == self.old_passwords[-1]:\n return True\n else:\n return False\n\nalso, you are accessing last item in list wrong way.old_passwords[len(old_passwords-1)] should be old_passwords[len(old_passwords)-1]. but, old_passwords[-1] is better choice.\n"
] |
[
2,
0
] |
[] |
[] |
[
"class",
"list",
"methods",
"python",
"typeerror"
] |
stackoverflow_0074499390_class_list_methods_python_typeerror.txt
|
Q:
Keylogger but when i press esc its doesnt get out
I'm writing a keylogger. The script is nice until I press esc. But it doesn't exit. I did write a code for it but doesn't work. I tried so many options but I couldn't do it.
import pynput.keyboard
keys = []
escape = ['Esc' , 'Key.esc' , 'p' , 'Key.shift']
def on_press(letters):
global keys
keys.append(letters)
print(letters)
for k in keys:
if k == escape:
exit()
listening = pynput.keyboard.Listener(on_press)
with listening:
listening.join()
I did try:
for k in keys:
if k.find(escape):
rapor.write(keys)
and just like this options. I was expecting when I press button of in escape, escape from the program.
A:
You only check for escape once before you populate keys
import pynput.keyboard
keys = []
escape = ['Esc' , 'Key.esc' , 'p' , 'Key.shift']
def on_press(letters):
global keys
keys.append(letters)
print(letters)
# at this point keys is empty
for k in keys:
if k == escape:
exit()
#only after this keys starts to get values
listening = pynput.keyboard.Listener(on_press)
with listening:
listening.join()
you need to check for the escape key in on_press something along the lines of this:
def on_press(letters):
global keys
if letters in escape:
exit()
keys.append(letters)
print(letters)
Also your escape is wrong you probably want something like:
from pynput.keyboard import Key
escape = [Key.esc, Key.shift]
|
Keylogger but when i press esc its doesnt get out
|
I'm writing a keylogger. The script is nice until I press esc. But it doesn't exit. I did write a code for it but doesn't work. I tried so many options but I couldn't do it.
import pynput.keyboard
keys = []
escape = ['Esc' , 'Key.esc' , 'p' , 'Key.shift']
def on_press(letters):
global keys
keys.append(letters)
print(letters)
for k in keys:
if k == escape:
exit()
listening = pynput.keyboard.Listener(on_press)
with listening:
listening.join()
I did try:
for k in keys:
if k.find(escape):
rapor.write(keys)
and just like this options. I was expecting when I press button of in escape, escape from the program.
|
[
"You only check for escape once before you populate keys\nimport pynput.keyboard\n\nkeys = []\nescape = ['Esc' , 'Key.esc' , 'p' , 'Key.shift']\n\ndef on_press(letters):\n global keys \n keys.append(letters)\n print(letters)\n# at this point keys is empty\nfor k in keys:\n if k == escape:\n exit()\n\n#only after this keys starts to get values\nlistening = pynput.keyboard.Listener(on_press)\n\nwith listening:\n listening.join()\n\nyou need to check for the escape key in on_press something along the lines of this:\ndef on_press(letters):\n global keys\n if letters in escape:\n exit()\n keys.append(letters)\n print(letters)\n\nAlso your escape is wrong you probably want something like:\nfrom pynput.keyboard import Key\nescape = [Key.esc, Key.shift]\n\n"
] |
[
1
] |
[] |
[] |
[
"python",
"python_3.x"
] |
stackoverflow_0074499445_python_python_3.x.txt
|
Q:
How to use python flask to read json string
How to use pytohn module to read/filter "webserver1" that string
{
"Title":"Nginx Service"
"Instant":"[
{\"Hostname\":\"webserver1\"}
]"
}
"Title":"Nginx Service"
"Instant":"[
{\"Hostname\":\"webserver1\"}
]"
}
data = json.load(jsonfile)
return (data)
A:
The response depends on the inut json file, which is not clear in your post, because you haven't written a correct json. See here a json linter in order to check if a json is ok.
Option 1: json file is a dictionary
Let's say we have this json file as input, named myjsonfile_dict.json:
{
"Title": "Nginx Service",
"Instant": [{
"Hostname": "webserver1"
}]
}
We could get the value of 'Hostname' (which is 'webserver1') like this:
import sys
# Reading the json file
try:
with open("myjsonfile_dict.json", "r") as read_content:
dict_data_from_file: dict = json.load(read_content)
except (FileNotFoundError, PermissionError, OSError, ValueError) as e:
print(f"Error opening the file: {e}")
sys.exit()
# Parsing the read dictionary
try:
# Option 1.a: Get variable if only one item in the "Instant" list
hostname: str = dict_data_from_file['Instant'][0]['Hostname']
print(f'The first hostname is {hostname}')
# Option 1.b: Get variable with multiple items in the "Instant" list
hostnames: list = []
for instant_list in dict_data_from_file['Instant']:
hostnames.append(instant_list['Hostname'])
print('All the hostnames are:')
print(*hostnames, sep=", ")
except (KeyError, TypeError) as e:
print(f"Error parsing the json file: {e}")
Option 2: json file is list of dictionaries
Given this json file as input, named myjsonfile_list_of_dicts.json:
[
{
"Title": "Nginx Service",
"Instant": [{
"Hostname": "webserver1"
}]
},
{
"Title": "Nginx Service",
"Instant": [{
"Hostname": "webserver2"
}]
}
]
We could get the values of 'Hostname' (which are 'webserver1' and 'webserver2') like this:
import sys
# Reading the json file
try:
with open("myjsonfile_list_of_dicts.json", "r") as read_content:
list_data_from_file: dict = json.load(read_content)
except (FileNotFoundError, PermissionError, OSError, ValueError) as e:
print(f"Error opening the file: {e}")
sys.exit()
# Parsing the read list of dictionaries
try:
# Option 2.a: Get variable with multiple items in the "Instant" list
hostnames_a: list = []
for item in list_data_from_file:
hostnames_a.append(dict_data_from_file['Instant'][0]['Hostname'])
print('All the hostnames are:')
print(*hostnames_a, sep=", ")
# Option 2.b: Get variable with multiple items in the "Instant" list
hostnames: list = []
for item in list_data_from_file:
for instant_list in item['Instant']:
hostnames.append(instant_list['Hostname'])
print('All the hostnames are:')
print(*hostnames, sep=", ")
except (KeyError, TypeError) as e:
print(f"Error parsing the json file: {e}")
Recommendations:
Comment the code
Check the json is correct in a linter
Use try-except
Open files with 'with'
|
How to use python flask to read json string
|
How to use pytohn module to read/filter "webserver1" that string
{
"Title":"Nginx Service"
"Instant":"[
{\"Hostname\":\"webserver1\"}
]"
}
"Title":"Nginx Service"
"Instant":"[
{\"Hostname\":\"webserver1\"}
]"
}
data = json.load(jsonfile)
return (data)
|
[
"The response depends on the inut json file, which is not clear in your post, because you haven't written a correct json. See here a json linter in order to check if a json is ok.\nOption 1: json file is a dictionary\nLet's say we have this json file as input, named myjsonfile_dict.json:\n{\n \"Title\": \"Nginx Service\",\n \"Instant\": [{\n \"Hostname\": \"webserver1\"\n }]\n}\n\nWe could get the value of 'Hostname' (which is 'webserver1') like this:\nimport sys\n\n# Reading the json file\ntry:\n with open(\"myjsonfile_dict.json\", \"r\") as read_content:\n dict_data_from_file: dict = json.load(read_content)\nexcept (FileNotFoundError, PermissionError, OSError, ValueError) as e:\n print(f\"Error opening the file: {e}\")\n sys.exit()\n\n# Parsing the read dictionary\ntry:\n # Option 1.a: Get variable if only one item in the \"Instant\" list\n hostname: str = dict_data_from_file['Instant'][0]['Hostname']\n print(f'The first hostname is {hostname}')\n\n # Option 1.b: Get variable with multiple items in the \"Instant\" list\n hostnames: list = []\n for instant_list in dict_data_from_file['Instant']:\n hostnames.append(instant_list['Hostname'])\n print('All the hostnames are:')\n print(*hostnames, sep=\", \")\n\nexcept (KeyError, TypeError) as e:\n print(f\"Error parsing the json file: {e}\")\n\nOption 2: json file is list of dictionaries\nGiven this json file as input, named myjsonfile_list_of_dicts.json:\n[\n {\n \"Title\": \"Nginx Service\",\n \"Instant\": [{\n \"Hostname\": \"webserver1\"\n }]\n },\n {\n \"Title\": \"Nginx Service\",\n \"Instant\": [{\n \"Hostname\": \"webserver2\"\n }]\n }\n]\n\nWe could get the values of 'Hostname' (which are 'webserver1' and 'webserver2') like this:\nimport sys\n\n# Reading the json file\ntry:\n with open(\"myjsonfile_list_of_dicts.json\", \"r\") as read_content:\n list_data_from_file: dict = json.load(read_content)\nexcept (FileNotFoundError, PermissionError, OSError, ValueError) as e:\n print(f\"Error opening the file: {e}\")\n sys.exit()\n\n# Parsing the read list of dictionaries\ntry:\n # Option 2.a: Get variable with multiple items in the \"Instant\" list\n hostnames_a: list = []\n for item in list_data_from_file:\n hostnames_a.append(dict_data_from_file['Instant'][0]['Hostname'])\n print('All the hostnames are:')\n print(*hostnames_a, sep=\", \")\n\n # Option 2.b: Get variable with multiple items in the \"Instant\" list\n hostnames: list = []\n for item in list_data_from_file:\n for instant_list in item['Instant']:\n hostnames.append(instant_list['Hostname'])\n print('All the hostnames are:')\n print(*hostnames, sep=\", \")\n\nexcept (KeyError, TypeError) as e:\n print(f\"Error parsing the json file: {e}\")\n\nRecommendations:\n\nComment the code\nCheck the json is correct in a linter\nUse try-except\nOpen files with 'with'\n\n"
] |
[
0
] |
[] |
[] |
[
"flask",
"json",
"python"
] |
stackoverflow_0074498527_flask_json_python.txt
|
Q:
How to simulate new values without normality assumption?
I have the following list:
series=[0.6, 4.1, 0.6, 6.7, 9.2, 7.6, 5.5, 0.9, 3.8, 8.4]
the mean of series is 4.74 and its np.std equals : 3.101
I want to generate 1000 observations from series so I used the following method:
>>> series_1000=np.random.normal(4.74, 3.101, size=(1000))
>>> series_1000
>>> array([ 3.43395217, 6.60462489, 5.27316166, 4.20429521, 4.76772334,
8.04441319, -0.6967243 , 0.53378519, 2.1736758 , 9.96333279....
Problem
The above method seems to be good, however it works under the assumption that series is normally distributed.
Goal
My goal is to find a way of simulating values without any assumption regarding the original series.
Any help from your side will be highly appreciated.
A:
If a uniform distribution is better suited for your needs, you can use:
(np.random.uniform(-1, 1, size=1000) * 3.101) + 4.74
Or inside a convenience function:
def generate_values(mean, std, size=1000):
return(np.random.uniform(-1, 1, size=size) * std) + mean
|
How to simulate new values without normality assumption?
|
I have the following list:
series=[0.6, 4.1, 0.6, 6.7, 9.2, 7.6, 5.5, 0.9, 3.8, 8.4]
the mean of series is 4.74 and its np.std equals : 3.101
I want to generate 1000 observations from series so I used the following method:
>>> series_1000=np.random.normal(4.74, 3.101, size=(1000))
>>> series_1000
>>> array([ 3.43395217, 6.60462489, 5.27316166, 4.20429521, 4.76772334,
8.04441319, -0.6967243 , 0.53378519, 2.1736758 , 9.96333279....
Problem
The above method seems to be good, however it works under the assumption that series is normally distributed.
Goal
My goal is to find a way of simulating values without any assumption regarding the original series.
Any help from your side will be highly appreciated.
|
[
"If a uniform distribution is better suited for your needs, you can use:\n(np.random.uniform(-1, 1, size=1000) * 3.101) + 4.74\n\nOr inside a convenience function:\ndef generate_values(mean, std, size=1000):\n return(np.random.uniform(-1, 1, size=size) * std) + mean\n\n"
] |
[
1
] |
[] |
[] |
[
"montecarlo",
"normal_distribution",
"numpy",
"python",
"random"
] |
stackoverflow_0074499495_montecarlo_normal_distribution_numpy_python_random.txt
|
Q:
How to delete list items from list in python
I have a list with strings and super script characters(as power).
I need to concatenate scripted values with strings.
But according to my coding part It repeating same value twice.
I have no idea to remove unnecessary values from the list.
my original list -->
separate_units = ['N', 'm', '⁻²⁴', 'kJ', 's', '⁻¹', 'km', '⁻²¹', 'kJ', '⁻²', 'm', '⁻²']
result according to my coding part -->
result = ['N', 'm', 'm⁻²⁴', 'kJ', 's', 's⁻¹', 'km', 'km⁻²¹', 'kJ', 'kJ⁻²', 'm', 'kJ⁻²']
I expected result -->
result = ['N', 'm⁻²⁴', 'kJ', 's⁻¹', 'km⁻²¹', 'kJ⁻²', 'm', 'kJ⁻²']
I tried to delete last index when concatenate two items.But It gave me an error.
--> del (separating_units[(separate_units.index(su) - 1)]) # grab the last (index of unit) value to delete from the list.
Error coding part -->
def power_set_to_unit():
result = [su if su.isalpha() else del (separating_units[(separate_units.index(su) - 1)]) (separate_units[(separate_units.index(su) - 1)] + su) for su in separate_units]
print(result)
I prefer to do this in single line coding part.
Please help me to do this...
A:
Inside the function power_set_to_unit, you can iterate deciding whether to start a new entry in result, or append to the last element if you found an exponent:
separate_units = ['N', 'm', '⁻²⁴', 'kJ', 's', '⁻¹', 'km', '⁻²¹', 'kJ', '⁻²', 'm', '⁻²']
def power_set_to_unit():
result = []
for x in separate_units:
if x.isalpha():
result.append(x)
else:
result[-1] += x
return result
print(power_set_to_unit())
# ['N', 'm⁻²⁴', 'kJ', 's⁻¹', 'km⁻²¹', 'kJ⁻²', 'm⁻²']
PS. One-liner:
power_set_to_unit = lambda sep='\n': ''.join((sep+x if x.isalpha() else x) for x in separate_units).split(sep)[1:]
print(power_set_to_unit())
# ['N', 'm⁻²⁴', 'kJ', 's⁻¹', 'km⁻²¹', 'kJ⁻²', 'm⁻²']
The basic idea is to add a separator between characters when a exponent is not detected.
A:
Here is another oneliner using list comprehension and zip for a look ahead:
separate_units = ['N', 'm', '⁻²⁴', 'kJ', 's', '⁻¹', 'km', '⁻²¹', 'kJ', '⁻²', 'm', '⁻²']
[a if b.isalpha() else a + b for (a,b) in zip(separate_units[:-1], separate_units[1:]) if a.isalpha()]
# should result in ['N', 'm⁻²⁴', 'kJ', 's⁻¹', 'km⁻²¹', 'kJ⁻²', 'm⁻²']
To answer the question in the title of your post, to delete an item in list comprehension put the filter in an if-condition that follows the for-in block. For example, to get rid of non-alphabetic strings in a string list string_list just use
[x for x in string_list if x.isalpha()]
|
How to delete list items from list in python
|
I have a list with strings and super script characters(as power).
I need to concatenate scripted values with strings.
But according to my coding part It repeating same value twice.
I have no idea to remove unnecessary values from the list.
my original list -->
separate_units = ['N', 'm', '⁻²⁴', 'kJ', 's', '⁻¹', 'km', '⁻²¹', 'kJ', '⁻²', 'm', '⁻²']
result according to my coding part -->
result = ['N', 'm', 'm⁻²⁴', 'kJ', 's', 's⁻¹', 'km', 'km⁻²¹', 'kJ', 'kJ⁻²', 'm', 'kJ⁻²']
I expected result -->
result = ['N', 'm⁻²⁴', 'kJ', 's⁻¹', 'km⁻²¹', 'kJ⁻²', 'm', 'kJ⁻²']
I tried to delete last index when concatenate two items.But It gave me an error.
--> del (separating_units[(separate_units.index(su) - 1)]) # grab the last (index of unit) value to delete from the list.
Error coding part -->
def power_set_to_unit():
result = [su if su.isalpha() else del (separating_units[(separate_units.index(su) - 1)]) (separate_units[(separate_units.index(su) - 1)] + su) for su in separate_units]
print(result)
I prefer to do this in single line coding part.
Please help me to do this...
|
[
"Inside the function power_set_to_unit, you can iterate deciding whether to start a new entry in result, or append to the last element if you found an exponent:\nseparate_units = ['N', 'm', '⁻²⁴', 'kJ', 's', '⁻¹', 'km', '⁻²¹', 'kJ', '⁻²', 'm', '⁻²']\n\ndef power_set_to_unit():\n result = []\n for x in separate_units:\n if x.isalpha():\n result.append(x)\n else:\n result[-1] += x\n return result\n\nprint(power_set_to_unit())\n# ['N', 'm⁻²⁴', 'kJ', 's⁻¹', 'km⁻²¹', 'kJ⁻²', 'm⁻²']\n\n\nPS. One-liner:\npower_set_to_unit = lambda sep='\\n': ''.join((sep+x if x.isalpha() else x) for x in separate_units).split(sep)[1:]\nprint(power_set_to_unit())\n# ['N', 'm⁻²⁴', 'kJ', 's⁻¹', 'km⁻²¹', 'kJ⁻²', 'm⁻²']\n\nThe basic idea is to add a separator between characters when a exponent is not detected.\n",
"Here is another oneliner using list comprehension and zip for a look ahead:\nseparate_units = ['N', 'm', '⁻²⁴', 'kJ', 's', '⁻¹', 'km', '⁻²¹', 'kJ', '⁻²', 'm', '⁻²']\n\n[a if b.isalpha() else a + b for (a,b) in zip(separate_units[:-1], separate_units[1:]) if a.isalpha()]\n# should result in ['N', 'm⁻²⁴', 'kJ', 's⁻¹', 'km⁻²¹', 'kJ⁻²', 'm⁻²']\n\nTo answer the question in the title of your post, to delete an item in list comprehension put the filter in an if-condition that follows the for-in block. For example, to get rid of non-alphabetic strings in a string list string_list just use\n[x for x in string_list if x.isalpha()]\n\n"
] |
[
3,
1
] |
[] |
[] |
[
"arraylist",
"data_science",
"python"
] |
stackoverflow_0074499347_arraylist_data_science_python.txt
|
Q:
Problem using numpy to obtain the complex conjugate of a matrix
I have the following code:
import numpy as np
A=np.array([[2, 2-9j, -5j], [4-1j, 0, 9+6j], [4j, 6+7j, 6]])
print(A)
print(A.getH())
It doesn't work. I have checked different webs and followed this webpage (geeksforgeeks), and this other(official numpy documentation) but I still get an error and I don't know where. Can someone please help me?
The error is 'numpy.ndarray' object has no attribute 'getH'
A:
That's correct, a numpy array doesn't have a method getH. Your second link actually is the official documentation, and it shows that the method is not called getH. Read the documentation closely!
A:
You have to use numpy.conj() function.
import numpy as np
A=np.array([[2, 2-9j, -5j], [4-1j, 0, 9+6j], [4j, 6+7j, 6]])
print(A)
print(A.conj())
Output
[[ 2.+0.j 2.-9.j -0.-5.j]
[ 4.-1.j 0.+0.j 9.+6.j]
[ 0.+4.j 6.+7.j 6.+0.j]]
[[ 2.-0.j 2.+9.j -0.+5.j]
[ 4.+1.j 0.-0.j 9.-6.j]
[ 0.-4.j 6.-7.j 6.-0.j]]
A:
You're looking at pages about the numpy.matrix class, but the numpy.array function creates instances of numpy.ndarray, not numpy.matrix.
You could use numpy.matrix, but that's a bad idea. numpy.matrix has a lot of weird compatibility problems, and its use is discouraged in new code. Instead, use numpy.conj:
print(numpy.conj(A))
|
Problem using numpy to obtain the complex conjugate of a matrix
|
I have the following code:
import numpy as np
A=np.array([[2, 2-9j, -5j], [4-1j, 0, 9+6j], [4j, 6+7j, 6]])
print(A)
print(A.getH())
It doesn't work. I have checked different webs and followed this webpage (geeksforgeeks), and this other(official numpy documentation) but I still get an error and I don't know where. Can someone please help me?
The error is 'numpy.ndarray' object has no attribute 'getH'
|
[
"That's correct, a numpy array doesn't have a method getH. Your second link actually is the official documentation, and it shows that the method is not called getH. Read the documentation closely!\n",
"You have to use numpy.conj() function.\nimport numpy as np\nA=np.array([[2, 2-9j, -5j], [4-1j, 0, 9+6j], [4j, 6+7j, 6]])\nprint(A)\nprint(A.conj())\n\nOutput\n[[ 2.+0.j 2.-9.j -0.-5.j]\n [ 4.-1.j 0.+0.j 9.+6.j]\n [ 0.+4.j 6.+7.j 6.+0.j]]\n[[ 2.-0.j 2.+9.j -0.+5.j]\n [ 4.+1.j 0.-0.j 9.-6.j]\n [ 0.-4.j 6.-7.j 6.-0.j]]\n\n",
"You're looking at pages about the numpy.matrix class, but the numpy.array function creates instances of numpy.ndarray, not numpy.matrix.\nYou could use numpy.matrix, but that's a bad idea. numpy.matrix has a lot of weird compatibility problems, and its use is discouraged in new code. Instead, use numpy.conj:\nprint(numpy.conj(A))\n\n"
] |
[
1,
1,
0
] |
[] |
[] |
[
"attributeerror",
"complex_numbers",
"numpy",
"python"
] |
stackoverflow_0074499447_attributeerror_complex_numbers_numpy_python.txt
|
Q:
Install PyTorch from requirements.txt
Torch documentation says use
pip install torch==1.4.0+cpu torchvision==0.5.0+cpu -f https://download.pytorch.org/whl/torch_stable.html
to install the latest version of PyTorch. This works when I do it manually but when I add it to req.txt and do pip install -r req.txt, it fails and says ERROR: No matching distribution.
Edit: adding the whole line from req.txt and error here.
torch==1.4.0+cpu -f https://download.pytorch.org/whl/torch_stable.html
torchvision==0.5.0+cpu -f https://download.pytorch.org/whl/torch_stable.htmltorch==1.4.0+cpu
ERROR: Could not find a version that satisfies the requirement torch==1.4.0+cpu (from -r requirements.txt (line 1)) (from versions: 0.1.2, 0.1.2.post1, 0.1.2.post2, 0.3.1, 0.4.0, 0.4.1, 1.0.0, 1.0.1, 1.0.1.post2, 1.1.0, 1.2.0, 1.3.0, 1.3.1, 1.4.0)
ERROR: No matching distribution found for torch==1.4.0+cpu (from -r requirements.txt (line 1))
A:
Add --find-links in requirements.txt before torch
--find-links https://download.pytorch.org/whl/torch_stable.html
torch==1.2.0+cpu
Source: https://github.com/pytorch/pytorch/issues/29745#issuecomment-553588171
A:
-f https://download.pytorch.org/whl/torch_stable.html
torch==1.4.0+cpu
-f https://download.pytorch.org/whl/torch_stable.html
torchvision==0.5.0+cpu
worked fine for me :)
A:
You can do something like that:
$ pip install -r req.txt --find-links https://download.pytorch.org/whl/torch_stable.html
Just put your PyTorch requirements in req.txt like this:
torch==1.4.0+cpu
torchvision==0.5.0+cpu
A:
To get the cuda version that I needed (instead of whatever the repos serve up), I converted the cuda-specific installation command from pytorch:
pip3 install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu116
into this at the top of requirements.txt:
--extra-index-url https://download.pytorch.org/whl/cu116
torch
torchvision
torchaudio
Then I do the usual pip install -r requirements.txt and when I import torch and run torch.version.cuda inside python, I get '11.6' as I wanted.
A:
For me, this requirement.txt worked for CPU version installation
--extra-index-url https://download.pytorch.org/whl/cpu
torch
torchvision
|
Install PyTorch from requirements.txt
|
Torch documentation says use
pip install torch==1.4.0+cpu torchvision==0.5.0+cpu -f https://download.pytorch.org/whl/torch_stable.html
to install the latest version of PyTorch. This works when I do it manually but when I add it to req.txt and do pip install -r req.txt, it fails and says ERROR: No matching distribution.
Edit: adding the whole line from req.txt and error here.
torch==1.4.0+cpu -f https://download.pytorch.org/whl/torch_stable.html
torchvision==0.5.0+cpu -f https://download.pytorch.org/whl/torch_stable.htmltorch==1.4.0+cpu
ERROR: Could not find a version that satisfies the requirement torch==1.4.0+cpu (from -r requirements.txt (line 1)) (from versions: 0.1.2, 0.1.2.post1, 0.1.2.post2, 0.3.1, 0.4.0, 0.4.1, 1.0.0, 1.0.1, 1.0.1.post2, 1.1.0, 1.2.0, 1.3.0, 1.3.1, 1.4.0)
ERROR: No matching distribution found for torch==1.4.0+cpu (from -r requirements.txt (line 1))
|
[
"Add --find-links in requirements.txt before torch\n--find-links https://download.pytorch.org/whl/torch_stable.html\n\ntorch==1.2.0+cpu\n\nSource: https://github.com/pytorch/pytorch/issues/29745#issuecomment-553588171\n",
"-f https://download.pytorch.org/whl/torch_stable.html \ntorch==1.4.0+cpu \n-f https://download.pytorch.org/whl/torch_stable.html\ntorchvision==0.5.0+cpu\n\nworked fine for me :)\n",
"You can do something like that:\n$ pip install -r req.txt --find-links https://download.pytorch.org/whl/torch_stable.html\nJust put your PyTorch requirements in req.txt like this:\ntorch==1.4.0+cpu\ntorchvision==0.5.0+cpu\n",
"To get the cuda version that I needed (instead of whatever the repos serve up), I converted the cuda-specific installation command from pytorch:\npip3 install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu116\n\ninto this at the top of requirements.txt:\n--extra-index-url https://download.pytorch.org/whl/cu116\ntorch\ntorchvision\ntorchaudio\n\nThen I do the usual pip install -r requirements.txt and when I import torch and run torch.version.cuda inside python, I get '11.6' as I wanted.\n",
"For me, this requirement.txt worked for CPU version installation\n--extra-index-url https://download.pytorch.org/whl/cpu\ntorch\ntorchvision\n\n"
] |
[
45,
9,
7,
6,
0
] |
[] |
[] |
[
"pip",
"python",
"pytorch",
"requirements.txt"
] |
stackoverflow_0060912744_pip_python_pytorch_requirements.txt.txt
|
Q:
certbot Error while running on CentOS. Error: pkg_resources.DistributionNotFound: mock
I have installed certbot on my CentOS 7 VPS server using the command # *yum install certbot* after installation got the message Package certbot-1.11.0-2.el7.noarch already installed and latest version
And when trying to run # *certbot* command on my server getting the following error.
Traceback (most recent call last):
File "/usr/bin/certbot", line 5, in <module>
from pkg_resources import load_entry_point
File "/usr/lib/python2.7/site-packages/pkg_resources.py", line 3007, in <module>
working_set.require(__requires__)
File "/usr/lib/python2.7/site-packages/pkg_resources.py", line 728, in require
needed = self.resolve(parse_requirements(requirements))
File "/usr/lib/python2.7/site-packages/pkg_resources.py", line 626, in resolve
raise DistributionNotFound(req)
pkg_resources.DistributionNotFound: mock
mock package is already installed on my server
# rpm -qa |grep mock easymock2-2.5.2-12.el7.noarch python2-mock-1.0.1-10.el7.noarch
Any solution to run certbot ?
A:
Thanks everyone...
I fixed issue by updating the Python version.
Certbot environment seems to indicate Python3.
Set up a Python virtual environment on Certbot Instructions | Certbot
|
certbot Error while running on CentOS. Error: pkg_resources.DistributionNotFound: mock
|
I have installed certbot on my CentOS 7 VPS server using the command # *yum install certbot* after installation got the message Package certbot-1.11.0-2.el7.noarch already installed and latest version
And when trying to run # *certbot* command on my server getting the following error.
Traceback (most recent call last):
File "/usr/bin/certbot", line 5, in <module>
from pkg_resources import load_entry_point
File "/usr/lib/python2.7/site-packages/pkg_resources.py", line 3007, in <module>
working_set.require(__requires__)
File "/usr/lib/python2.7/site-packages/pkg_resources.py", line 728, in require
needed = self.resolve(parse_requirements(requirements))
File "/usr/lib/python2.7/site-packages/pkg_resources.py", line 626, in resolve
raise DistributionNotFound(req)
pkg_resources.DistributionNotFound: mock
mock package is already installed on my server
# rpm -qa |grep mock easymock2-2.5.2-12.el7.noarch python2-mock-1.0.1-10.el7.noarch
Any solution to run certbot ?
|
[
"Thanks everyone...\nI fixed issue by updating the Python version.\nCertbot environment seems to indicate Python3.\nSet up a Python virtual environment on Certbot Instructions | Certbot\n"
] |
[
0
] |
[] |
[] |
[
"certbot",
"lets_encrypt",
"python",
"python_packaging"
] |
stackoverflow_0074411489_certbot_lets_encrypt_python_python_packaging.txt
|
Q:
"DateTimeField %s received a naive datetime (%s)
'2022-11-11'
this is the input value getting from the front end,
RuntimeWarning: DateTimeField PaymentChart.date received a naive datetime (2022-11-18 00:00:00) while time zone support is active.
this is the error that coming
paydate = datetime.datetime.strptime(date,'%Y-%m-%d').isoformat()
this is how i tried to convert the date, and not working,
i got this error before, and i added 'tz=datetime.timezone.utc' , it was workin fine then
offer.expiry=datetime.datetime.now(tz=datetime.timezone.utc)+datetime.timedelta(days=28)
but how can i add tz in strptime ??
A:
You have to use Django's datetime, and not "datetime" library's datetime:
from django.utils import timezone
import pytz
offer.expiry=timezone.now()(tzinfo=pytz.UTC)+datetime.timedelta(days=28, tzinfo=pytz.UTC)
|
"DateTimeField %s received a naive datetime (%s)
|
'2022-11-11'
this is the input value getting from the front end,
RuntimeWarning: DateTimeField PaymentChart.date received a naive datetime (2022-11-18 00:00:00) while time zone support is active.
this is the error that coming
paydate = datetime.datetime.strptime(date,'%Y-%m-%d').isoformat()
this is how i tried to convert the date, and not working,
i got this error before, and i added 'tz=datetime.timezone.utc' , it was workin fine then
offer.expiry=datetime.datetime.now(tz=datetime.timezone.utc)+datetime.timedelta(days=28)
but how can i add tz in strptime ??
|
[
"You have to use Django's datetime, and not \"datetime\" library's datetime:\nfrom django.utils import timezone\nimport pytz\n\noffer.expiry=timezone.now()(tzinfo=pytz.UTC)+datetime.timedelta(days=28, tzinfo=pytz.UTC)\n\n"
] |
[
1
] |
[] |
[] |
[
"datetime",
"django",
"django_rest_framework",
"python",
"python_datetime"
] |
stackoverflow_0074497164_datetime_django_django_rest_framework_python_python_datetime.txt
|
Q:
Create Multi-Index empty DataFrame to join with main DataFrame
Suppose that I have a dataframe which can be created using code below
df = pd.DataFrame(data = {'date':['2021-01-01', '2021-01-02', '2021-01-05','2021-01-02', '2021-01-03', '2021-01-05'],
'product':['A', 'A', 'A', 'B', 'B', 'B'],
'price':[10, 20, 30, 40, 50, 60]
}
)
df['date'] = pd.to_datetime(df['date'])
I want to create an empty dataframe let's say main_df which will contain all dates between df.date.min() and df.date.max() for each product and on days where values in nan I want to ffill and bfill for remaning. The resulting dataframe would be as below:
+------------+---------+-------+
| date | product | price |
+------------+---------+-------+
| 2021-01-01 | A | 10 |
| 2021-01-02 | A | 20 |
| 2021-01-03 | A | 20 |
| 2021-01-04 | A | 20 |
| 2021-01-05 | A | 30 |
| 2021-01-01 | B | 40 |
| 2021-01-02 | B | 40 |
| 2021-01-03 | B | 50 |
| 2021-01-04 | B | 50 |
| 2021-01-05 | B | 60 |
+------------+---------+-------+
A:
First
make pivot table, upsampling by asfreq and fill null
df.pivot_table('price', 'date', 'product').asfreq('D').ffill().bfill()
output:
product A B
date
2021-01-01 10.0 40.0
2021-01-02 20.0 40.0
2021-01-03 20.0 50.0
2021-01-04 20.0 50.0
2021-01-05 30.0 60.0
Second
stack result and so on (include full code)
(df.pivot_table('price', 'date', 'product').asfreq('D').ffill().bfill()
.stack().reset_index().rename(columns={0:'price'})
.sort_values('product').reset_index(drop=True))
output:
date product price
0 2021-01-01 A 10.0
1 2021-01-02 A 20.0
2 2021-01-03 A 20.0
3 2021-01-04 A 20.0
4 2021-01-05 A 30.0
5 2021-01-01 B 40.0
6 2021-01-02 B 40.0
7 2021-01-03 B 50.0
8 2021-01-04 B 50.0
9 2021-01-05 B 60.0
A:
Using resample
df = pd.DataFrame(data = {'date':['2021-01-01', '2021-01-02', '2021-01-05','2021-01-02', '2021-01-03', '2021-01-06'],
'product':['A', 'A', 'A', 'B', 'B', 'B'],
'price':[10, 20, 30, 40, 50, 60]
}
)
df['date'] = pd.to_datetime(df['date'])
df
# Out:
# date product price
# 0 2021-01-01 A 10
# 1 2021-01-02 A 20
# 2 2021-01-05 A 30
# 3 2021-01-02 B 40
# 4 2021-01-03 B 50
# 5 2021-01-06 B 60
df.set_index("date").groupby("product")["price"].resample("d").ffill().reset_index()
# Out:
# product date price
# 0 A 2021-01-01 10
# 1 A 2021-01-02 20
# 2 A 2021-01-03 20
# 3 A 2021-01-04 20
# 4 A 2021-01-05 30
# 5 B 2021-01-02 40
# 6 B 2021-01-03 50
# 7 B 2021-01-04 50
# 8 B 2021-01-05 50
# 9 B 2021-01-06 60
See the rows that have been filled by ffill:
df.set_index("date").groupby("product")["price"].resample("d").mean()
# Out:
# product date
# A 2021-01-01 10.0
# 2021-01-02 20.0
# 2021-01-03 NaN
# 2021-01-04 NaN
# 2021-01-05 30.0
# B 2021-01-02 40.0
# 2021-01-03 50.0
# 2021-01-04 NaN
# 2021-01-05 NaN
# 2021-01-06 60.0
# Name: price, dtype: float64
Note that by grouping by product before resampling and filling the empty slots, you can have different ranges (from min to max) for each product (I modified the data to showcase this).
|
Create Multi-Index empty DataFrame to join with main DataFrame
|
Suppose that I have a dataframe which can be created using code below
df = pd.DataFrame(data = {'date':['2021-01-01', '2021-01-02', '2021-01-05','2021-01-02', '2021-01-03', '2021-01-05'],
'product':['A', 'A', 'A', 'B', 'B', 'B'],
'price':[10, 20, 30, 40, 50, 60]
}
)
df['date'] = pd.to_datetime(df['date'])
I want to create an empty dataframe let's say main_df which will contain all dates between df.date.min() and df.date.max() for each product and on days where values in nan I want to ffill and bfill for remaning. The resulting dataframe would be as below:
+------------+---------+-------+
| date | product | price |
+------------+---------+-------+
| 2021-01-01 | A | 10 |
| 2021-01-02 | A | 20 |
| 2021-01-03 | A | 20 |
| 2021-01-04 | A | 20 |
| 2021-01-05 | A | 30 |
| 2021-01-01 | B | 40 |
| 2021-01-02 | B | 40 |
| 2021-01-03 | B | 50 |
| 2021-01-04 | B | 50 |
| 2021-01-05 | B | 60 |
+------------+---------+-------+
|
[
"First\nmake pivot table, upsampling by asfreq and fill null\ndf.pivot_table('price', 'date', 'product').asfreq('D').ffill().bfill()\n\noutput:\nproduct A B\ndate \n2021-01-01 10.0 40.0\n2021-01-02 20.0 40.0\n2021-01-03 20.0 50.0\n2021-01-04 20.0 50.0\n2021-01-05 30.0 60.0\n\n\nSecond\nstack result and so on (include full code)\n(df.pivot_table('price', 'date', 'product').asfreq('D').ffill().bfill()\n .stack().reset_index().rename(columns={0:'price'})\n .sort_values('product').reset_index(drop=True))\n\noutput:\n date product price\n0 2021-01-01 A 10.0\n1 2021-01-02 A 20.0\n2 2021-01-03 A 20.0\n3 2021-01-04 A 20.0\n4 2021-01-05 A 30.0\n5 2021-01-01 B 40.0\n6 2021-01-02 B 40.0\n7 2021-01-03 B 50.0\n8 2021-01-04 B 50.0\n9 2021-01-05 B 60.0\n\n",
"Using resample\ndf = pd.DataFrame(data = {'date':['2021-01-01', '2021-01-02', '2021-01-05','2021-01-02', '2021-01-03', '2021-01-06'],\n 'product':['A', 'A', 'A', 'B', 'B', 'B'],\n 'price':[10, 20, 30, 40, 50, 60]\n }\n )\ndf['date'] = pd.to_datetime(df['date'])\n\ndf\n# Out: \n# date product price\n# 0 2021-01-01 A 10\n# 1 2021-01-02 A 20\n# 2 2021-01-05 A 30\n# 3 2021-01-02 B 40\n# 4 2021-01-03 B 50\n# 5 2021-01-06 B 60\n\n\n\n\ndf.set_index(\"date\").groupby(\"product\")[\"price\"].resample(\"d\").ffill().reset_index()\n# Out: \n# product date price\n# 0 A 2021-01-01 10\n# 1 A 2021-01-02 20\n# 2 A 2021-01-03 20\n# 3 A 2021-01-04 20\n# 4 A 2021-01-05 30\n# 5 B 2021-01-02 40\n# 6 B 2021-01-03 50\n# 7 B 2021-01-04 50\n# 8 B 2021-01-05 50\n# 9 B 2021-01-06 60\n\nSee the rows that have been filled by ffill:\ndf.set_index(\"date\").groupby(\"product\")[\"price\"].resample(\"d\").mean()\n# Out: \n# product date \n# A 2021-01-01 10.0\n# 2021-01-02 20.0\n# 2021-01-03 NaN\n# 2021-01-04 NaN\n# 2021-01-05 30.0\n# B 2021-01-02 40.0\n# 2021-01-03 50.0\n# 2021-01-04 NaN\n# 2021-01-05 NaN\n# 2021-01-06 60.0\n# Name: price, dtype: float64\n\nNote that by grouping by product before resampling and filling the empty slots, you can have different ranges (from min to max) for each product (I modified the data to showcase this).\n"
] |
[
2,
0
] |
[] |
[] |
[
"dataframe",
"multi_index",
"pandas",
"python"
] |
stackoverflow_0074499439_dataframe_multi_index_pandas_python.txt
|
Q:
Trying to stream live video using gstreamer but video keeps loading on client side
I have a raspberry pi 4 which I have a see3cam connected to via USB. I am trying to stream the live video to IP so that a computer on the same network can access the live feed.
I have tested that the camera in fact works with the raspberry pi. I'm able to watch it on the pi itself.
I've been following this tutorial.
My directory is /home/pi/cam, which now contains the multiple segment files, playlist.m3u8, and index.html.
When opening http://123.456.78.910:8080/index.html on another computer the page loads, but once you click play it just keeps loading forever and no video is actually shown. After trying to access the feed from the second computer, the raspberry pi displays
123.456.78.910 - - [31/Oct/2022 14:03:18] "GET /index.html HTTP/1.1" 200 -
123.456.78.910 - - [31/Oct/2022 14:03:19] "GET /playlist.m3u8 HTTP/1.1" 200 -
123.456.78.910 - - [31/Oct/2022 14:03:26] "GET /playlist.m3u8 HTTP/1.1" 200 -
There are no error messages.
I appreciate any advice, thank you for your time.
In one terminal I ran the following (results included):
pi@raspberrypi:~/cam $ gst-launch-1.0 v4l2src device=/dev/video0 ! video/x-raw, width=640, height=480, framerate=30/1 ! videoconvert ! videoscale ! clockoverlay time-format="%D %H:%M:%S" ! x264enc tune=zerolatency ! mpegtsmux ! hlssink playlist-root=http://123.456.78.910 location=/home/pi/cam/segment_%05d.ts target-duration=5 max-files=5
It ran successfully with the message "Setting pipeline to PLAYING..."
In another console I ran (results included):
pi@raspberrypi:~/cam $ python3 -m http.server 8080
Serving HTTP on 0.0.0.0 port 8080 (http://0.0.0.0:8080/) ...
A:
As we can see "playlist.m3u8" is called but the segment are not
123.456.78.910 - - [31/Oct/2022 14:03:18] "GET /index.html HTTP/1.1" 200. -
123.456.78.910 - - [31/Oct/2022 14:03:19] "GET /playlist.m3u8 HTTP/1.1" 200 -
123.456.78.910 - - [31/Oct/2022 14:03:26] "GET /playlist.m3u8 HTTP/1.1" 200 -
This mainly because :
The playlist.m3u8 generated deliver wrong link for ts files
#EXTM3U
#EXT-X-VERSION:3
#EXT-X-MEDIA-SEQUENCE:1
#EXT-X-TARGETDURATION:5
#EXTINF:5.0053420066833496,
http://123.456.78.910/segment_00000.ts
#EXTINF:5,
http://123.456.78.910/segment_00001.ts
This command should help :
pi@raspberrypi:~/cam $ gst-launch-1.0 v4l2src device=/dev/video0 ! video/x-raw, width=640, height=480, framerate=30/1 ! videoconvert ! videoscale ! clockoverlay time-format="%D %H:%M:%S" ! x264enc tune=zerolatency ! mpegtsmux ! hlssink playlist-root=http://123.456.78.910:8080 location=/home/pi/cam/segment_%05d.ts target-duration=5 max-files=5
|
Trying to stream live video using gstreamer but video keeps loading on client side
|
I have a raspberry pi 4 which I have a see3cam connected to via USB. I am trying to stream the live video to IP so that a computer on the same network can access the live feed.
I have tested that the camera in fact works with the raspberry pi. I'm able to watch it on the pi itself.
I've been following this tutorial.
My directory is /home/pi/cam, which now contains the multiple segment files, playlist.m3u8, and index.html.
When opening http://123.456.78.910:8080/index.html on another computer the page loads, but once you click play it just keeps loading forever and no video is actually shown. After trying to access the feed from the second computer, the raspberry pi displays
123.456.78.910 - - [31/Oct/2022 14:03:18] "GET /index.html HTTP/1.1" 200 -
123.456.78.910 - - [31/Oct/2022 14:03:19] "GET /playlist.m3u8 HTTP/1.1" 200 -
123.456.78.910 - - [31/Oct/2022 14:03:26] "GET /playlist.m3u8 HTTP/1.1" 200 -
There are no error messages.
I appreciate any advice, thank you for your time.
In one terminal I ran the following (results included):
pi@raspberrypi:~/cam $ gst-launch-1.0 v4l2src device=/dev/video0 ! video/x-raw, width=640, height=480, framerate=30/1 ! videoconvert ! videoscale ! clockoverlay time-format="%D %H:%M:%S" ! x264enc tune=zerolatency ! mpegtsmux ! hlssink playlist-root=http://123.456.78.910 location=/home/pi/cam/segment_%05d.ts target-duration=5 max-files=5
It ran successfully with the message "Setting pipeline to PLAYING..."
In another console I ran (results included):
pi@raspberrypi:~/cam $ python3 -m http.server 8080
Serving HTTP on 0.0.0.0 port 8080 (http://0.0.0.0:8080/) ...
|
[
"As we can see \"playlist.m3u8\" is called but the segment are not\n123.456.78.910 - - [31/Oct/2022 14:03:18] \"GET /index.html HTTP/1.1\" 200. -\n123.456.78.910 - - [31/Oct/2022 14:03:19] \"GET /playlist.m3u8 HTTP/1.1\" 200 -\n123.456.78.910 - - [31/Oct/2022 14:03:26] \"GET /playlist.m3u8 HTTP/1.1\" 200 -\n\nThis mainly because :\nThe playlist.m3u8 generated deliver wrong link for ts files\n#EXTM3U\n#EXT-X-VERSION:3\n#EXT-X-MEDIA-SEQUENCE:1\n#EXT-X-TARGETDURATION:5\n\n#EXTINF:5.0053420066833496,\nhttp://123.456.78.910/segment_00000.ts\n#EXTINF:5,\nhttp://123.456.78.910/segment_00001.ts\n\nThis command should help :\npi@raspberrypi:~/cam $ gst-launch-1.0 v4l2src device=/dev/video0 ! video/x-raw, width=640, height=480, framerate=30/1 ! videoconvert ! videoscale ! clockoverlay time-format=\"%D %H:%M:%S\" ! x264enc tune=zerolatency ! mpegtsmux ! hlssink playlist-root=http://123.456.78.910:8080 location=/home/pi/cam/segment_%05d.ts target-duration=5 max-files=5\n\n"
] |
[
0
] |
[] |
[] |
[
"gstreamer",
"python",
"raspberry_pi",
"raspbian",
"streaming"
] |
stackoverflow_0074267957_gstreamer_python_raspberry_pi_raspbian_streaming.txt
|
Q:
PyWinAuto with out using "child_window"
I have NO return on child_window when the program is in its state i expect to work in.
I need a way to edit the text field but literally all examples and google searches i have done show no examples of implementation EXCEPT when using child_window
this should put Test into the edit field
from pywinauto.application import Application
app = Application(backend="uia").connect(title="DaVinci Resolve Studio - Template")
#app.DaVinciResolveStudioTemplate.print_control_identifiers()
Title = app.DaVinciResolveStudioTemplate.['TitleEdit', 'Edit8'].wrapper_object()
Title.type_keys("Test")
it returns a syntax error
I have read teh documentation and i HONESTLY have no idea how to initiate the return with out a child window. Googing "no child_window" with multiple iterations has yielded me hours wasted and NOT ONE solution.
if text is entered the child_window appears in returns, but that isnt how the program start's
This is the native return
please, explain it for me how im supposed to seach/grab/interact with out child window? with a example please because this has me at a loss
A:
Syntax error is in line Title = app.DaVinciResolveStudioTemplate.['TitleEdit', 'Edit8'].wrapper_object().
This line should be written as either Title = app.DaVinciResolveStudioTemplate['TitleEdit', 'Edit8'].wrapper_object() or Title = app.DaVinciResolveStudioTemplate.Edit8.wrapper_object().
|
PyWinAuto with out using "child_window"
|
I have NO return on child_window when the program is in its state i expect to work in.
I need a way to edit the text field but literally all examples and google searches i have done show no examples of implementation EXCEPT when using child_window
this should put Test into the edit field
from pywinauto.application import Application
app = Application(backend="uia").connect(title="DaVinci Resolve Studio - Template")
#app.DaVinciResolveStudioTemplate.print_control_identifiers()
Title = app.DaVinciResolveStudioTemplate.['TitleEdit', 'Edit8'].wrapper_object()
Title.type_keys("Test")
it returns a syntax error
I have read teh documentation and i HONESTLY have no idea how to initiate the return with out a child window. Googing "no child_window" with multiple iterations has yielded me hours wasted and NOT ONE solution.
if text is entered the child_window appears in returns, but that isnt how the program start's
This is the native return
please, explain it for me how im supposed to seach/grab/interact with out child window? with a example please because this has me at a loss
|
[
"Syntax error is in line Title = app.DaVinciResolveStudioTemplate.['TitleEdit', 'Edit8'].wrapper_object().\nThis line should be written as either Title = app.DaVinciResolveStudioTemplate['TitleEdit', 'Edit8'].wrapper_object() or Title = app.DaVinciResolveStudioTemplate.Edit8.wrapper_object().\n"
] |
[
1
] |
[] |
[] |
[
"python",
"pywinauto"
] |
stackoverflow_0074495478_python_pywinauto.txt
|
Q:
Python Docx - how to number headings?
There is a good example for Python Docx.
I have used multiple document.add_heading('xxx', level=Y) and can see when I open the generated document in MS Word that the levels are correct.
What I don't see is numbering, such a 1, 1.1, 1.1.1, etc I just see the heading text.
How can I display heading numbers, using Docx ?
A:
Alphanumeric heading prefixes are automatically created based on the outline style and level of the heading. Set the outline style and insert the correct level and you will get the numbering.
From documentation:
_NumberingStyle objects class docx.styles.style._NumberingStyle[source] A numbering style. Not yet
implemented.
However, if you set the heading like this:
paragraph.style = document.styles['Heading 1']
then it should default to the latent numbering style of that heading.
A:
There is a great work around with python docx for achieving complex operations like headings enumerations. Here how to proceed:
Create a new blank document in Word and define your complex individual multilevel list there .
Save the blank document as my_template.docx.
Create the document in your python script based on your template:
from docx import Document
document = Document("my_template.docx")
document.add_heading('My first numbered heading', level=1)
And, voila, you can generate your perfect document with numbered headings.
A:
this answer will realy help you
first you need to new a without number header like this
paragraph = document.add_paragraph()
paragraph.style = document.styles['Heading 4']
then you will have xml word like this
<w:pPr>
<w:pStyle w:val="4"/>
</w:pPr>
then you can access xml word "pStyle" property and change it using under code
header._p.pPr.pStyle.set(qn('w:val'), u'4FDD')
final, open word file you will get what you want !!!
|
Python Docx - how to number headings?
|
There is a good example for Python Docx.
I have used multiple document.add_heading('xxx', level=Y) and can see when I open the generated document in MS Word that the levels are correct.
What I don't see is numbering, such a 1, 1.1, 1.1.1, etc I just see the heading text.
How can I display heading numbers, using Docx ?
|
[
"Alphanumeric heading prefixes are automatically created based on the outline style and level of the heading. Set the outline style and insert the correct level and you will get the numbering.\nFrom documentation:\n\n_NumberingStyle objects class docx.styles.style._NumberingStyle[source] A numbering style. Not yet\nimplemented.\n\nHowever, if you set the heading like this:\nparagraph.style = document.styles['Heading 1']\nthen it should default to the latent numbering style of that heading.\n",
"There is a great work around with python docx for achieving complex operations like headings enumerations. Here how to proceed:\n\nCreate a new blank document in Word and define your complex individual multilevel list there .\nSave the blank document as my_template.docx.\nCreate the document in your python script based on your template:\n\n from docx import Document\n\n document = Document(\"my_template.docx\")\n document.add_heading('My first numbered heading', level=1)\n\nAnd, voila, you can generate your perfect document with numbered headings.\n",
"this answer will realy help you\nfirst you need to new a without number header like this\nparagraph = document.add_paragraph()\nparagraph.style = document.styles['Heading 4']\n\nthen you will have xml word like this\n<w:pPr>\n<w:pStyle w:val=\"4\"/>\n</w:pPr>\n\nthen you can access xml word \"pStyle\" property and change it using under code\nheader._p.pPr.pStyle.set(qn('w:val'), u'4FDD')\n\nfinal, open word file you will get what you want !!!\n"
] |
[
4,
1,
0
] |
[
"def __str__(self):\n if self.nivel == 1: \n return str(Level.count_1)+'.- '+self.titulo\n elif self.nivel==2: #Imprime si es del nivel 2\n return str(Level.count_1)+'.'+str(Level.count_2)+'.- '+self.titulo\n elif self.nivel==3: #Imprime si es del nivel 3\n return str(Level.count_1)+'.'+str(Level.count_2)+'.'+str(Level.count_3)+'.- '+self.titulo \n\n"
] |
[
-1
] |
[
"python",
"python_docx"
] |
stackoverflow_0053870457_python_python_docx.txt
|
Q:
Reading information from a txt file and storing it in a dictionary
I need to take information from a txt file and store it into a dictionary
Only one line of the information is being stored in the dictionary, How do I have all the lines get stored?
text = '''
admin, Register Users with taskManager.py, Use taskManager.py to add the usernames and passwords for all team members that will be using this program., 10 Oct 2019, 20 Oct 2019, No
admin, Assign initial tasks, Use taskManager.py to assign each team member with appropriate tasks, 10 Oct 2019, 25 Oct 2019, No
'''
tasks = {}
with open('tasks.txt', 'r', encoding='utf-8') as file:
for line in file:
temp = line.split(", ")
user = temp[0]
title = temp[1]
description = temp[2]
due_date = temp[3]
date_assigned = temp[4]
status = temp[5]
tasks[user] = {'title': title, 'description': description, 'due date': due_date, 'date assigned': date_assigned, 'status': status}
print(tasks)
A:
you have the same key admin in your result dictionary, the first one is replaced by the second one, so modify you text file to give different names.
if you have multi assignment for one user, you can use following code:
text = '''
admin, Register Users with taskManager.py, Use taskManager.py to
add the usernames and passwords for all team members that will be
using this program., 10 Oct 2019, 20 Oct 2019, No
admin, Assign initial tasks, Use taskManager.py to assign each team
member with appropriate tasks, 10 Oct 2019, 25 Oct 2019, No
'''
tasks = {}
with open('tasks.txt', 'r', encoding='utf-8') as file:
for line in file:
temp = line.split(", ")
user = temp[0]
title = temp[1]
description = temp[2]
due_date = temp[3]
date_assigned = temp[4]
status = temp[5]
if user in list(tasks):
tasks[user].append({'title': title, 'description': description,
'due date': due_date, 'date assigned': date_assigned, 'status': status})
else:
tasks[user] = [{'title': title, 'description': description,
'due date': due_date, 'date assigned': date_assigned, 'status': status}]
print(tasks)
this should print:
{'admin': [{'title': 'Register Users with taskManager.py', 'description': 'Use taskManager.py to add the usernames and passwords for all team members that will be using this program.', 'due date': '10 Oct 2019', 'date assigned': '20 Oct 2019', 'status': 'No\n'}, {'title': 'Assign initial tasks', 'description': 'Use taskManager.py to assign each team member with appropriate tasks', 'due date': '10 Oct 2019', 'date assigned': '25 Oct 2019', 'status': 'No\n'}]}
|
Reading information from a txt file and storing it in a dictionary
|
I need to take information from a txt file and store it into a dictionary
Only one line of the information is being stored in the dictionary, How do I have all the lines get stored?
text = '''
admin, Register Users with taskManager.py, Use taskManager.py to add the usernames and passwords for all team members that will be using this program., 10 Oct 2019, 20 Oct 2019, No
admin, Assign initial tasks, Use taskManager.py to assign each team member with appropriate tasks, 10 Oct 2019, 25 Oct 2019, No
'''
tasks = {}
with open('tasks.txt', 'r', encoding='utf-8') as file:
for line in file:
temp = line.split(", ")
user = temp[0]
title = temp[1]
description = temp[2]
due_date = temp[3]
date_assigned = temp[4]
status = temp[5]
tasks[user] = {'title': title, 'description': description, 'due date': due_date, 'date assigned': date_assigned, 'status': status}
print(tasks)
|
[
"you have the same key admin in your result dictionary, the first one is replaced by the second one, so modify you text file to give different names.\nif you have multi assignment for one user, you can use following code:\ntext = '''\nadmin, Register Users with taskManager.py, Use taskManager.py to \nadd the usernames and passwords for all team members that will be \nusing this program., 10 Oct 2019, 20 Oct 2019, No\nadmin, Assign initial tasks, Use taskManager.py to assign each team \nmember with appropriate tasks, 10 Oct 2019, 25 Oct 2019, No\n\n'''\n\n\ntasks = {}\n\nwith open('tasks.txt', 'r', encoding='utf-8') as file:\n\n for line in file:\n temp = line.split(\", \")\n user = temp[0]\n title = temp[1]\n description = temp[2]\n due_date = temp[3]\n date_assigned = temp[4]\n status = temp[5]\n\n if user in list(tasks):\n tasks[user].append({'title': title, 'description': description,\n 'due date': due_date, 'date assigned': date_assigned, 'status': status})\n else:\n tasks[user] = [{'title': title, 'description': description,\n 'due date': due_date, 'date assigned': date_assigned, 'status': status}]\n\nprint(tasks)\n\nthis should print:\n{'admin': [{'title': 'Register Users with taskManager.py', 'description': 'Use taskManager.py to add the usernames and passwords for all team members that will be using this program.', 'due date': '10 Oct 2019', 'date assigned': '20 Oct 2019', 'status': 'No\\n'}, {'title': 'Assign initial tasks', 'description': 'Use taskManager.py to assign each team member with appropriate tasks', 'due date': '10 Oct 2019', 'date assigned': '25 Oct 2019', 'status': 'No\\n'}]}\n\n"
] |
[
0
] |
[] |
[] |
[
"dictionary",
"python"
] |
stackoverflow_0074499614_dictionary_python.txt
|
Q:
How to split images depend on it's label so each label will have it's image's folder
I have a csv file which contain images label and path, and I have another folder contain all images, so I want to save each label's images in it's own folder, here how the csv looks like, I appreciate any help
enter image description here
I didn't find any code for this one
A:
You have to use pandas for reading the csv, os for creating the folders e shutil for copying files.
import os
import shutil
import pandas as pd
# read the file
csv_file = pd.read_csv('file.csv', dtype=str)
# create the folders
labels = csv_file['label']
for label in labels:
os.makedirs(label, exist_ok=True)
# iterate rows and copy images
for _, row in csv_file.iterrows():
label = row['label']
path = row['path']
img_name = os.path.split(path)[-1]
new_path = os.path.join(label, img_name)
shutil.copy(path, new_path)
|
How to split images depend on it's label so each label will have it's image's folder
|
I have a csv file which contain images label and path, and I have another folder contain all images, so I want to save each label's images in it's own folder, here how the csv looks like, I appreciate any help
enter image description here
I didn't find any code for this one
|
[
"You have to use pandas for reading the csv, os for creating the folders e shutil for copying files.\nimport os\nimport shutil\nimport pandas as pd\n\n# read the file\ncsv_file = pd.read_csv('file.csv', dtype=str)\n\n# create the folders\nlabels = csv_file['label']\nfor label in labels:\n os.makedirs(label, exist_ok=True) \n\n# iterate rows and copy images\nfor _, row in csv_file.iterrows():\n label = row['label']\n path = row['path']\n img_name = os.path.split(path)[-1]\n new_path = os.path.join(label, img_name)\n shutil.copy(path, new_path)\n\n"
] |
[
1
] |
[] |
[] |
[
"csv",
"machine_learning",
"python"
] |
stackoverflow_0074499597_csv_machine_learning_python.txt
|
Q:
write multiple lines in a file in python
I have the following code:
line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")
print "I'm going to write these to the file."
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
Here target is the file object and line1, line2, line3 are the user inputs.
I want to use only a single target.write() command to write this script. I have tried using the following:
target.write("%s \n %s \n %s \n") % (line1, line2, line3)
But doesn't that put a string inside another string but if I use the following:
target.write(%s "\n" %s "\n" %s "\n") % (line1, line2, line3)
The Python interpreter(I'm using Microsoft Powershell) says invalid syntax.
How would I able to do it?
A:
You're confusing the braces. Do it like this:
target.write("%s \n %s \n %s \n" % (line1, line2, line3))
Or even better, use writelines:
target.writelines([line1, line2, line3])
A:
another way which, at least to me, seems more intuitive:
target.write('''line 1
line 2
line 3''')
A:
with open('target.txt','w') as out:
line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")
print("I'm going to write these to the file.")
out.write('{}\n{}\n{}\n'.format(line1,line2,line3))
A:
I notice that this is a study drill from the book "Learn Python The Hard Way". Though you've asked this question 3 years ago, I'm posting this for new users to say that don't ask in stackoverflow directly. At least read the documentation before asking.
And as far as the question is concerned, using writelines is the easiest way.
Use it like this:
target.writelines([line1, line2, line3])
And as alkid said, you messed with the brackets, just follow what he said.
A:
It can be done like this as well:
target.write(line1 + "\n" + line2 + "\n" + line3 + "\n")
A:
Assuming you don't want a space at each new line use:
print("I'm going to write these to the file")
target.write("%s\n%s\n%s\n" % (line1, line2, line3))
This works for version 3.6
A:
this also works:
target.write("{}" "\n" "{}" "\n" "{}" "\n".format(line1, line2, line3))
A:
You could use the join method of Python strings.
target.writelines("\n".join([line1, line2, line3]))
target.write("\n")
From https://docs.python.org/3/library/stdtypes.html#str.join :
Return a string which is the concatenation of the strings in iterable.
|
write multiple lines in a file in python
|
I have the following code:
line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")
print "I'm going to write these to the file."
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
Here target is the file object and line1, line2, line3 are the user inputs.
I want to use only a single target.write() command to write this script. I have tried using the following:
target.write("%s \n %s \n %s \n") % (line1, line2, line3)
But doesn't that put a string inside another string but if I use the following:
target.write(%s "\n" %s "\n" %s "\n") % (line1, line2, line3)
The Python interpreter(I'm using Microsoft Powershell) says invalid syntax.
How would I able to do it?
|
[
"You're confusing the braces. Do it like this:\ntarget.write(\"%s \\n %s \\n %s \\n\" % (line1, line2, line3))\n\nOr even better, use writelines:\ntarget.writelines([line1, line2, line3])\n\n",
"another way which, at least to me, seems more intuitive:\ntarget.write('''line 1\nline 2\nline 3''')\n\n",
"with open('target.txt','w') as out:\n line1 = raw_input(\"line 1: \")\n line2 = raw_input(\"line 2: \")\n line3 = raw_input(\"line 3: \")\n print(\"I'm going to write these to the file.\")\n out.write('{}\\n{}\\n{}\\n'.format(line1,line2,line3))\n\n",
"I notice that this is a study drill from the book \"Learn Python The Hard Way\". Though you've asked this question 3 years ago, I'm posting this for new users to say that don't ask in stackoverflow directly. At least read the documentation before asking.\nAnd as far as the question is concerned, using writelines is the easiest way.\nUse it like this:\ntarget.writelines([line1, line2, line3])\n\nAnd as alkid said, you messed with the brackets, just follow what he said.\n",
"It can be done like this as well:\ntarget.write(line1 + \"\\n\" + line2 + \"\\n\" + line3 + \"\\n\")\n\n",
"Assuming you don't want a space at each new line use:\nprint(\"I'm going to write these to the file\")\ntarget.write(\"%s\\n%s\\n%s\\n\" % (line1, line2, line3))\n\nThis works for version 3.6\n",
"this also works:\ntarget.write(\"{}\" \"\\n\" \"{}\" \"\\n\" \"{}\" \"\\n\".format(line1, line2, line3))\n\n",
"You could use the join method of Python strings.\ntarget.writelines(\"\\n\".join([line1, line2, line3]))\ntarget.write(\"\\n\")\n\nFrom https://docs.python.org/3/library/stdtypes.html#str.join :\n\nReturn a string which is the concatenation of the strings in iterable.\n\n"
] |
[
45,
10,
7,
3,
2,
1,
1,
0
] |
[
"variable=10\nf=open(\"fileName.txt\",\"w+\") # file name and mode\nfor x in range(0,10):\n f.writelines('your text')\n f.writelines('if you want to add variable data'+str(variable))\n # to add data you only add String data so you want to type cast variable \n f.writelines(\"\\n\")\n\n"
] |
[
-2
] |
[
"python"
] |
stackoverflow_0021019942_python.txt
|
Q:
How to catch any words in TfidfVectorizer by token_pattern
I'd like to catch any words separated by just space in TfidfVectorizer, even if the words like "0" "a" "x" "0?0" and so on.
I wrote the below code for this purpose.
However, maybe, this code doesn't work well.
vectorizer = TfidfVectorizer(smooth_idf = False, token_pattern=r"[^ ]+")
A:
You may be looking for word boundaries:
\b\S+\b
Explanation:
\b looks for a word boundary, in the first instance of usage it will look for the start of a word (first words after a newline or anything after a space (or type of whitespace))
\S+ matches non whitespace characters at least once (the word you are looking for)
Second \b matches end of word matched
Usage:
For string: Greetings from Spain it'd match Greetings , from and Spain
|
How to catch any words in TfidfVectorizer by token_pattern
|
I'd like to catch any words separated by just space in TfidfVectorizer, even if the words like "0" "a" "x" "0?0" and so on.
I wrote the below code for this purpose.
However, maybe, this code doesn't work well.
vectorizer = TfidfVectorizer(smooth_idf = False, token_pattern=r"[^ ]+")
|
[
"You may be looking for word boundaries:\n\\b\\S+\\b\n\nExplanation:\n\n\\b looks for a word boundary, in the first instance of usage it will look for the start of a word (first words after a newline or anything after a space (or type of whitespace))\n\\S+ matches non whitespace characters at least once (the word you are looking for)\nSecond \\b matches end of word matched\n\nUsage:\nFor string: Greetings from Spain it'd match Greetings , from and Spain\n"
] |
[
0
] |
[] |
[] |
[
"python",
"regex",
"scikit_learn",
"tfidfvectorizer"
] |
stackoverflow_0074498765_python_regex_scikit_learn_tfidfvectorizer.txt
|
Q:
I rewrite a matlab code in python but they result different outputs
the matlab code and the output i was expecting (gauss elimination method)
my code in python:
import numpy as np
A = np.array([
[1,2,-1,1],
[-1,4,3,1],
[2,1,1,1]])
n = rows = len(A)
col = len(A[0])
for i in range(n):
A[i,:] = A[i,:] / A[i,i]
for j in range(n):
if i==j:
pass
else:
A[j,:] = A[j,:] - (A[i,:] * A[j,i])
print(A)
the output i got:
[[1 0 0 1]
[0 1 0 0]
[0 0 1 0]]
A:
Your problem is related to casting. Without info, numpy cast your matrix to integer numbers, so when you divide, the result is not a float. For example 2 / 6 = 0 and not 0.33333.
If you put
A = np.array([
[1,2,-1,1],
[-1,4,3,1],
[2,1,1,1]], dtype=float)
your result will be
[[1. 0. 0. 0.33333333]
[0. 1. 0. 0.33333333]
[0. 0. 1. 0.]]
In matlab there is not this problem because your starting matrix is already casted to floating point numbers.
|
I rewrite a matlab code in python but they result different outputs
|
the matlab code and the output i was expecting (gauss elimination method)
my code in python:
import numpy as np
A = np.array([
[1,2,-1,1],
[-1,4,3,1],
[2,1,1,1]])
n = rows = len(A)
col = len(A[0])
for i in range(n):
A[i,:] = A[i,:] / A[i,i]
for j in range(n):
if i==j:
pass
else:
A[j,:] = A[j,:] - (A[i,:] * A[j,i])
print(A)
the output i got:
[[1 0 0 1]
[0 1 0 0]
[0 0 1 0]]
|
[
"Your problem is related to casting. Without info, numpy cast your matrix to integer numbers, so when you divide, the result is not a float. For example 2 / 6 = 0 and not 0.33333.\nIf you put\nA = np.array([\n [1,2,-1,1],\n [-1,4,3,1],\n [2,1,1,1]], dtype=float)\n\nyour result will be\n[[1. 0. 0. 0.33333333]\n[0. 1. 0. 0.33333333]\n[0. 0. 1. 0.]]\n\nIn matlab there is not this problem because your starting matrix is already casted to floating point numbers.\n"
] |
[
0
] |
[] |
[] |
[
"matlab",
"python"
] |
stackoverflow_0074499749_matlab_python.txt
|
Q:
How can I export all dataframes into an Excel file
I have a notebook open with about 45 dataframes. I would like to export all of them into a single Excel file with each dataframe being it's own tab in Excel.
Is there an easy way to do this without having to write each tab out manually?
Thank you!
A:
Please check the link Example: Pandas Excel with multiple dataframes
You can then as suggested by @delimiter create a list of the names
import pandas as pd
# Create some Pandas dataframes from some data.
df1 = pd.DataFrame({'Data': [11, 12, 13, 14]})
df2 = pd.DataFrame({'Data': [21, 22, 23, 24]})
df3 = pd.DataFrame({'Data': [31, 32, 33, 34]})
# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('pandas_multiple.xlsx', engine='xlsxwriter')
list = [df1,df2,df3]
names = ['df1','df2','df3']
for i in range(len(list)):
list[i].to_excel(writer, sheet_name=names[i])
A:
You can do this:
first create a list of all the dataframes that you need to write.
l=[df1,df2,df3...]
writer=pd.ExcelWriter('multi_df.xlsx',engine='xlsxwriter')
for i,df in enumerate(l):
df.to_excel(writer,sheet_name="df_"+str(i+1))
A:
Create a pandas excel writer instance and name the excel file
xlwriter = pd.ExcelWriter('Customer_Details.xlsx')
If you don't include a file path like 'C:\Users\Ron\Desktop\File_Name.xlsx', it will save to your default folder, that is where the file you're reading from is located.
#2. Write each dataframe to a worksheet with a name
dfName.to_excel(xlwriter, sheet_name = 'Name', index = False)
dfAddress.to_excel(xlwriter, sheet_name = 'Address', index = False)
dfContact.to_excel(xlwriter, sheet_name = 'Contact', index = False)
#3. Close the instance
xlwriter.close()
source youtu.be
|
How can I export all dataframes into an Excel file
|
I have a notebook open with about 45 dataframes. I would like to export all of them into a single Excel file with each dataframe being it's own tab in Excel.
Is there an easy way to do this without having to write each tab out manually?
Thank you!
|
[
"Please check the link Example: Pandas Excel with multiple dataframes\nYou can then as suggested by @delimiter create a list of the names\nimport pandas as pd\n# Create some Pandas dataframes from some data.\ndf1 = pd.DataFrame({'Data': [11, 12, 13, 14]})\ndf2 = pd.DataFrame({'Data': [21, 22, 23, 24]})\ndf3 = pd.DataFrame({'Data': [31, 32, 33, 34]})\n\n# Create a Pandas Excel writer using XlsxWriter as the engine.\nwriter = pd.ExcelWriter('pandas_multiple.xlsx', engine='xlsxwriter')\n\nlist = [df1,df2,df3]\nnames = ['df1','df2','df3']\nfor i in range(len(list)):\n list[i].to_excel(writer, sheet_name=names[i])\n\n",
"You can do this:\nfirst create a list of all the dataframes that you need to write.\nl=[df1,df2,df3...]\n\nwriter=pd.ExcelWriter('multi_df.xlsx',engine='xlsxwriter')\n\nfor i,df in enumerate(l):\n df.to_excel(writer,sheet_name=\"df_\"+str(i+1))\n\n",
"\nCreate a pandas excel writer instance and name the excel file\n\n xlwriter = pd.ExcelWriter('Customer_Details.xlsx')\n\nIf you don't include a file path like 'C:\\Users\\Ron\\Desktop\\File_Name.xlsx', it will save to your default folder, that is where the file you're reading from is located.\n#2. Write each dataframe to a worksheet with a name\n dfName.to_excel(xlwriter, sheet_name = 'Name', index = False)\n dfAddress.to_excel(xlwriter, sheet_name = 'Address', index = False)\n dfContact.to_excel(xlwriter, sheet_name = 'Contact', index = False)\n\n#3. Close the instance\nxlwriter.close()\n\nsource youtu.be\n"
] |
[
1,
0,
0
] |
[] |
[] |
[
"dataframe",
"pandas",
"python"
] |
stackoverflow_0066343969_dataframe_pandas_python.txt
|
Q:
Why I am getting 'pytest: error: unrecognized arguments: --env=qa' when running multiple pytest commands in a bash script
Hell there,
1.
I am using pipenv to create and activate a virtual environment where all dependencies are installed.
All the tests pass but my build fails because of this Error:
ERROR: usage: pytest [options] [file_or_dir] [file_or_dir] [...]
pytest: error: unrecognized arguments: --env=qa
inifile: /*/*/projects/<root dir>/pytest.ini
rootdir: /*/*/projects/<root dir>
metadata: {'Python': '3.8.3', 'Platform': 'Linux-4.4.0-184-generic-x86_64-with-glibc2.17', 'Packages': {'pytest': '7.2.0',...}
**conftest.py**:
def pytest_addoption(parser):
parser.addoption("--env", action="store", help="Environments: qa, staging, prod")
Project dir structure
├── roster
│ ├── __init__.py
│ ├── conftest.py
│ ├── run_suite_jenkins.sh
│ ├── smoke
│ └── utils.py
**executable bash script has multiple such commands: run_suite_jenkins.sh:
pytest roster/smoke/tests/test_team.py --env=qa --alluredir allure-results
pytest roster/smoke/tests/test_account_access.py --env=qa --alluredir allure-results
pytest roster/smoke/tests/test_brand.py --env=qa --alluredir allure-results
pytest roster/smoke/tests/test_company.py --env=qa --alluredir allure-results
.....
.....
.....
I execute the script this way: $./roster/run_suite_jenkins.sh
FYI.
I know I can run the tests with just this command, but there reasons why we are not doing it this way.
pytest roster/smoke/tests/ --env=qa --alluredir allure-results
Any help will be much much appreciated.
Thank you
A:
The documentation explains why this is not working. It states:
This function should be implemented only in plugins or conftest.py files situated at the tests root directory due to how pytest discovers plugins during startup.
Based on the diagram of the repository structure you are showing, the conftest.py file is not located in the root of the tests directory. Move it there and try again.
|
Why I am getting 'pytest: error: unrecognized arguments: --env=qa' when running multiple pytest commands in a bash script
|
Hell there,
1.
I am using pipenv to create and activate a virtual environment where all dependencies are installed.
All the tests pass but my build fails because of this Error:
ERROR: usage: pytest [options] [file_or_dir] [file_or_dir] [...]
pytest: error: unrecognized arguments: --env=qa
inifile: /*/*/projects/<root dir>/pytest.ini
rootdir: /*/*/projects/<root dir>
metadata: {'Python': '3.8.3', 'Platform': 'Linux-4.4.0-184-generic-x86_64-with-glibc2.17', 'Packages': {'pytest': '7.2.0',...}
**conftest.py**:
def pytest_addoption(parser):
parser.addoption("--env", action="store", help="Environments: qa, staging, prod")
Project dir structure
├── roster
│ ├── __init__.py
│ ├── conftest.py
│ ├── run_suite_jenkins.sh
│ ├── smoke
│ └── utils.py
**executable bash script has multiple such commands: run_suite_jenkins.sh:
pytest roster/smoke/tests/test_team.py --env=qa --alluredir allure-results
pytest roster/smoke/tests/test_account_access.py --env=qa --alluredir allure-results
pytest roster/smoke/tests/test_brand.py --env=qa --alluredir allure-results
pytest roster/smoke/tests/test_company.py --env=qa --alluredir allure-results
.....
.....
.....
I execute the script this way: $./roster/run_suite_jenkins.sh
FYI.
I know I can run the tests with just this command, but there reasons why we are not doing it this way.
pytest roster/smoke/tests/ --env=qa --alluredir allure-results
Any help will be much much appreciated.
Thank you
|
[
"The documentation explains why this is not working. It states:\n\nThis function should be implemented only in plugins or conftest.py files situated at the tests root directory due to how pytest discovers plugins during startup.\n\nBased on the diagram of the repository structure you are showing, the conftest.py file is not located in the root of the tests directory. Move it there and try again.\n"
] |
[
0
] |
[] |
[] |
[
"pytest",
"python"
] |
stackoverflow_0074481427_pytest_python.txt
|
Q:
What does "not enough values to unpack (expected 2, got 1)" means?
I'm using selenium to scrape images from google, and trying to save it using wget returns a "not enough values to unpack (expected 2, got 1)" error. Does anyone know what could possibly cause this?
imageDownload = wget.download(src, "images/{0}.png".format(counter))
File "image_scraper.py", line 38, in <module>
imageDownload = wget.download(actualImage.get_attribute("src"), "images/{0}.png".format(counter))
File "C:\Users\Ivab\AppData\Local\Programs\Python\Python37-32\lib\site-packages\wget.py", line 526, in download
(tmpfile, headers) = ulib.urlretrieve(binurl, tmpfile, callback)
File "C:\Users\Ivab\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 247, in urlretrieve
with contextlib.closing(urlopen(url, data)) as fp:
File "C:\Users\Ivab\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 222, in urlopen
return opener.open(url, data, timeout)
File "C:\Users\Ivab\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 525, in open
response = self._open(req, data)
File "C:\Users\Ivab\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 543, in _open
'_open', req)
File "C:\Users\Ivab\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 503, in _call_chain
result = func(*args)
File "C:\Users\Ivab\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 1624, in data_open
mediatype, data = data.split(",",1)
ValueError: not enough values to unpack (expected 2, got 1)
A:
Please check the values of your variables. In your given code you use src variable. In the errormessage is actualImage.get_attribute("src") used.
Print the src path and check if it´s valid (also try to open it manually in your browser as doublecheck).
Additionally please provide more of your code (and a sample for src). I guess the origin of your problem is hidden somewhere else.
A:
I ran into this same issue. After playing around with inputs and formats... it's the "old missing fwd slash" chestnut. :)
here's a real world example that works:
#-- utilities.py ---#
def wget_file(url,destination):
import wget as wget
wget.download(url, out=destination + f'/' )
output = str(destination) +f'/' + str(basename(url).decode().replace('\n',''))
print(output)
status = is_file(output)
return status
Notice the " +f'/' " after 'out=destination'. if that exrtra f'/' is not there it throws the
"ValueError: not enough values to unpack (expected 2, got 1)"...
hope it helps !
PS. 'basename()' is just a wrapper for os linux shell command 'basename'. you could do some fangdangled super tricky python equiv but im to busy LOL
Here's some output:
>>> import utilities as u
>>> version = 'v1.23.1'
>>> url = 'https://dl.k8s.io/release'+'/'+version+'/'+'bin/linux/amd64/kubectl.sha256'
>>> destPath = '/uga/app/py/rke2/.work/src/kubectl'
>>> u.wget_file(url,destPath)
100% [.......................................................] 64 / 64
/uga/app/py/rke2/.work/src/kubectl/kubectl.sha256
True
PPS. utilities.py contains the wget_file() and basename(), and is_file() which returns true if the file passed into it exists on the filesystem
|
What does "not enough values to unpack (expected 2, got 1)" means?
|
I'm using selenium to scrape images from google, and trying to save it using wget returns a "not enough values to unpack (expected 2, got 1)" error. Does anyone know what could possibly cause this?
imageDownload = wget.download(src, "images/{0}.png".format(counter))
File "image_scraper.py", line 38, in <module>
imageDownload = wget.download(actualImage.get_attribute("src"), "images/{0}.png".format(counter))
File "C:\Users\Ivab\AppData\Local\Programs\Python\Python37-32\lib\site-packages\wget.py", line 526, in download
(tmpfile, headers) = ulib.urlretrieve(binurl, tmpfile, callback)
File "C:\Users\Ivab\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 247, in urlretrieve
with contextlib.closing(urlopen(url, data)) as fp:
File "C:\Users\Ivab\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 222, in urlopen
return opener.open(url, data, timeout)
File "C:\Users\Ivab\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 525, in open
response = self._open(req, data)
File "C:\Users\Ivab\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 543, in _open
'_open', req)
File "C:\Users\Ivab\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 503, in _call_chain
result = func(*args)
File "C:\Users\Ivab\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 1624, in data_open
mediatype, data = data.split(",",1)
ValueError: not enough values to unpack (expected 2, got 1)
|
[
"Please check the values of your variables. In your given code you use src variable. In the errormessage is actualImage.get_attribute(\"src\") used.\nPrint the src path and check if it´s valid (also try to open it manually in your browser as doublecheck).\nAdditionally please provide more of your code (and a sample for src). I guess the origin of your problem is hidden somewhere else.\n",
"I ran into this same issue. After playing around with inputs and formats... it's the \"old missing fwd slash\" chestnut. :)\nhere's a real world example that works:\n#-- utilities.py ---# \ndef wget_file(url,destination):\n import wget as wget\n wget.download(url, out=destination + f'/' )\n output = str(destination) +f'/' + str(basename(url).decode().replace('\\n',''))\n print(output)\n status = is_file(output)\n return status\n\nNotice the \" +f'/' \" after 'out=destination'. if that exrtra f'/' is not there it throws the\n\"ValueError: not enough values to unpack (expected 2, got 1)\"...\nhope it helps !\nPS. 'basename()' is just a wrapper for os linux shell command 'basename'. you could do some fangdangled super tricky python equiv but im to busy LOL\nHere's some output:\n >>> import utilities as u\n >>> version = 'v1.23.1'\n >>> url = 'https://dl.k8s.io/release'+'/'+version+'/'+'bin/linux/amd64/kubectl.sha256'\n >>> destPath = '/uga/app/py/rke2/.work/src/kubectl'\n >>> u.wget_file(url,destPath)\n 100% [.......................................................] 64 / 64\n /uga/app/py/rke2/.work/src/kubectl/kubectl.sha256\n True\n\nPPS. utilities.py contains the wget_file() and basename(), and is_file() which returns true if the file passed into it exists on the filesystem\n"
] |
[
0,
0
] |
[] |
[] |
[
"python",
"wget"
] |
stackoverflow_0061034555_python_wget.txt
|
Q:
Selenium + Python: How to click Pay button on Google Pay pop up iframe checkout?
UPDATED:
Here is the checkout link. Click on gPay Button, log in Google with gPay to see the final Pay button to complete order that I want Selenium script to click on.
https://store.ui.com/14391668/checkouts/ae284ed7a99abc227e54933f1760e670
I have Selenium script to got to checkout and click the gPay button that pops up a window iframe which has a Pay div button below. How can I switch to the iFrame and click the Pay button to complete checkout?
https://i.stack.imgur.com/pubLj.png
Pay Button div
<div role="button" class="goog-inline-block jfk-button jfk-button-action b3-button b3id-button b3-ripple-container b3-primary-button" tabindex="0" style="user-select: none;" data-start-event-id="-131" data-was-visible="true">Pay<div class="b3id-ripple b3-ripple" aria-hidden="true" data-was-visible="true"></div></div>
This is the iframe in Body
<iframe style="border: 0px none; vertical-align: initial; display: block; width: 100%; position: static; top: auto; visibility: visible; z-index: auto; background-color: inherit; height: 510px; left: auto; min-height: auto; opacity: 1; transition: all 0s ease 0s;" src="https://payments.google.com/payments/u/0/embedded/buy_flow?tc=98%2C97%2C81%2C83%2xxxxxxxxxxxx" id="**sM432dIframe**" name="sM432dIframe" data-widget="current" title="" frameborder="0"></iframe>
I have tried these but did not work
WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.NAME, "sM432dIframe")))
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CLASS_NAME, "goog-inline-block jfk-button jfk-button-action b3-button b3id-button b3-ripple-container b3-primary-button"))).click()
or
time.sleep(10)
driver.switch_to.frame("sM432dIframe")
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CLASS_NAME, "goog-inline-block jfk-button jfk-button-action b3-button b3id-button b3-ripple-container b3-primary-button"))).click()
A:
In the switch_to.frame() function you need to specify the element thet contains the iframe. So instead of:
driver.switch_to.frame("sM432dIframe")
should be:
iframe = driver.find_element(By.ID, 'sM432dIframe')
driver.switch_to.frame(iframe)
|
Selenium + Python: How to click Pay button on Google Pay pop up iframe checkout?
|
UPDATED:
Here is the checkout link. Click on gPay Button, log in Google with gPay to see the final Pay button to complete order that I want Selenium script to click on.
https://store.ui.com/14391668/checkouts/ae284ed7a99abc227e54933f1760e670
I have Selenium script to got to checkout and click the gPay button that pops up a window iframe which has a Pay div button below. How can I switch to the iFrame and click the Pay button to complete checkout?
https://i.stack.imgur.com/pubLj.png
Pay Button div
<div role="button" class="goog-inline-block jfk-button jfk-button-action b3-button b3id-button b3-ripple-container b3-primary-button" tabindex="0" style="user-select: none;" data-start-event-id="-131" data-was-visible="true">Pay<div class="b3id-ripple b3-ripple" aria-hidden="true" data-was-visible="true"></div></div>
This is the iframe in Body
<iframe style="border: 0px none; vertical-align: initial; display: block; width: 100%; position: static; top: auto; visibility: visible; z-index: auto; background-color: inherit; height: 510px; left: auto; min-height: auto; opacity: 1; transition: all 0s ease 0s;" src="https://payments.google.com/payments/u/0/embedded/buy_flow?tc=98%2C97%2C81%2C83%2xxxxxxxxxxxx" id="**sM432dIframe**" name="sM432dIframe" data-widget="current" title="" frameborder="0"></iframe>
I have tried these but did not work
WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.NAME, "sM432dIframe")))
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CLASS_NAME, "goog-inline-block jfk-button jfk-button-action b3-button b3id-button b3-ripple-container b3-primary-button"))).click()
or
time.sleep(10)
driver.switch_to.frame("sM432dIframe")
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CLASS_NAME, "goog-inline-block jfk-button jfk-button-action b3-button b3id-button b3-ripple-container b3-primary-button"))).click()
|
[
"In the switch_to.frame() function you need to specify the element thet contains the iframe. So instead of:\ndriver.switch_to.frame(\"sM432dIframe\")\n\nshould be:\niframe = driver.find_element(By.ID, 'sM432dIframe') \ndriver.switch_to.frame(iframe)\n\n"
] |
[
0
] |
[] |
[] |
[
"iframe",
"python",
"selenium"
] |
stackoverflow_0074498650_iframe_python_selenium.txt
|
Q:
Python Dictionary showing empty values when adding lists
I'm trying to produce a JSON format for a given entity and I'm having an issue getting the dictionary to NOT overwrite itself or become empty. This is pulling rows from a table in a MySQL database and attempting to produce JSON result from the query.
Here is my function:
def detail():
student = 'John Doe'
conn = get_db_connection()
cur = conn.cursor()
sql = ("""
select
a.student_name,
a.student_id,
a.student_homeroom_name,
a.test_id,
a.datetaken,
a.datecertified,
b.request_number
FROM student_information a
INNER JOIN homeroom b ON a.homeroom_id = b.homeroom_id
WHERE a.student_name = '""" + student + """'
ORDER BY datecertified DESC
""")
cur.execute(sql)
details=cur.fetchall()
dataset = defaultdict(dict)
case_dataset = defaultdict(dict)
case_dataset = dict(case_dataset)
for student_name, student_id, student_homeroom_name, test_id, datetaken, datecertified, request_number in details:
dataset[student_name]['student_id'] = student_id
dataset[student_name]['student_homeroom_name'] = student_homeroom_name
case_dataset['test_id'] = test_id
case_dataset['datetaken'] = datetaken
case_dataset['datecertified'] = datecertified
case_dataset['request_number'] = request_number
dataset[student_name]['additional_information'] = case_dataset
case_dataset.clear()
dataset= dict(dataset)
print(dataset)
cur.close()
conn.close()
I tried a few different ways but nothing seems to work. What I'm getting is nothing in the additonal_information key. What I'm getting is this:
{
"John Doe": {
"student_id": "1234",
"student_homeroom_name": "HR1",
"additional_information": []
}
}
What I'm expecting is something similar to the below JSON. However, I'm torn if this is even correct. Each student will have one to many test_id and I will need to iterate through them in my application.
{
"John Doe": {
"student_id": "1234",
"student_homeroom_name": "HR1",
"additional_information": [
{
"test_id": "0987",
"datetaken": "1-1-1970",
"datecertified": "1-2-1970",
"request_number": "5643"
},
{
"test_id": "12343",
"datetaken": "1-1-1980",
"datecertified": "1-2-1980",
"request_number": "39807"
}
]
}
}
Removing the clear() from the function produces this JSON:
{
"John Doe": {
"student_id": "1234",
"student_homeroom_name": "HR1",
"additional_information": [
{
"test_id": "0987",
"datetaken": "1-1-1970",
"datecertified": "1-2-1970",
"request_number": "5643"
},
{
"test_id": "0987",
"datetaken": "1-1-1970",
"datecertified": "1-2-1970",
"request_number": "5643"
}
]
}
}
A:
lists are mutable objects. Which means that list's are passed by reference.
when you set
dataset[student]['additional_information'] = case_dataset
case_dataset.clear()
you're setting the list and then clearing it. So the list inside additional_information is also cleared.
Copy the list when setting it:
dataset[student]['additional_information'] = case_dataset[:]
case_dataset.clear()
A:
Thanks everyone for the guidance and pointing me in the right direction.
I have what I'm looking for now. Based on some of the comments and troubleshooting, I updated my code. Here is what I did:
I added back additional_dataset as a list
Removed case_dataset = defaultdict(dict) and case_dataset = dict(case_dataset) and replaced it with case_dataset = {}.
Updated dataset[student_name]['additional_information'] = case_dataset with dataset[student_name]['additional_information'] = additional_dataset
Replaced case_dataset.clear() with case_dataset = {}
Here is my new code now
def detail():
student = 'John Doe'
conn = get_db_connection()
cur = conn.cursor()
sql = ("""
select
a.student_name,
a.student_id,
a.student_homeroom_name,
a.test_id,
a.datetaken,
a.datecertified,
b.request_number
FROM student_information a
INNER JOIN homeroom b ON a.homeroom_id = b.homeroom_id
WHERE a.student_name = '""" + student + """'
ORDER BY datecertified DESC
""")
cur.execute(sql)
details=cur.fetchall()
dataset = defaultdict(dict)
case_dataset = {} #2 - Updated to just dict
additional_dataset = [] #1 - added back additional_dataset as a list
for student_name, student_id, student_homeroom_name, test_id, datetaken, datecertified, request_number in details:
dataset[student_name]['student_id'] = student_id
dataset[student_name]['student_homeroom_name'] = student_homeroom_name
case_dataset['test_id'] = test_id
case_dataset['datetaken'] = datetaken
case_dataset['datecertified'] = datecertified
case_dataset['request_number'] = request_number
dataset[student_name]['additional_information'] = additional_dataset #3 - updated to additional_dataset
case_dataset = {} #4 - updated to clear with new dict
dataset= dict(dataset)
print(dataset)
cur.close()
conn.close()
This is what it produces now. This is a much better structure then wat I was previously expecting.
{
"John Doe": {
"student_id": "1234",
"student_homeroom_name": "HR1",
"additional_information": [
{
"test_id": "0987",
"datetaken": "1-1-1970",
"datecertified": "1-2-1970",
"request_number": "5643"
},
{
"test_id": "12343",
"datetaken": "1-1-1980",
"datecertified": "1-2-1980",
"request_number": "39807"
}
]
}
}
|
Python Dictionary showing empty values when adding lists
|
I'm trying to produce a JSON format for a given entity and I'm having an issue getting the dictionary to NOT overwrite itself or become empty. This is pulling rows from a table in a MySQL database and attempting to produce JSON result from the query.
Here is my function:
def detail():
student = 'John Doe'
conn = get_db_connection()
cur = conn.cursor()
sql = ("""
select
a.student_name,
a.student_id,
a.student_homeroom_name,
a.test_id,
a.datetaken,
a.datecertified,
b.request_number
FROM student_information a
INNER JOIN homeroom b ON a.homeroom_id = b.homeroom_id
WHERE a.student_name = '""" + student + """'
ORDER BY datecertified DESC
""")
cur.execute(sql)
details=cur.fetchall()
dataset = defaultdict(dict)
case_dataset = defaultdict(dict)
case_dataset = dict(case_dataset)
for student_name, student_id, student_homeroom_name, test_id, datetaken, datecertified, request_number in details:
dataset[student_name]['student_id'] = student_id
dataset[student_name]['student_homeroom_name'] = student_homeroom_name
case_dataset['test_id'] = test_id
case_dataset['datetaken'] = datetaken
case_dataset['datecertified'] = datecertified
case_dataset['request_number'] = request_number
dataset[student_name]['additional_information'] = case_dataset
case_dataset.clear()
dataset= dict(dataset)
print(dataset)
cur.close()
conn.close()
I tried a few different ways but nothing seems to work. What I'm getting is nothing in the additonal_information key. What I'm getting is this:
{
"John Doe": {
"student_id": "1234",
"student_homeroom_name": "HR1",
"additional_information": []
}
}
What I'm expecting is something similar to the below JSON. However, I'm torn if this is even correct. Each student will have one to many test_id and I will need to iterate through them in my application.
{
"John Doe": {
"student_id": "1234",
"student_homeroom_name": "HR1",
"additional_information": [
{
"test_id": "0987",
"datetaken": "1-1-1970",
"datecertified": "1-2-1970",
"request_number": "5643"
},
{
"test_id": "12343",
"datetaken": "1-1-1980",
"datecertified": "1-2-1980",
"request_number": "39807"
}
]
}
}
Removing the clear() from the function produces this JSON:
{
"John Doe": {
"student_id": "1234",
"student_homeroom_name": "HR1",
"additional_information": [
{
"test_id": "0987",
"datetaken": "1-1-1970",
"datecertified": "1-2-1970",
"request_number": "5643"
},
{
"test_id": "0987",
"datetaken": "1-1-1970",
"datecertified": "1-2-1970",
"request_number": "5643"
}
]
}
}
|
[
"lists are mutable objects. Which means that list's are passed by reference.\nwhen you set\ndataset[student]['additional_information'] = case_dataset\n\ncase_dataset.clear()\n\nyou're setting the list and then clearing it. So the list inside additional_information is also cleared.\nCopy the list when setting it:\ndataset[student]['additional_information'] = case_dataset[:]\n\ncase_dataset.clear()\n\n",
"Thanks everyone for the guidance and pointing me in the right direction.\nI have what I'm looking for now. Based on some of the comments and troubleshooting, I updated my code. Here is what I did:\n\nI added back additional_dataset as a list\nRemoved case_dataset = defaultdict(dict) and case_dataset = dict(case_dataset) and replaced it with case_dataset = {}.\nUpdated dataset[student_name]['additional_information'] = case_dataset with dataset[student_name]['additional_information'] = additional_dataset\nReplaced case_dataset.clear() with case_dataset = {}\n\nHere is my new code now\ndef detail():\n student = 'John Doe'\n conn = get_db_connection()\n cur = conn.cursor()\n sql = (\"\"\"\n select\n a.student_name,\n a.student_id,\n a.student_homeroom_name,\n a.test_id,\n a.datetaken, \n a.datecertified,\n b.request_number\n FROM student_information a \n INNER JOIN homeroom b ON a.homeroom_id = b.homeroom_id\n WHERE a.student_name = '\"\"\" + student + \"\"\"'\n ORDER BY datecertified DESC \n \"\"\")\n cur.execute(sql)\n details=cur.fetchall()\n \n dataset = defaultdict(dict)\n case_dataset = {} #2 - Updated to just dict\n additional_dataset = [] #1 - added back additional_dataset as a list\n \n for student_name, student_id, student_homeroom_name, test_id, datetaken, datecertified, request_number in details:\n dataset[student_name]['student_id'] = student_id\n dataset[student_name]['student_homeroom_name'] = student_homeroom_name\n \n case_dataset['test_id'] = test_id\n case_dataset['datetaken'] = datetaken\n case_dataset['datecertified'] = datecertified\n case_dataset['request_number'] = request_number\n\n dataset[student_name]['additional_information'] = additional_dataset #3 - updated to additional_dataset\n\n case_dataset = {} #4 - updated to clear with new dict\n \n dataset= dict(dataset)\n print(dataset)\n\n cur.close()\n conn.close()\n\nThis is what it produces now. This is a much better structure then wat I was previously expecting.\n{\n \"John Doe\": {\n \"student_id\": \"1234\",\n \"student_homeroom_name\": \"HR1\",\n \"additional_information\": [\n {\n \"test_id\": \"0987\",\n \"datetaken\": \"1-1-1970\",\n \"datecertified\": \"1-2-1970\",\n \"request_number\": \"5643\"\n },\n {\n \"test_id\": \"12343\",\n \"datetaken\": \"1-1-1980\",\n \"datecertified\": \"1-2-1980\",\n \"request_number\": \"39807\"\n }\n ]\n }\n}\n\n"
] |
[
1,
0
] |
[] |
[] |
[
"dictionary",
"json",
"python",
"python_3.x"
] |
stackoverflow_0074499510_dictionary_json_python_python_3.x.txt
|
Q:
Unable to initiate a boiler plate fast api code
I come from Javascript land so this bit confusing to me.
I am trying to use this as a boiler plate code for a project: https://github.com/anthonycepeda/fastapi-sqlmodel
This is there for quick start
### Quickstart
1. <b>Start the App</b>:
2. Using Python:
`pipenv run python asgi.py`
3. sing Docker:
`docker build -t sqlmodel-api:latest . && docker run -p 8080:8080 sqlmodel-api:latest`
4. <b>Use Openapi at</b>: `http://localhost:8080/#/`
but there wasn't anything mention for installation.
So, to start with I did pip install and pipenv shell from here.
and then proceeded to run following command
pipenv run python asgi.py
This throws following error
File "/Users/userB/Desktop/fastapi-sql-blog/asgi.py", line 3, in <module>
from api.app import create_app
File "/Users/userB/Desktop/fastapi-sql-blog/api/app.py", line 3, in <module>
from api.config import settings
File "/Users/userB/Desktop/fastapi-sql-blog/api/config.py", line 21, in <module>
settings = Settings()
File "/Users/userB/.local/share/virtualenvs/fastapi-sql-blog-a9YFiCXV/lib/python3.9/site-packages/pydantic/env_settings.py", line 36, in __init__
super().__init__(
File "/Users/userB/.local/share/virtualenvs/fastapi-sql-blog-a9YFiCXV/lib/python3.9/site-packages/pydantic/main.py", line 406, in __init__
raise validation_error
pydantic.error_wrappers.ValidationError: 2 validation errors for Settings
ENV
field required (type=value_error.missing)
VERSION
field required (type=value_error.missing)
Any idea what I am doing wrong here?
A:
The error log explains the problem
ENV
field required (type=value_error.missing)
VERSION
field required (type=value_error.missing)
These two fields are mandatory when creating an instance of the class Settings. The exception is triggered on line settings = Settings() of "/Users/userB/Desktop/fastapi-sql-blog/api/config.py", line 21
Change therefore the instantation of the Settings class or add some default values
|
Unable to initiate a boiler plate fast api code
|
I come from Javascript land so this bit confusing to me.
I am trying to use this as a boiler plate code for a project: https://github.com/anthonycepeda/fastapi-sqlmodel
This is there for quick start
### Quickstart
1. <b>Start the App</b>:
2. Using Python:
`pipenv run python asgi.py`
3. sing Docker:
`docker build -t sqlmodel-api:latest . && docker run -p 8080:8080 sqlmodel-api:latest`
4. <b>Use Openapi at</b>: `http://localhost:8080/#/`
but there wasn't anything mention for installation.
So, to start with I did pip install and pipenv shell from here.
and then proceeded to run following command
pipenv run python asgi.py
This throws following error
File "/Users/userB/Desktop/fastapi-sql-blog/asgi.py", line 3, in <module>
from api.app import create_app
File "/Users/userB/Desktop/fastapi-sql-blog/api/app.py", line 3, in <module>
from api.config import settings
File "/Users/userB/Desktop/fastapi-sql-blog/api/config.py", line 21, in <module>
settings = Settings()
File "/Users/userB/.local/share/virtualenvs/fastapi-sql-blog-a9YFiCXV/lib/python3.9/site-packages/pydantic/env_settings.py", line 36, in __init__
super().__init__(
File "/Users/userB/.local/share/virtualenvs/fastapi-sql-blog-a9YFiCXV/lib/python3.9/site-packages/pydantic/main.py", line 406, in __init__
raise validation_error
pydantic.error_wrappers.ValidationError: 2 validation errors for Settings
ENV
field required (type=value_error.missing)
VERSION
field required (type=value_error.missing)
Any idea what I am doing wrong here?
|
[
"The error log explains the problem\nENV\n field required (type=value_error.missing)\nVERSION\n field required (type=value_error.missing)\n\nThese two fields are mandatory when creating an instance of the class Settings. The exception is triggered on line settings = Settings() of \"/Users/userB/Desktop/fastapi-sql-blog/api/config.py\", line 21\nChange therefore the instantation of the Settings class or add some default values\n"
] |
[
0
] |
[] |
[] |
[
"fastapi",
"python"
] |
stackoverflow_0074499456_fastapi_python.txt
|
Q:
Whenever i try to search elementS in selenium it only prints out 1 out of the maybe 100 possible
Whenever I try to search elements in selenium it only prints out 1 out of the maybe 100 possible. Here is my Code :
Edit: full Code :
*import time
import sys
from selenium import webdriver
from selenium.webdriver.common.by import By
stdoutOrigin=sys.stdout
sys.stdout = open("log.txt", "w")
driver = webdriver.Chrome (executable_path="C:\chromedriver.exe")
driver.get("https://ludwigbeck.mitarbeiterangebote.de/")
driver.find_element(By.ID, 'loginData[email]').send_keys("removed email")
driver.find_element(By.ID, 'loginData[password]').send_keys("removed password")
driver.find_element(By.NAME, 'cbg3-submit').click()
time.sleep(3)
driver.find_element(By.NAME, 'cbg3-submit').click()
for i in range(1, 10):
time.sleep(1)
driver.get("https://ludwigbeck.mitarbeiterangebote.de/search?s=*&page=" + str(i))
rabatte=driver.find_elements(By.CLASS_NAME, 'cbg3-list-item--discount')
for r in rabatte:
print(r.text)
driver.close()
sys.stdout.close()
sys.stdout=stdoutOrigin*
And all the class names are the same. I tried using other classes, but it it didn't helped
it didn't worked. I uploaded a video, link : youtu.be/GLBHTwRaQ0s . More informations in the video description
A:
Now you code collects rabatte only on the page https://ludwigbeck.mitarbeiterangebote.de/search?s=*&page=9. This code goes through search result pages and stops at opening the page 9:
for i in range(1, 10):
time.sleep(1)
driver.get("https://ludwigbeck.mitarbeiterangebote.de/search?s=*&page=" + str(i))
And after that, this code collects the elements you want only on the last page:
rabatte=driver.find_elements(By.CLASS_NAME, 'cbg3-list-item--discount')
Are you sure there are more than 1 element on this 9th page?
If you want to collect rabatte on each page you need to insert the second loop into the first loop:
for i in range(1, 10):
time.sleep(1)
driver.get("https://ludwigbeck.mitarbeiterangebote.de/search?s=*&page=" + str(i))
rabatte=driver.find_elements(By.CLASS_NAME, 'cbg3-list-item--discount')
for r in rabatte:
print(r.text)
|
Whenever i try to search elementS in selenium it only prints out 1 out of the maybe 100 possible
|
Whenever I try to search elements in selenium it only prints out 1 out of the maybe 100 possible. Here is my Code :
Edit: full Code :
*import time
import sys
from selenium import webdriver
from selenium.webdriver.common.by import By
stdoutOrigin=sys.stdout
sys.stdout = open("log.txt", "w")
driver = webdriver.Chrome (executable_path="C:\chromedriver.exe")
driver.get("https://ludwigbeck.mitarbeiterangebote.de/")
driver.find_element(By.ID, 'loginData[email]').send_keys("removed email")
driver.find_element(By.ID, 'loginData[password]').send_keys("removed password")
driver.find_element(By.NAME, 'cbg3-submit').click()
time.sleep(3)
driver.find_element(By.NAME, 'cbg3-submit').click()
for i in range(1, 10):
time.sleep(1)
driver.get("https://ludwigbeck.mitarbeiterangebote.de/search?s=*&page=" + str(i))
rabatte=driver.find_elements(By.CLASS_NAME, 'cbg3-list-item--discount')
for r in rabatte:
print(r.text)
driver.close()
sys.stdout.close()
sys.stdout=stdoutOrigin*
And all the class names are the same. I tried using other classes, but it it didn't helped
it didn't worked. I uploaded a video, link : youtu.be/GLBHTwRaQ0s . More informations in the video description
|
[
"Now you code collects rabatte only on the page https://ludwigbeck.mitarbeiterangebote.de/search?s=*&page=9. This code goes through search result pages and stops at opening the page 9:\nfor i in range(1, 10):\n time.sleep(1)\n driver.get(\"https://ludwigbeck.mitarbeiterangebote.de/search?s=*&page=\" + str(i))\n\nAnd after that, this code collects the elements you want only on the last page:\nrabatte=driver.find_elements(By.CLASS_NAME, 'cbg3-list-item--discount')\n\nAre you sure there are more than 1 element on this 9th page?\nIf you want to collect rabatte on each page you need to insert the second loop into the first loop:\nfor i in range(1, 10):\n time.sleep(1)\n driver.get(\"https://ludwigbeck.mitarbeiterangebote.de/search?s=*&page=\" + str(i))\n rabatte=driver.find_elements(By.CLASS_NAME, 'cbg3-list-item--discount')\n for r in rabatte:\n print(r.text)\n\n"
] |
[
0
] |
[] |
[] |
[
"python",
"selenium"
] |
stackoverflow_0074497977_python_selenium.txt
|
Q:
How to verify integrity of files using digest in python (SHA256SUMS)
I have a set of files and a SHA256SUMS digest file that contains a sha256() hash for each of the files. What's the best way to verify the integrity of my files with python?
For example, here's how I would download the Debian 10 net installer SHA256SUMS digest file and download/verify its the MANIFEST file in BASH
user@host:~$ wget http://ftp.nl.debian.org/debian/dists/buster/main/installer-amd64/current/images/SHA256SUMS
--2020-08-25 02:11:20-- http://ftp.nl.debian.org/debian/dists/buster/main/installer-amd64/current/images/SHA256SUMS
Resolving ftp.nl.debian.org (ftp.nl.debian.org)... 130.89.149.21, 2001:67c:2564:a120::21
Connecting to ftp.nl.debian.org (ftp.nl.debian.org)|130.89.149.21|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 75295 (74K)
Saving to: ‘SHA256SUMS’
SHA256SUMS 100%[===================>] 73.53K 71.7KB/s in 1.0s
2020-08-25 02:11:22 (71.7 KB/s) - ‘SHA256SUMS’ saved [75295/75295]
user@host:~$ wget http://ftp.nl.debian.org/debian/dists/buster/main/installer-amd64/current/images/MANIFEST
--2020-08-25 02:11:27-- http://ftp.nl.debian.org/debian/dists/buster/main/installer-amd64/current/images/MANIFEST
Resolving ftp.nl.debian.org (ftp.nl.debian.org)... 130.89.149.21, 2001:67c:2564:a120::21
Connecting to ftp.nl.debian.org (ftp.nl.debian.org)|130.89.149.21|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 1709 (1.7K)
Saving to: ‘MANIFEST’
MANIFEST 100%[===================>] 1.67K --.-KB/s in 0s
2020-08-25 02:11:28 (128 MB/s) - ‘MANIFEST’ saved [1709/1709]
user@host:~$ sha256sum --check --ignore-missing SHA256SUMS
./MANIFEST: OK
user@host:~$
What is the best way to do this same operation (download and verify the integrity of the Debian 10 MANIFEST file using the SHA256SUMS file) in python?
A:
The following python script implements a function named integrity_is_ok() that takes the path to a SHA256SUMS file and a list of files to be verified, and it returns False if any of the files couldn't be verified and True otherwise.
#!/usr/bin/env python3
from hashlib import sha256
import os
# Takes the path (as a string) to a SHA256SUMS file and a list of paths to
# local files. Returns true only if all files' checksums are present in the
# SHA256SUMS file and their checksums match
def integrity_is_ok( sha256sums_filepath, local_filepaths ):
# first we parse the SHA256SUMS file and convert it into a dictionary
sha256sums = dict()
with open( sha256sums_filepath ) as fd:
for line in fd:
# sha256 hashes are exactly 64 characters long
checksum = line[0:64]
# there is one space followed by one metadata character between the
# checksum and the filename in the `sha256sum` command output
filename = os.path.split( line[66:] )[1].strip()
sha256sums[filename] = checksum
# now loop through each file that we were asked to check and confirm its
# checksum matches what was listed in the SHA256SUMS file
for local_file in local_filepaths:
local_filename = os.path.split( local_file )[1]
sha256sum = sha256()
with open( local_file, 'rb' ) as fd:
data_chunk = fd.read(1024)
while data_chunk:
sha256sum.update(data_chunk)
data_chunk = fd.read(1024)
checksum = sha256sum.hexdigest()
if checksum != sha256sums[local_filename]:
return False
return True
if __name__ == '__main__':
script_dir = os.path.split( os.path.realpath(__file__) )[0]
sha256sums_filepath = script_dir + '/SHA256SUMS'
local_filepaths = [ script_dir + '/MANIFEST' ]
if integrity_is_ok( sha256sums_filepath, local_filepaths ):
print( "INFO: Checksum OK" )
else:
print( "ERROR: Checksum Invalid" )
Here is an example execution:
user@host:~$ wget http://ftp.nl.debian.org/debian/dists/buster/main/installer-amd64/current/images/SHA256SUMS
--2020-08-25 22:40:16-- http://ftp.nl.debian.org/debian/dists/buster/main/installer-amd64/current/images/SHA256SUMS
Resolving ftp.nl.debian.org (ftp.nl.debian.org)... 130.89.149.21, 2001:67c:2564:a120::21
Connecting to ftp.nl.debian.org (ftp.nl.debian.org)|130.89.149.21|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 75295 (74K)
Saving to: ‘SHA256SUMS’
SHA256SUMS 100%[===================>] 73.53K 201KB/s in 0.4s
2020-08-25 22:40:17 (201 KB/s) - ‘SHA256SUMS’ saved [75295/75295]
user@host:~$ wget http://ftp.nl.debian.org/debian/dists/buster/main/installer-amd64/current/images/MANIFEST
--2020-08-25 22:40:32-- http://ftp.nl.debian.org/debian/dists/buster/main/installer-amd64/current/images/MANIFEST
Resolving ftp.nl.debian.org (ftp.nl.debian.org)... 130.89.149.21, 2001:67c:2564:a120::21
Connecting to ftp.nl.debian.org (ftp.nl.debian.org)|130.89.149.21|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 1709 (1.7K)
Saving to: ‘MANIFEST’
MANIFEST 100%[===================>] 1.67K --.-KB/s in 0s
2020-08-25 22:40:32 (13.0 MB/s) - ‘MANIFEST’ saved [1709/1709]
user@host:~$ ./sha256sums_python.py
INFO: Checksum OK
user@host:~$
Parts of the above code were adapted from the following answer on Ask Ubuntu:
https://askubuntu.com/questions/638459/how-to-automate-the-process-of-checking-an-ubuntu-iso-sha256sum
A:
You may calculate the sha256sums of each file as described in this blog post:
https://www.quickprogrammingtips.com/python/how-to-calculate-sha256-hash-of-a-file-in-python.html
A sample implementation to generate a new manifest file may look like:
import hashlib
from pathlib import Path
# Your output file
output_file = "manifest-check"
# Your target directory
p = Path('.')
sha256_hash = hashlib.sha256()
with open(output_file, "w") as out:
# Iterate over the files in the directory
for f in p.glob("**/*"):
# Process files only (no subdirs)
if f.is_file():
with open(filename,"rb") as f:
# Read the file by chunks
for byte_block in iter(lambda: f.read(4096),b""):
sha256_hash.update(byte_block)
out.write(f + "\t" + sha256_hash.hexdigest() + "\n")
Alternatively, this seems to be achieved by manifest-checker pip package.
You may have a look at its source here
https://github.com/TonyFlury/manifest-checkerand adjust it for python 3
A:
Python 3.11 added hashlib.file_digest()
https://docs.python.org/3.11/library/hashlib.html#file-hashing
Generating the digest for a file:
with open("my_file", "rb") as f:
digest = hashlib.file_digest(f, "sha256")
s = digest.hexdigest()
Compare s against the information you have in SHA256SUMS.
|
How to verify integrity of files using digest in python (SHA256SUMS)
|
I have a set of files and a SHA256SUMS digest file that contains a sha256() hash for each of the files. What's the best way to verify the integrity of my files with python?
For example, here's how I would download the Debian 10 net installer SHA256SUMS digest file and download/verify its the MANIFEST file in BASH
user@host:~$ wget http://ftp.nl.debian.org/debian/dists/buster/main/installer-amd64/current/images/SHA256SUMS
--2020-08-25 02:11:20-- http://ftp.nl.debian.org/debian/dists/buster/main/installer-amd64/current/images/SHA256SUMS
Resolving ftp.nl.debian.org (ftp.nl.debian.org)... 130.89.149.21, 2001:67c:2564:a120::21
Connecting to ftp.nl.debian.org (ftp.nl.debian.org)|130.89.149.21|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 75295 (74K)
Saving to: ‘SHA256SUMS’
SHA256SUMS 100%[===================>] 73.53K 71.7KB/s in 1.0s
2020-08-25 02:11:22 (71.7 KB/s) - ‘SHA256SUMS’ saved [75295/75295]
user@host:~$ wget http://ftp.nl.debian.org/debian/dists/buster/main/installer-amd64/current/images/MANIFEST
--2020-08-25 02:11:27-- http://ftp.nl.debian.org/debian/dists/buster/main/installer-amd64/current/images/MANIFEST
Resolving ftp.nl.debian.org (ftp.nl.debian.org)... 130.89.149.21, 2001:67c:2564:a120::21
Connecting to ftp.nl.debian.org (ftp.nl.debian.org)|130.89.149.21|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 1709 (1.7K)
Saving to: ‘MANIFEST’
MANIFEST 100%[===================>] 1.67K --.-KB/s in 0s
2020-08-25 02:11:28 (128 MB/s) - ‘MANIFEST’ saved [1709/1709]
user@host:~$ sha256sum --check --ignore-missing SHA256SUMS
./MANIFEST: OK
user@host:~$
What is the best way to do this same operation (download and verify the integrity of the Debian 10 MANIFEST file using the SHA256SUMS file) in python?
|
[
"The following python script implements a function named integrity_is_ok() that takes the path to a SHA256SUMS file and a list of files to be verified, and it returns False if any of the files couldn't be verified and True otherwise.\n#!/usr/bin/env python3\nfrom hashlib import sha256\nimport os\n\n# Takes the path (as a string) to a SHA256SUMS file and a list of paths to\n# local files. Returns true only if all files' checksums are present in the\n# SHA256SUMS file and their checksums match\ndef integrity_is_ok( sha256sums_filepath, local_filepaths ):\n\n # first we parse the SHA256SUMS file and convert it into a dictionary\n sha256sums = dict()\n with open( sha256sums_filepath ) as fd:\n for line in fd:\n # sha256 hashes are exactly 64 characters long\n checksum = line[0:64]\n\n # there is one space followed by one metadata character between the\n # checksum and the filename in the `sha256sum` command output\n filename = os.path.split( line[66:] )[1].strip()\n sha256sums[filename] = checksum\n\n # now loop through each file that we were asked to check and confirm its\n # checksum matches what was listed in the SHA256SUMS file\n for local_file in local_filepaths:\n\n local_filename = os.path.split( local_file )[1]\n\n sha256sum = sha256()\n with open( local_file, 'rb' ) as fd:\n data_chunk = fd.read(1024)\n while data_chunk:\n sha256sum.update(data_chunk)\n data_chunk = fd.read(1024)\n\n checksum = sha256sum.hexdigest()\n if checksum != sha256sums[local_filename]:\n return False\n\n return True\n\nif __name__ == '__main__':\n\n script_dir = os.path.split( os.path.realpath(__file__) )[0]\n sha256sums_filepath = script_dir + '/SHA256SUMS'\n local_filepaths = [ script_dir + '/MANIFEST' ]\n\n if integrity_is_ok( sha256sums_filepath, local_filepaths ):\n print( \"INFO: Checksum OK\" )\n else:\n print( \"ERROR: Checksum Invalid\" )\n\nHere is an example execution:\nuser@host:~$ wget http://ftp.nl.debian.org/debian/dists/buster/main/installer-amd64/current/images/SHA256SUMS\n--2020-08-25 22:40:16-- http://ftp.nl.debian.org/debian/dists/buster/main/installer-amd64/current/images/SHA256SUMS\nResolving ftp.nl.debian.org (ftp.nl.debian.org)... 130.89.149.21, 2001:67c:2564:a120::21\nConnecting to ftp.nl.debian.org (ftp.nl.debian.org)|130.89.149.21|:80... connected.\nHTTP request sent, awaiting response... 200 OK\nLength: 75295 (74K)\nSaving to: ‘SHA256SUMS’\n\nSHA256SUMS 100%[===================>] 73.53K 201KB/s in 0.4s \n\n2020-08-25 22:40:17 (201 KB/s) - ‘SHA256SUMS’ saved [75295/75295]\n\nuser@host:~$ wget http://ftp.nl.debian.org/debian/dists/buster/main/installer-amd64/current/images/MANIFEST\n--2020-08-25 22:40:32-- http://ftp.nl.debian.org/debian/dists/buster/main/installer-amd64/current/images/MANIFEST\nResolving ftp.nl.debian.org (ftp.nl.debian.org)... 130.89.149.21, 2001:67c:2564:a120::21\nConnecting to ftp.nl.debian.org (ftp.nl.debian.org)|130.89.149.21|:80... connected.\nHTTP request sent, awaiting response... 200 OK\nLength: 1709 (1.7K)\nSaving to: ‘MANIFEST’\n\nMANIFEST 100%[===================>] 1.67K --.-KB/s in 0s \n\n2020-08-25 22:40:32 (13.0 MB/s) - ‘MANIFEST’ saved [1709/1709]\n\nuser@host:~$ ./sha256sums_python.py \nINFO: Checksum OK\nuser@host:~$ \n\nParts of the above code were adapted from the following answer on Ask Ubuntu:\n\nhttps://askubuntu.com/questions/638459/how-to-automate-the-process-of-checking-an-ubuntu-iso-sha256sum\n\n",
"You may calculate the sha256sums of each file as described in this blog post:\nhttps://www.quickprogrammingtips.com/python/how-to-calculate-sha256-hash-of-a-file-in-python.html\nA sample implementation to generate a new manifest file may look like:\nimport hashlib\nfrom pathlib import Path\n\n# Your output file\noutput_file = \"manifest-check\"\n\n# Your target directory\np = Path('.')\n\nsha256_hash = hashlib.sha256()\n\nwith open(output_file, \"w\") as out:\n # Iterate over the files in the directory\n for f in p.glob(\"**/*\"):\n # Process files only (no subdirs)\n if f.is_file():\n with open(filename,\"rb\") as f:\n # Read the file by chunks\n for byte_block in iter(lambda: f.read(4096),b\"\"):\n sha256_hash.update(byte_block)\n out.write(f + \"\\t\" + sha256_hash.hexdigest() + \"\\n\")\n\n\nAlternatively, this seems to be achieved by manifest-checker pip package.\nYou may have a look at its source here\nhttps://github.com/TonyFlury/manifest-checkerand adjust it for python 3\n",
"Python 3.11 added hashlib.file_digest()\nhttps://docs.python.org/3.11/library/hashlib.html#file-hashing\nGenerating the digest for a file:\nwith open(\"my_file\", \"rb\") as f:\n digest = hashlib.file_digest(f, \"sha256\")\n s = digest.hexdigest()\n\nCompare s against the information you have in SHA256SUMS.\n"
] |
[
1,
0,
0
] |
[] |
[] |
[
"checksum",
"data_integrity",
"python",
"python_3.x",
"sha256"
] |
stackoverflow_0063568328_checksum_data_integrity_python_python_3.x_sha256.txt
|
Q:
Changing static class variables
How is it possible to change static variables of a class? I want it to be changed by some sort of input.
class MyClass:
var1 = 1
var2 = 4
def __init__(self, var3, var4):
self.var3 = var3
self.var4 = var4
It is var1 og var2 that i want to be changable, or want to know how to change.
A:
class Whatever():
b = 5
def __init__(self):
Whatever.b = 9999
boo = Whatever()
print(boo.b) # prints 9999
boo.b = 500
print(boo.b) # prints 500
Whatever.b = 400
print(boo.b) # prints 500
# since its a static var you can always access it through class name
# Whatever.b
A:
If you want to change the class variables, you can assign them to the variables in the __init__ scope:
class MyClass:
var1 = 1
var2 = 4
def __init__(self, var3, var4):
self.var1 = var3
self.var2 = var4
c = MyClass(100, 200)
>>>c.var1, c.var2
Output:
(100, 200)
A:
It depends when you need to rebind the class attributes. You can also do so later when the object is created:
mc = MyClass(1, 2)
mc.var1 = 20
mc.var2 = 40
There is no difference between an attribute created or changed within the class body to one created outside by assigning to an attribute.
A:
You can change the class variables by class name as shown below:
class MyClass:
var1 = 1
var2 = 2
MyClass.var1 = 10 # By class name
MyClass.var2 = 20 # By class name
print(MyClass.var1) # Class variable
print(MyClass.var2) # Class variable
Output:
10
20
Be careful, if you try to change the class variables by object, you are actually adding new instance variables but not changing the class variables as shown below:
class MyClass:
var1 = 1
var2 = 2
obj = MyClass()
obj.var1 = 10 # Adding a new instance variable but not changing the class variable
obj.var2 = 20 # Adding a new instance variable but not changing the class variable
print(MyClass.var1) # Class variable
print(MyClass.var2) # Class variable
print(obj.var1) # New instance variable
print(obj.var2) # New instance variable
Output:
1
2
10
20
|
Changing static class variables
|
How is it possible to change static variables of a class? I want it to be changed by some sort of input.
class MyClass:
var1 = 1
var2 = 4
def __init__(self, var3, var4):
self.var3 = var3
self.var4 = var4
It is var1 og var2 that i want to be changable, or want to know how to change.
|
[
"class Whatever():\n b = 5\n def __init__(self):\n Whatever.b = 9999\n\nboo = Whatever()\nprint(boo.b) # prints 9999\n\nboo.b = 500\nprint(boo.b) # prints 500\n\nWhatever.b = 400\nprint(boo.b) # prints 500\n\n# since its a static var you can always access it through class name\n# Whatever.b\n\n",
"If you want to change the class variables, you can assign them to the variables in the __init__ scope:\nclass MyClass: \n var1 = 1\n var2 = 4\n def __init__(self, var3, var4):\n self.var1 = var3\n self.var2 = var4\n\nc = MyClass(100, 200)\n>>>c.var1, c.var2\n\nOutput:\n(100, 200)\n\n",
"It depends when you need to rebind the class attributes. You can also do so later when the object is created:\nmc = MyClass(1, 2)\nmc.var1 = 20\nmc.var2 = 40\n\nThere is no difference between an attribute created or changed within the class body to one created outside by assigning to an attribute.\n",
"You can change the class variables by class name as shown below:\nclass MyClass: \n var1 = 1\n var2 = 2\n \nMyClass.var1 = 10 # By class name\nMyClass.var2 = 20 # By class name\n\nprint(MyClass.var1) # Class variable\nprint(MyClass.var2) # Class variable\n\nOutput:\n10\n20\n\nBe careful, if you try to change the class variables by object, you are actually adding new instance variables but not changing the class variables as shown below:\nclass MyClass: \n var1 = 1 \n var2 = 2 \n \nobj = MyClass()\nobj.var1 = 10 # Adding a new instance variable but not changing the class variable\nobj.var2 = 20 # Adding a new instance variable but not changing the class variable\n\nprint(MyClass.var1) # Class variable\nprint(MyClass.var2) # Class variable\nprint(obj.var1) # New instance variable\nprint(obj.var2) # New instance variable\n\nOutput:\n1\n2\n10\n20\n\n"
] |
[
4,
0,
0,
0
] |
[] |
[] |
[
"class",
"class_variables",
"python",
"static_variables"
] |
stackoverflow_0048240905_class_class_variables_python_static_variables.txt
|
Q:
Checkbox ALWAYS returns False/ not in request.POST - Django
I have a checkbox on my django app, where user can add or remove a listing from their watchlist.
However, this checkbox always returns False, and is never in request.POST, i have tried sooo many solutions from SO and all over the internet for literal days now and cant figure it out
Models.py
class Watchlists(models.Model):
user = models.CharField(max_length=64, default='user')
title = models.CharField(max_length=64, blank=True)
watchlist = models.BooleanField(default=False, blank=False)
def __str__(self):
return f"{self.title}, {self.user}, {self.watchlist}"
Forms.py
class CheckForm(ModelForm):
watchlist = forms.BooleanField(required=False)
# watchlist = forms.DecimalField(widget=forms.CheckboxInput(attrs={"value":"watchlist"}))
class Meta:
model = Watchlists
fields = ['watchlist']
Checkbox didnt have a value so i thought that was the issue and tried to give it one here on the commented line, it didnt help
Views.py
watchlist = CheckForm(request.POST or None)
if request.method == 'POST':
# if request.POST['watchlist']:
# if 'watchlist' in request.POST:
# if request.POST.get('watchlist', False):
if request.POST.get('watchlist', '') == 'on':
if watchlist.is_valid():
check = watchlist.cleaned_data['watchlist']
watchlist_data = Watchlists.objects.all().filter(title=title, user=username).first()
if not watchlist_data:
watchlisted = Watchlists.objects.create(title=title, user=username, watchlist='True')
watchlisted.save()
if watchlist_data:
watchlist_data.delete()
I have tried all the different solutions i could find
**Template**
<form action="listing" method="POST">
{% csrf_token %}
{{ checkbox }}
</form>
It has a name and id attribute, label is fine too
**Entire views.py**
@login_required
def listing(request, title):
if request.user.is_authenticated:
username = request.user.get_username()
form = BidForm()
comment_form = CommentForm()
watchlist = CheckForm(request.POST or None)
listing_object = Listing.objects.all().filter(title=title).first()
author = listing_object.user
bids = Bid.objects.all().filter(title=title).values_list("price", flat=True)
max_bid = max(bids, default=0)
comments = Comment.objects.all().filter(list_title=title)
if request.method == "POST":
bid = Bid(title=title, user=username)
bidform = BidForm(request.POST, request.FILES, instance=bid)
# if request.POST['watchlist']:
# if 'watchlist' in request.POST:
# if request.POST.get('watchlist', False):
if request.POST.get('watchlist', '') == 'on':
if watchlist.is_valid():
check = watchlist.cleaned_data['watchlist']
watchlist_data = Watchlists.objects.all().filter(title=title, user=username).first()
if not watchlist_data:
watchlisted = Watchlists.objects.create(title=title, user=username, watchlist='True')
watchlisted.save()
if watchlist_data:
watchlist_data.delete()
if "price" in request.POST:
if bidform.is_valid():
price = bid.price
if not bids:
bid = bidform.save()
messages.success(request, 'Your bid has been placed succesfully')
return HttpResponseRedirect(reverse('listing', args=(), kwargs={'title': title}))
else:
max_bid = max(bids)
if price >= listing_object.price and price > max_bid:
bid = bidform.save()
messages.success(request, 'Your bid has been placed succesfully')
return HttpResponseRedirect(reverse('listing', args=(), kwargs={'title': title}))
else:
messages.warning(request, 'Bid price must be greater than highest bid and starting price')
return HttpResponseRedirect(reverse('listing', args=(), kwargs={'title': title}))
if "close" in request.POST:
bid = Bid.objects.all().filter(title=title, price=max_bid).first()
max_bid_user = bid.user
listing_object.tag = 'closed'
listing_object.save()
if username == max_bid_user:
messages.warning(request, 'Thank you for your entry into this auction. You have emerged the winner and this listing has been closed')
return HttpResponseRedirect(reverse('listing', args=(), kwargs={'title': title}))
comment = Comment(user_commented=username, list_title=title, list_author=author)
comment_form = CommentForm(request.POST, request.FILES, instance=comment)
if "comment" in request.POST:
if comment_form.is_valid():
user_comment = comment_form.save()
comments = Comment.objects.all().filter(list_title=title)
return HttpResponseRedirect(reverse('listing', args=(), kwargs={'title': title}))
return render(request, "auctions/listing.html", {
"form": form,
"listing": listing_object,
"checkbox": watchlist,
"max_bid": max_bid,
"users": author,
"commentform": comment_form,
"comments": comments
})
urls.py
path("auctions/<str:title>/", views.listing, name="listing"),
A:
First, you don't have to add blank=False in your watchlist field since you gave it a default value, so rewrite it like so
watchlist = models.BooleanField(default=False)
By doing so, you can also remove this from your forms.py. It's not necessary
watchlist = forms.BooleanField(required=False)
Just use as follows
class CheckForm(ModelForm):
class Meta:
model = Watchlists
fields = ['watchlist']
Additional things to fix based on @Sunderam Dubey's comment
In your HTML form, change action="listing" to action="{% url 'listing' %}"
|
Checkbox ALWAYS returns False/ not in request.POST - Django
|
I have a checkbox on my django app, where user can add or remove a listing from their watchlist.
However, this checkbox always returns False, and is never in request.POST, i have tried sooo many solutions from SO and all over the internet for literal days now and cant figure it out
Models.py
class Watchlists(models.Model):
user = models.CharField(max_length=64, default='user')
title = models.CharField(max_length=64, blank=True)
watchlist = models.BooleanField(default=False, blank=False)
def __str__(self):
return f"{self.title}, {self.user}, {self.watchlist}"
Forms.py
class CheckForm(ModelForm):
watchlist = forms.BooleanField(required=False)
# watchlist = forms.DecimalField(widget=forms.CheckboxInput(attrs={"value":"watchlist"}))
class Meta:
model = Watchlists
fields = ['watchlist']
Checkbox didnt have a value so i thought that was the issue and tried to give it one here on the commented line, it didnt help
Views.py
watchlist = CheckForm(request.POST or None)
if request.method == 'POST':
# if request.POST['watchlist']:
# if 'watchlist' in request.POST:
# if request.POST.get('watchlist', False):
if request.POST.get('watchlist', '') == 'on':
if watchlist.is_valid():
check = watchlist.cleaned_data['watchlist']
watchlist_data = Watchlists.objects.all().filter(title=title, user=username).first()
if not watchlist_data:
watchlisted = Watchlists.objects.create(title=title, user=username, watchlist='True')
watchlisted.save()
if watchlist_data:
watchlist_data.delete()
I have tried all the different solutions i could find
**Template**
<form action="listing" method="POST">
{% csrf_token %}
{{ checkbox }}
</form>
It has a name and id attribute, label is fine too
**Entire views.py**
@login_required
def listing(request, title):
if request.user.is_authenticated:
username = request.user.get_username()
form = BidForm()
comment_form = CommentForm()
watchlist = CheckForm(request.POST or None)
listing_object = Listing.objects.all().filter(title=title).first()
author = listing_object.user
bids = Bid.objects.all().filter(title=title).values_list("price", flat=True)
max_bid = max(bids, default=0)
comments = Comment.objects.all().filter(list_title=title)
if request.method == "POST":
bid = Bid(title=title, user=username)
bidform = BidForm(request.POST, request.FILES, instance=bid)
# if request.POST['watchlist']:
# if 'watchlist' in request.POST:
# if request.POST.get('watchlist', False):
if request.POST.get('watchlist', '') == 'on':
if watchlist.is_valid():
check = watchlist.cleaned_data['watchlist']
watchlist_data = Watchlists.objects.all().filter(title=title, user=username).first()
if not watchlist_data:
watchlisted = Watchlists.objects.create(title=title, user=username, watchlist='True')
watchlisted.save()
if watchlist_data:
watchlist_data.delete()
if "price" in request.POST:
if bidform.is_valid():
price = bid.price
if not bids:
bid = bidform.save()
messages.success(request, 'Your bid has been placed succesfully')
return HttpResponseRedirect(reverse('listing', args=(), kwargs={'title': title}))
else:
max_bid = max(bids)
if price >= listing_object.price and price > max_bid:
bid = bidform.save()
messages.success(request, 'Your bid has been placed succesfully')
return HttpResponseRedirect(reverse('listing', args=(), kwargs={'title': title}))
else:
messages.warning(request, 'Bid price must be greater than highest bid and starting price')
return HttpResponseRedirect(reverse('listing', args=(), kwargs={'title': title}))
if "close" in request.POST:
bid = Bid.objects.all().filter(title=title, price=max_bid).first()
max_bid_user = bid.user
listing_object.tag = 'closed'
listing_object.save()
if username == max_bid_user:
messages.warning(request, 'Thank you for your entry into this auction. You have emerged the winner and this listing has been closed')
return HttpResponseRedirect(reverse('listing', args=(), kwargs={'title': title}))
comment = Comment(user_commented=username, list_title=title, list_author=author)
comment_form = CommentForm(request.POST, request.FILES, instance=comment)
if "comment" in request.POST:
if comment_form.is_valid():
user_comment = comment_form.save()
comments = Comment.objects.all().filter(list_title=title)
return HttpResponseRedirect(reverse('listing', args=(), kwargs={'title': title}))
return render(request, "auctions/listing.html", {
"form": form,
"listing": listing_object,
"checkbox": watchlist,
"max_bid": max_bid,
"users": author,
"commentform": comment_form,
"comments": comments
})
urls.py
path("auctions/<str:title>/", views.listing, name="listing"),
|
[
"First, you don't have to add blank=False in your watchlist field since you gave it a default value, so rewrite it like so\nwatchlist = models.BooleanField(default=False)\n\nBy doing so, you can also remove this from your forms.py. It's not necessary\nwatchlist = forms.BooleanField(required=False)\n\nJust use as follows\nclass CheckForm(ModelForm):\n class Meta:\n model = Watchlists\n fields = ['watchlist']\n\nAdditional things to fix based on @Sunderam Dubey's comment\nIn your HTML form, change action=\"listing\" to action=\"{% url 'listing' %}\"\n"
] |
[
1
] |
[] |
[] |
[
"checkbox",
"django",
"python"
] |
stackoverflow_0074499927_checkbox_django_python.txt
|
Q:
How does the name end up getting capitalized?
### Greeting people more formally ###
def get_formatted_name(first_name, last_name):
"""Return a full name, neatly formatted."""
full_name = f"{first_name} {last_name}"
return full_name.title()
# This is an infinite loop!
while True:
print("\nPlease tell me your name:")
print("(enter 'q' at any time to quit)")
f_name = input("first name: ")
if f_name == 'q':
break
l_name = input("Last name: ")
if l_name == 'q':
break
formatted_name = get_formatted_name(f_name, l_name)
print(f"\nHello, {formatted_name}!")
Please tell me your name:
(enter 'q' at any time to quit)
first name: john
Last name: doe
Hello, John Doe!
Please tell me your name:
(enter 'q' at any time to quit)
first name:
Last name: q
***Repl Closed***
I am a beginner when it comes to coding.
My question is, why is the name... capitalized?
Im confused at the lower part of the first code
The inputs end up under the values (f_name and l_name)
formatted_name = get_formatted_name(f_name, l_name)
inputs go into the function...
the get_formatted_name fuction gets thrown up and applied in the earlier code?
def get_formatted_name(first_name, last_name):
"""Return a full name, neatly formatted."""
full_name = f"{first_name} {last_name}"
return full_name.title()
this one?
ends up being returned to python as the full_name.title()
and that ends up being what formatted_name equals... right?
because full_name.title() came as a result of the function get_formatted_name
and get_formatted_name equals formatted_name
therefore that is the process of how the name gets capitalized right?
sooooo**....**
have an input, function sends the input to the earlier function, function processes and refines the input and returns it back into the code, whatever is returned is made equal to formatted_name.... and then ends up being printed out... yes?
does that mean that f_name serves as an input for first_name in this case?
same for l_name? I think that is what threw me off..
This code is from a book called
Python Crash Course 2nd Edition
page 141
A:
Short, but harsh:
https://google.com/search?q=string+title+python+3+docs
https://docs.python.org/3/library/stdtypes.html?highlight=title#str.title
Longer:
str.title()
Return a titlecased version of the string where words start with an uppercase character and the remaining characters are lowercase.
|
How does the name end up getting capitalized?
|
### Greeting people more formally ###
def get_formatted_name(first_name, last_name):
"""Return a full name, neatly formatted."""
full_name = f"{first_name} {last_name}"
return full_name.title()
# This is an infinite loop!
while True:
print("\nPlease tell me your name:")
print("(enter 'q' at any time to quit)")
f_name = input("first name: ")
if f_name == 'q':
break
l_name = input("Last name: ")
if l_name == 'q':
break
formatted_name = get_formatted_name(f_name, l_name)
print(f"\nHello, {formatted_name}!")
Please tell me your name:
(enter 'q' at any time to quit)
first name: john
Last name: doe
Hello, John Doe!
Please tell me your name:
(enter 'q' at any time to quit)
first name:
Last name: q
***Repl Closed***
I am a beginner when it comes to coding.
My question is, why is the name... capitalized?
Im confused at the lower part of the first code
The inputs end up under the values (f_name and l_name)
formatted_name = get_formatted_name(f_name, l_name)
inputs go into the function...
the get_formatted_name fuction gets thrown up and applied in the earlier code?
def get_formatted_name(first_name, last_name):
"""Return a full name, neatly formatted."""
full_name = f"{first_name} {last_name}"
return full_name.title()
this one?
ends up being returned to python as the full_name.title()
and that ends up being what formatted_name equals... right?
because full_name.title() came as a result of the function get_formatted_name
and get_formatted_name equals formatted_name
therefore that is the process of how the name gets capitalized right?
sooooo**....**
have an input, function sends the input to the earlier function, function processes and refines the input and returns it back into the code, whatever is returned is made equal to formatted_name.... and then ends up being printed out... yes?
does that mean that f_name serves as an input for first_name in this case?
same for l_name? I think that is what threw me off..
This code is from a book called
Python Crash Course 2nd Edition
page 141
|
[
"Short, but harsh:\nhttps://google.com/search?q=string+title+python+3+docs\nhttps://docs.python.org/3/library/stdtypes.html?highlight=title#str.title\nLonger:\nstr.title()\n\nReturn a titlecased version of the string where words start with an uppercase character and the remaining characters are lowercase.\n\n"
] |
[
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0074500018_python.txt
|
Q:
Problems with Chrome webdriver
Getting started with using Chrome webdrivers and selenium. When I execute the code:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
driver = webdriver.Chrome(executable_path = \
r"C:\Users\payto\Downloads\chromedriver_win32.zip\chromedriver.exe")
I keep getting this error:
WebDriverException: 'chromedriver.exe' executable needs to be in PATH. Please see https://sites.google.com/a/chromium.org/chromedriver/home
I've looked up how to solve it, but anything I see says to install a webdriver...which I've already done. My Chrome version is 107 and that's the one I downloaded, so it should be working but it's not. Any tips?
A:
You can use webdriver_manager instead of constantly setting executable_path and chromedriver yourself.
For chrome driver:
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
it will automatically download the appropriate chromedriver. if it's already loaded, it finds it in the cache and uses it directly.
A:
Solution
You can get rid of all driver versions issues by using ChromeDriverManager
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
driver.maximize_window()
driver.get("https://www.google.com")
OR Fixing the issue in your existing code like ..
Downloading a specific version of ChromeDriver you can use the following code block:
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
s = Service('C:/Users/hp/Downloads/chromedriver/chromedriver.exe')
driver = webdriver.Chrome(service=s)
You can find more discussion here, hope this will help you.
A:
You actually have to install the Chrome Browser on you machine.
Go to https://www.google.com/intl/en_en/chrome/, download and install it.
It is needed to run Selenium/ Chrome.
|
Problems with Chrome webdriver
|
Getting started with using Chrome webdrivers and selenium. When I execute the code:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
driver = webdriver.Chrome(executable_path = \
r"C:\Users\payto\Downloads\chromedriver_win32.zip\chromedriver.exe")
I keep getting this error:
WebDriverException: 'chromedriver.exe' executable needs to be in PATH. Please see https://sites.google.com/a/chromium.org/chromedriver/home
I've looked up how to solve it, but anything I see says to install a webdriver...which I've already done. My Chrome version is 107 and that's the one I downloaded, so it should be working but it's not. Any tips?
|
[
"You can use webdriver_manager instead of constantly setting executable_path and chromedriver yourself.\nFor chrome driver:\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\nfrom webdriver_manager.chrome import ChromeDriverManager\n\ndriver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))\n\nit will automatically download the appropriate chromedriver. if it's already loaded, it finds it in the cache and uses it directly.\n",
"Solution\nYou can get rid of all driver versions issues by using ChromeDriverManager\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\nfrom webdriver_manager.chrome import ChromeDriverManager\n\ndriver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))\ndriver.maximize_window()\ndriver.get(\"https://www.google.com\")\n\nOR Fixing the issue in your existing code like ..\nDownloading a specific version of ChromeDriver you can use the following code block:\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\n\ns = Service('C:/Users/hp/Downloads/chromedriver/chromedriver.exe')\ndriver = webdriver.Chrome(service=s)\n\nYou can find more discussion here, hope this will help you.\n",
"You actually have to install the Chrome Browser on you machine.\nGo to https://www.google.com/intl/en_en/chrome/, download and install it.\nIt is needed to run Selenium/ Chrome.\n"
] |
[
0,
0,
0
] |
[] |
[] |
[
"google_chrome",
"python",
"selenium",
"webdriver"
] |
stackoverflow_0074340337_google_chrome_python_selenium_webdriver.txt
|
Q:
Random number generator that will always give all numbers within the specified range?
Is there a way to generate random intergers like with random.randint(i, j) but where it will always return all numbers within the range, without repetition and in random order ?
e.g:
(0,6) would give me 5, 3, 4, 2, 0, 1
random.randint(i, j) does not do it.
A:
Maybe
def random_range(begin: int, end: int) -> list[int]:
nums: list[int] = list(range(begin, end + 1))
random.shuffle(nums)
return nums
The + 1 is to account for the last number, you can remove it though if you want to get it IN the range, not THE range
|
Random number generator that will always give all numbers within the specified range?
|
Is there a way to generate random intergers like with random.randint(i, j) but where it will always return all numbers within the range, without repetition and in random order ?
e.g:
(0,6) would give me 5, 3, 4, 2, 0, 1
random.randint(i, j) does not do it.
|
[
"Maybe\ndef random_range(begin: int, end: int) -> list[int]:\n nums: list[int] = list(range(begin, end + 1))\n random.shuffle(nums)\n return nums\n\nThe + 1 is to account for the last number, you can remove it though if you want to get it IN the range, not THE range\n"
] |
[
0
] |
[] |
[] |
[
"python",
"random"
] |
stackoverflow_0074500130_python_random.txt
|
Q:
How to click on hidden select under button
I need to select a URL value, but I don't understand how to do it
<span class="select select_layout_content select_size_s select_theme_normal
queries-filter-item__indicator i-bem select_js_inited _popup-destructor
_popup-destructor_js_inited"
data-bem="{"select":{"live":false}}" title="">
<button class="button button_arrow_down button_theme_normal button_size_s select__button i-bem button_js_inited" type="button" autocomplete="off" role="listbox" aria-haspopup="true" aria-expanded="false" data-bem="{"button":{}}">
<span class="button__text" aria-hidden="true">Total shows</span>
</button>
<select class="select__control" id="uniq16686900391151" tabindex="-1" aria-hidden="true">
<option class="select__option" value="TOTAL_SHOWS_COUNT" selected="selected">Total shows</option>
<option class="select__option" value="TOTAL_CLICKS_COUNT">Clicks count</option>
<option class="select__option" value="AVERAGE_SHOW_POSITION">Average Position</option>
<option class="select__option" value="TOTAL_CTR">CTR, %</option>
<option class="select__option" value="URL">URL</option>
<option class="select__option" value="QUERY">Text</option>
</select>
</span>
My code (the last command) get "Message: element not interactable: Element is not currently visible and may not be manipulated"
# Click on make filter - is works
driver.find_element(By.XPATH, "/html/body/div[3]/div[1]/div[1]/div[2]/div[2]/div/form/span/span").click()
time.sleep(1)
# Click on select button - is works
driver.find_element(By.XPATH, "/html/body/div[3]/div[1]/div[1]/div[2]/div[2]/div/form/div[1]/div/span[1]/button").click()
time.sleep(5)
# Click on URL option
driver.find_element(By.XPATH, "/html/body/div[3]/div[1]/div[1]/div[2]/div[2]/div/form/div[1]/div/span[1]/select/option[5]").click()
A:
I'm not sure if this will work with the element that has the attribute aria-hidden="true".
There is a special class in Selenium for the select elements. First, you need to import the Select class. You can try to use this code:
from selenium.webdriver.support.select import Select
# Click on make filter - is works
driver.find_element(By.XPATH, "/html/body/div[3]/div[1]/div[1]/div[2]/div[2]/div/form/span/span").click()
time.sleep(1)
# Click on select button - is works
driver.find_element(By.XPATH, "/html/body/div[3]/div[1]/div[1]/div[2]/div[2]/div/form/div[1]/div/span[1]/button").click()
time.sleep(5)
# Click on URL option
dropdown = Select(driver.find_element(By.ID, 'uniq16686900391151'))
dropdown.select_by_value('URL')
|
How to click on hidden select under button
|
I need to select a URL value, but I don't understand how to do it
<span class="select select_layout_content select_size_s select_theme_normal
queries-filter-item__indicator i-bem select_js_inited _popup-destructor
_popup-destructor_js_inited"
data-bem="{"select":{"live":false}}" title="">
<button class="button button_arrow_down button_theme_normal button_size_s select__button i-bem button_js_inited" type="button" autocomplete="off" role="listbox" aria-haspopup="true" aria-expanded="false" data-bem="{"button":{}}">
<span class="button__text" aria-hidden="true">Total shows</span>
</button>
<select class="select__control" id="uniq16686900391151" tabindex="-1" aria-hidden="true">
<option class="select__option" value="TOTAL_SHOWS_COUNT" selected="selected">Total shows</option>
<option class="select__option" value="TOTAL_CLICKS_COUNT">Clicks count</option>
<option class="select__option" value="AVERAGE_SHOW_POSITION">Average Position</option>
<option class="select__option" value="TOTAL_CTR">CTR, %</option>
<option class="select__option" value="URL">URL</option>
<option class="select__option" value="QUERY">Text</option>
</select>
</span>
My code (the last command) get "Message: element not interactable: Element is not currently visible and may not be manipulated"
# Click on make filter - is works
driver.find_element(By.XPATH, "/html/body/div[3]/div[1]/div[1]/div[2]/div[2]/div/form/span/span").click()
time.sleep(1)
# Click on select button - is works
driver.find_element(By.XPATH, "/html/body/div[3]/div[1]/div[1]/div[2]/div[2]/div/form/div[1]/div/span[1]/button").click()
time.sleep(5)
# Click on URL option
driver.find_element(By.XPATH, "/html/body/div[3]/div[1]/div[1]/div[2]/div[2]/div/form/div[1]/div/span[1]/select/option[5]").click()
|
[
"I'm not sure if this will work with the element that has the attribute aria-hidden=\"true\".\nThere is a special class in Selenium for the select elements. First, you need to import the Select class. You can try to use this code:\nfrom selenium.webdriver.support.select import Select\n\n# Click on make filter - is works\ndriver.find_element(By.XPATH, \"/html/body/div[3]/div[1]/div[1]/div[2]/div[2]/div/form/span/span\").click()\ntime.sleep(1)\n# Click on select button - is works\ndriver.find_element(By.XPATH, \"/html/body/div[3]/div[1]/div[1]/div[2]/div[2]/div/form/div[1]/div/span[1]/button\").click()\ntime.sleep(5)\n# Click on URL option\ndropdown = Select(driver.find_element(By.ID, 'uniq16686900391151'))\ndropdown.select_by_value('URL')\n\n"
] |
[
0
] |
[] |
[] |
[
"python",
"python_3.x",
"select",
"selenium",
"selenium_webdriver"
] |
stackoverflow_0074499819_python_python_3.x_select_selenium_selenium_webdriver.txt
|
Q:
How to make a square bouncing in random positions using Pywin32
Can anyone tell me how i tried to make one but I didn't know
a square bouncing in random positions using Pywin32
A:
I don't have much of an explanation here but I do have some comments to show you what I am doing.
I haven't tested if this works yet but you can try it.
import win32api, win32con, win32gui, time, random
# get the screen size
width = win32api.GetSystemMetrics(0)
# create a window
win32gui.InitCommonControls()
wc = win32gui.WNDCLASS()
wc.hInstance = win32api.GetModuleHandle(None)
wc.lpszClassName = 'PythonTaskbar'
wc.style = win32con.CS_VREDRAW | win32con.CS_HREDRAW
wc.hbrBackground = win32con.COLOR_WINDOW
wc.lpfnWndProc = {win32con.WM_PAINT: win32gui.DefWindowProc}
classAtom = win32gui.RegisterClass(wc)
hwnd = win32gui.CreateWindow(classAtom, 'PythonTaskbar', win32con.WS_OVERLAPPEDWINDOW, 0, 0, width, 100, 0, 0, wc.hInstance, None)
win32gui.UpdateWindow(hwnd)
# create a square
hdc = win32gui.GetDC(hwnd)
win32gui.SetPixel(hdc, 0, 0, win32api.RGB(255, 0, 0))
win32gui.SetPixel(hdc, 1, 0, win32api.RGB(255, 0, 0))
win32gui.SetPixel(hdc, 0, 1, win32api.RGB(255, 0, 0))
win32gui.SetPixel(hdc, 1, 1, win32api.RGB(255, 0, 0))
# move the square
while True:
x = random.randint(0, width - 2)
y = random.randint(0, 98)
win32gui.SetWindowPos(hwnd, win32con.HWND_TOP, x, y, 0, 0, win32con.SWP_NOSIZE)
time.sleep(0.5)
# close the window
win32gui.DestroyWindow(hwnd)
|
How to make a square bouncing in random positions using Pywin32
|
Can anyone tell me how i tried to make one but I didn't know
a square bouncing in random positions using Pywin32
|
[
"I don't have much of an explanation here but I do have some comments to show you what I am doing.\nI haven't tested if this works yet but you can try it. \nimport win32api, win32con, win32gui, time, random\n\n# get the screen size\nwidth = win32api.GetSystemMetrics(0)\n\n# create a window\n\nwin32gui.InitCommonControls()\nwc = win32gui.WNDCLASS()\nwc.hInstance = win32api.GetModuleHandle(None)\nwc.lpszClassName = 'PythonTaskbar'\nwc.style = win32con.CS_VREDRAW | win32con.CS_HREDRAW\nwc.hbrBackground = win32con.COLOR_WINDOW\nwc.lpfnWndProc = {win32con.WM_PAINT: win32gui.DefWindowProc}\nclassAtom = win32gui.RegisterClass(wc)\n\nhwnd = win32gui.CreateWindow(classAtom, 'PythonTaskbar', win32con.WS_OVERLAPPEDWINDOW, 0, 0, width, 100, 0, 0, wc.hInstance, None)\nwin32gui.UpdateWindow(hwnd)\n\n# create a square\n\nhdc = win32gui.GetDC(hwnd)\nwin32gui.SetPixel(hdc, 0, 0, win32api.RGB(255, 0, 0))\nwin32gui.SetPixel(hdc, 1, 0, win32api.RGB(255, 0, 0))\nwin32gui.SetPixel(hdc, 0, 1, win32api.RGB(255, 0, 0))\nwin32gui.SetPixel(hdc, 1, 1, win32api.RGB(255, 0, 0))\n\n# move the square\n\nwhile True:\n x = random.randint(0, width - 2)\n y = random.randint(0, 98)\n win32gui.SetWindowPos(hwnd, win32con.HWND_TOP, x, y, 0, 0, win32con.SWP_NOSIZE)\n time.sleep(0.5)\n\n# close the window\n\nwin32gui.DestroyWindow(hwnd)\n\n\n"
] |
[
0
] |
[] |
[] |
[
"gdi",
"python"
] |
stackoverflow_0074500001_gdi_python.txt
|
Q:
Selenium crashed on M1 mac: selenium.common.exceptions.WebDriverException
Selenium doen't seems to start properly,
Keep raising **selenium.common.exceptions.WebDriverException: Message: **
Would someone knows how to fix it?
about my setting info
Mac M1 pro
Chrome version: 107.0.5304.87
ChromeDriver: 107.0.5304.62
selenium version: 4.5.0
First I tried the webdriver manual downloaded.
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
s = Service('/Users/itsmeleah/code/itsmeleahh/Get-Taobao-Data/chromedriver')
chrome_options = Options()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument("--disable-dev-shm-usage")
driver = webdriver.Chrome(service=s, options=chrome_options)
driver.get('https://www.google.com')
the log:
Traceback (most recent call last):
File "/Users/itsmeleah/code/itsmeleahh/Get-Taobao-Data/scraping_test.py", line 11, in <module>
driver = webdriver.Chrome(service=s, options=chrome_options)
File "/Users/itsmeleah/opt/anaconda3/lib/python3.9/site-packages/selenium/webdriver/chrome/webdriver.py", line 69, in __init__
super().__init__(DesiredCapabilities.CHROME['browserName'], "goog",
File "/Users/itsmeleah/opt/anaconda3/lib/python3.9/site-packages/selenium/webdriver/chromium/webdriver.py", line 92, in __init__
super().__init__(
File "/Users/itsmeleah/opt/anaconda3/lib/python3.9/site-packages/selenium/webdriver/remote/webdriver.py", line 272, in __init__
self.start_session(capabilities, browser_profile)
File "/Users/itsmeleah/opt/anaconda3/lib/python3.9/site-packages/selenium/webdriver/remote/webdriver.py", line 364, in start_session
response = self.execute(Command.NEW_SESSION, parameters)
File "/Users/itsmeleah/opt/anaconda3/lib/python3.9/site-packages/selenium/webdriver/remote/webdriver.py", line 429, in execute
self.error_handler.check_response(response)
File "/Users/itsmeleah/opt/anaconda3/lib/python3.9/site-packages/selenium/webdriver/remote/errorhandler.py", line 207, in check_response
raise exception_class(value)
selenium.common.exceptions.WebDriverException: Message:
Sencondly, I used the chromedrive manager, still got the same error
from webdriver_manager.chrome import ChromeDriverManager
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
driver.maximize_window()
driver.get("https://www.google.com")
[WDM] - Downloading: 100%|██████████████████████████████████████████████████████| 8.41M/8.41M [00:25<00:00, 348kB/s]
Traceback (most recent call last):
File "/Users/itsmeleah/code/itsmeleahh/Get-Taobao-Data/scraping_test.py", line 19, in <module>
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
File "/Users/itsmeleah/opt/anaconda3/lib/python3.9/site-packages/selenium/webdriver/chrome/webdriver.py", line 69, in __init__
super().__init__(DesiredCapabilities.CHROME['browserName'], "goog",
File "/Users/itsmeleah/opt/anaconda3/lib/python3.9/site-packages/selenium/webdriver/chromium/webdriver.py", line 92, in __init__
super().__init__(
File "/Users/itsmeleah/opt/anaconda3/lib/python3.9/site-packages/selenium/webdriver/remote/webdriver.py", line 272, in __init__
self.start_session(capabilities, browser_profile)
File "/Users/itsmeleah/opt/anaconda3/lib/python3.9/site-packages/selenium/webdriver/remote/webdriver.py", line 364, in start_session
response = self.execute(Command.NEW_SESSION, parameters)
File "/Users/itsmeleah/opt/anaconda3/lib/python3.9/site-packages/selenium/webdriver/remote/webdriver.py", line 429, in execute
self.error_handler.check_response(response)
File "/Users/itsmeleah/opt/anaconda3/lib/python3.9/site-packages/selenium/webdriver/remote/errorhandler.py", line 207, in check_response
raise exception_class(value)
selenium.common.exceptions.WebDriverException: Message:
There's no window popping out after executing the code, and I also tried to close my existing chrome windows to avoid the conflicts, but still not working.
A:
Make sure you have the chrome browser installed.
brew install google-chrome
Make sure to run the newest versions of selenium and webdriver_manager.
python3 -m pip install --upgrade selenium webdriver_manager
Delete all existing downloads with rm -rf ~/.wdm and try again. Make sure to not run your script as root.
|
Selenium crashed on M1 mac: selenium.common.exceptions.WebDriverException
|
Selenium doen't seems to start properly,
Keep raising **selenium.common.exceptions.WebDriverException: Message: **
Would someone knows how to fix it?
about my setting info
Mac M1 pro
Chrome version: 107.0.5304.87
ChromeDriver: 107.0.5304.62
selenium version: 4.5.0
First I tried the webdriver manual downloaded.
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
s = Service('/Users/itsmeleah/code/itsmeleahh/Get-Taobao-Data/chromedriver')
chrome_options = Options()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument("--disable-dev-shm-usage")
driver = webdriver.Chrome(service=s, options=chrome_options)
driver.get('https://www.google.com')
the log:
Traceback (most recent call last):
File "/Users/itsmeleah/code/itsmeleahh/Get-Taobao-Data/scraping_test.py", line 11, in <module>
driver = webdriver.Chrome(service=s, options=chrome_options)
File "/Users/itsmeleah/opt/anaconda3/lib/python3.9/site-packages/selenium/webdriver/chrome/webdriver.py", line 69, in __init__
super().__init__(DesiredCapabilities.CHROME['browserName'], "goog",
File "/Users/itsmeleah/opt/anaconda3/lib/python3.9/site-packages/selenium/webdriver/chromium/webdriver.py", line 92, in __init__
super().__init__(
File "/Users/itsmeleah/opt/anaconda3/lib/python3.9/site-packages/selenium/webdriver/remote/webdriver.py", line 272, in __init__
self.start_session(capabilities, browser_profile)
File "/Users/itsmeleah/opt/anaconda3/lib/python3.9/site-packages/selenium/webdriver/remote/webdriver.py", line 364, in start_session
response = self.execute(Command.NEW_SESSION, parameters)
File "/Users/itsmeleah/opt/anaconda3/lib/python3.9/site-packages/selenium/webdriver/remote/webdriver.py", line 429, in execute
self.error_handler.check_response(response)
File "/Users/itsmeleah/opt/anaconda3/lib/python3.9/site-packages/selenium/webdriver/remote/errorhandler.py", line 207, in check_response
raise exception_class(value)
selenium.common.exceptions.WebDriverException: Message:
Sencondly, I used the chromedrive manager, still got the same error
from webdriver_manager.chrome import ChromeDriverManager
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
driver.maximize_window()
driver.get("https://www.google.com")
[WDM] - Downloading: 100%|██████████████████████████████████████████████████████| 8.41M/8.41M [00:25<00:00, 348kB/s]
Traceback (most recent call last):
File "/Users/itsmeleah/code/itsmeleahh/Get-Taobao-Data/scraping_test.py", line 19, in <module>
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
File "/Users/itsmeleah/opt/anaconda3/lib/python3.9/site-packages/selenium/webdriver/chrome/webdriver.py", line 69, in __init__
super().__init__(DesiredCapabilities.CHROME['browserName'], "goog",
File "/Users/itsmeleah/opt/anaconda3/lib/python3.9/site-packages/selenium/webdriver/chromium/webdriver.py", line 92, in __init__
super().__init__(
File "/Users/itsmeleah/opt/anaconda3/lib/python3.9/site-packages/selenium/webdriver/remote/webdriver.py", line 272, in __init__
self.start_session(capabilities, browser_profile)
File "/Users/itsmeleah/opt/anaconda3/lib/python3.9/site-packages/selenium/webdriver/remote/webdriver.py", line 364, in start_session
response = self.execute(Command.NEW_SESSION, parameters)
File "/Users/itsmeleah/opt/anaconda3/lib/python3.9/site-packages/selenium/webdriver/remote/webdriver.py", line 429, in execute
self.error_handler.check_response(response)
File "/Users/itsmeleah/opt/anaconda3/lib/python3.9/site-packages/selenium/webdriver/remote/errorhandler.py", line 207, in check_response
raise exception_class(value)
selenium.common.exceptions.WebDriverException: Message:
There's no window popping out after executing the code, and I also tried to close my existing chrome windows to avoid the conflicts, but still not working.
|
[
"Make sure you have the chrome browser installed.\nbrew install google-chrome\nMake sure to run the newest versions of selenium and webdriver_manager.\npython3 -m pip install --upgrade selenium webdriver_manager \nDelete all existing downloads with rm -rf ~/.wdm and try again. Make sure to not run your script as root.\n"
] |
[
0
] |
[] |
[] |
[
"python",
"selenium",
"selenium_webdriver",
"web_scraping"
] |
stackoverflow_0074298630_python_selenium_selenium_webdriver_web_scraping.txt
|
Q:
Check Dataframes with Python
I got multiple excel file which needs to be need if OLD data is matching NEW data. Normally I use dataframe.equals but since the NEW data is containing additional columns this doesn't work anymore.
Very excel file contains two tabs with OLD and NEW data. I have to check if the OLD data is matching per record in NEW. The issue of NEW is that columns aren't in the same order, additional columns plus record aren't in the same order.
Table OLD and Table NEW
The code I normally use to check but it is giving
import os
import pandas as pd
TargetFolder = os.listdir('Dir')
for file in TargetFolder:
df = pd.ExcelFile('TargetFolder' + file)
dfPrep = pd.read_excel(df, 'OLD')
dfCE = pd.read_excel(df, 'NEW')
Checkdf = dfPrep.equals(dfCE)
A:
IIUC, you can use pandas.DataFrame.loc to select/pick the exact OLD columns from the NEW ones then use pandas.DataFrame.sort_values to reorder the rows by the two columns Column4 and Column8.
Try this :
from pathlib import Path
import pandas as pd
a_directory= "path_to_the_folder_containing_the_excel_files"
for file in Path(a_directory).glob("*.xlsx"):
dfPrep = pd.read_excel(file, sheet_name="OLD")
dfCE = pd.read_excel(file, sheet_name="NEW")
dfCE_adapted= (
dfCE.loc[:, dfPrep.columns]
.sort_values(by=["Column4", "Column8"], ignore_index=True)
)
Checkdf= dfPrep.equals(dfCE_adapted)
if Checkdf:
print(file.stem)
else:
pass
If the two sheets OLD and NEW matches, then the Excel filename will be printed.
|
Check Dataframes with Python
|
I got multiple excel file which needs to be need if OLD data is matching NEW data. Normally I use dataframe.equals but since the NEW data is containing additional columns this doesn't work anymore.
Very excel file contains two tabs with OLD and NEW data. I have to check if the OLD data is matching per record in NEW. The issue of NEW is that columns aren't in the same order, additional columns plus record aren't in the same order.
Table OLD and Table NEW
The code I normally use to check but it is giving
import os
import pandas as pd
TargetFolder = os.listdir('Dir')
for file in TargetFolder:
df = pd.ExcelFile('TargetFolder' + file)
dfPrep = pd.read_excel(df, 'OLD')
dfCE = pd.read_excel(df, 'NEW')
Checkdf = dfPrep.equals(dfCE)
|
[
"IIUC, you can use pandas.DataFrame.loc to select/pick the exact OLD columns from the NEW ones then use pandas.DataFrame.sort_values to reorder the rows by the two columns Column4 and Column8.\nTry this :\nfrom pathlib import Path\nimport pandas as pd\n\na_directory= \"path_to_the_folder_containing_the_excel_files\"\n\nfor file in Path(a_directory).glob(\"*.xlsx\"):\n dfPrep = pd.read_excel(file, sheet_name=\"OLD\")\n dfCE = pd.read_excel(file, sheet_name=\"NEW\")\n\n dfCE_adapted= (\n dfCE.loc[:, dfPrep.columns]\n .sort_values(by=[\"Column4\", \"Column8\"], ignore_index=True)\n )\n\n Checkdf= dfPrep.equals(dfCE_adapted)\n \n if Checkdf:\n print(file.stem)\n else:\n pass\n\nIf the two sheets OLD and NEW matches, then the Excel filename will be printed.\n"
] |
[
0
] |
[] |
[] |
[
"pandas",
"python"
] |
stackoverflow_0074499645_pandas_python.txt
|
Q:
How can I create the fibonacci series using a list comprehension?
I am new to python, and I was wondering if I could generate the fibonacci series using python's list comprehension feature. I don't know how list comprehensions are implemented.
I tried the following (the intention was to generate the first five fibonacci numbers):
series=[]
series.append(1)
series.append(1)
series += [series[k-1]+series[k-2] for k in range(2,5)]
This piece of code throws the error: IndexError: list index out of range.
Let me know if it is even possible to generate such a series using a list comprehension.
A:
You cannot do it like that: the list comprehension is evaluated first, and then that list is added to series. So basically it would be like you would have written:
series=[]
series.append(1)
series.append(1)
temp = [series[k-1]+series[k-2] for k in range(2,5)]
series += temp
You can however solve this by using list comprehension as a way to force side effects, like for instance:
series=[]
series.append(1)
series.append(1)
[series.append(series[k-1]+series[k-2]) for k in range(2,5)]
Note that we here do not add the result to series. The list comprehension is only used such that .append is called on series. However some consider list comprehensions with side effects rather error prone: it is not very declarative and tends to introduce bugs if not done carefully.
A:
We could write it as a clean Python list comprehension (or generator) using it's relationship to the golden ratio:
>>> series = [int((((1 + 5**0.5) / 2)**n - ((1 - 5**0.5) / 2)**n) / 5**0.5) for n in range(1, 21)]
>>> series
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765]
>>>
or a little more nicely as:
>>> square_root_of_five = 5**0.5
>>> Phi = (1 + square_root_of_five) / 2
>>> phi = (1 - square_root_of_five) / 2
>>>
>>> series = [int((Phi**n - phi**n) / square_root_of_five) for n in range(1, 21)]
>>> series
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765]
A:
If you know how many terms of the series you will need then you can write the code compactly without a list comprehension like this.
def Fibonacci(n):
f0, f1 = 1, 1
for _ in range(n):
yield f0
f0, f1 = f1, f0+f1
fibs = list(Fibonacci(10))
print (fibs)
If you want some indefinite number of terms then you could use this, which is very similar.
def Fibonacci():
f0, f1 = 1, 1
while True:
yield f0
f0, f1 = f1, f0+f1
fibs = []
for f in Fibonacci():
fibs.append(f)
if f>100:
break
print (fibs)
When you need a potentially infinite collection of items you should perhaps consider either a function with one or more yield statements or a generator expression. I'd love to be able to make Fibonacci numbers with a generator expression but apparently one can't.
A:
Using Assignment Expression (python >= 3.8):
s = [0, 1]
s += [(s := [s[1], s[0] + s[1]]) and s[1] for k in range(10)]
print (s)
# [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
A:
To build on what Willem van Onsem said:
The conventional way to calculate the nth term of the fibonacci sequence is to sum the n-1 and n-2 terms, as you're aware. A list comprehension is designed to create a list with no side effects during the comprehension (apart from the creation of the single list). Storing the last 2 terms of the sequence during calculation of the sequence is a side-effect, therefore a list comprehension is ill-suited to the task on its own.
A safe way around this would be to make a closure generator (essentially a generator with some associated private state) that can be passed to the list comprehension such that the list comprehension does not have to worry about the details of what's being stored:
def fib_generator(n):
def fib_n_generator():
last = 1
curr = 1
if n == 0:
return
yield last
if n == 1:
return
yield curr
if n == 2:
return
ii = 2
while ii < n:
next = curr + last
yield next
last = curr
curr = next
ii += 1
return fib_n_generator()
fib = [xx for xx in fib_generator(10)]
print(fib)
A:
Here's a one-line list comprehension solution that avoids the separate initialization step with nested ternary operators and the walrus operator (so needs Python 3.8), and also avoids the rapid onset of overflow problems that the explicit form can give you (with its **n component):
[
0 if not i else
(x := [0, 1]) and 1 if i == 1 else
not x.append(x[-2] + x[-1]) and x[-1]
for i in range(10)
]
Gives:
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
This is faster than the explicit form for generating all of the values up to N. If, however, you don't want all of the values then the explicit form could be much faster, but it does suffer from overflow for some N between 1000 and 2000:
n = 2000
int((((1 + 5**0.5) / 2)**n - ((1 - 5**0.5) / 2)**n) / 5**0.5)
gives for me:
OverflowError: (34, 'Numerical result out of range')
whereas the "adding the last two values" approach can generate higher values for larger N. On my machine, I can keep going until some N between 300000 and 400000 before I run out of memory.
Thanks to Jonathan Gregory for leading me most of the way to this approach.
A:
List comprehension of the fibonacci serie, based on the explicit formula 1:
[int((0.5+5**0.5/2)**n/5**0.5+0.5) for n in range(21)]
A:
From Python One-Liners by Christian Mayer.
n = 10
x = [0,1]
fibs = x[0:2] + [x.append(x[-1] + x[-2]) or x[-1] for i in range(n-2)]
print(fibs)
# [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
The answer is you can do this with a list comprehension without the assignment operator (works even in Python 2).
A:
I did it this way:
def Phi(number:int):
n = [1,1]
[n.append(n[i-2]+n[i-1])for i in range(2,number)]
return n
A:
Simplification of @dhassel version (requires python 3.8 or later)
series = [i0 := 0, i1 := 1]+[i1 := i0 + (i0 := i1) for j in range(2, 5)]
One can also be written as a generator expression, but it's a bit tricky because for some reason, the obvious answer: fibo = (v for g in ((i0 := 0, i1 := 1), (i1 := i0 + (i0 := i1) for j in range(2,10))) for v in g) doesn't work (I do not exclude a bug). However, it is OK if you get the subgenerators list outside :
glist = ((i0 := 0, i1 := 1), (i1 := i0 + (i0 := i1) for j in range(2, 5)))
fibo = (v for g in glist for v in g)
A:
# Get a number from the user.
number = int(input("enter a number"))
# Create a empty list
mylist=[]
# create list comprehension following fibonaci series
[mylist.append(0) if n==0 else mylist.append(1) if n==1 else mylist.append(mylist[-2]+mylist[-1]) for n in range(number+1)]
print(mylist)
|
How can I create the fibonacci series using a list comprehension?
|
I am new to python, and I was wondering if I could generate the fibonacci series using python's list comprehension feature. I don't know how list comprehensions are implemented.
I tried the following (the intention was to generate the first five fibonacci numbers):
series=[]
series.append(1)
series.append(1)
series += [series[k-1]+series[k-2] for k in range(2,5)]
This piece of code throws the error: IndexError: list index out of range.
Let me know if it is even possible to generate such a series using a list comprehension.
|
[
"You cannot do it like that: the list comprehension is evaluated first, and then that list is added to series. So basically it would be like you would have written:\nseries=[]\nseries.append(1)\nseries.append(1)\ntemp = [series[k-1]+series[k-2] for k in range(2,5)]\nseries += temp\nYou can however solve this by using list comprehension as a way to force side effects, like for instance:\nseries=[]\nseries.append(1)\nseries.append(1)\n[series.append(series[k-1]+series[k-2]) for k in range(2,5)]\nNote that we here do not add the result to series. The list comprehension is only used such that .append is called on series. However some consider list comprehensions with side effects rather error prone: it is not very declarative and tends to introduce bugs if not done carefully.\n",
"We could write it as a clean Python list comprehension (or generator) using it's relationship to the golden ratio:\n>>> series = [int((((1 + 5**0.5) / 2)**n - ((1 - 5**0.5) / 2)**n) / 5**0.5) for n in range(1, 21)]\n>>> series\n[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765]\n>>> \n\nor a little more nicely as:\n>>> square_root_of_five = 5**0.5\n>>> Phi = (1 + square_root_of_five) / 2\n>>> phi = (1 - square_root_of_five) / 2\n>>> \n>>> series = [int((Phi**n - phi**n) / square_root_of_five) for n in range(1, 21)]\n>>> series\n[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765]\n\n",
"If you know how many terms of the series you will need then you can write the code compactly without a list comprehension like this.\ndef Fibonacci(n):\n f0, f1 = 1, 1\n for _ in range(n):\n yield f0\n f0, f1 = f1, f0+f1\n\nfibs = list(Fibonacci(10))\nprint (fibs)\n\nIf you want some indefinite number of terms then you could use this, which is very similar.\ndef Fibonacci():\n f0, f1 = 1, 1\n while True:\n yield f0\n f0, f1 = f1, f0+f1\n\nfibs = []\nfor f in Fibonacci():\n fibs.append(f)\n if f>100:\n break\nprint (fibs)\n\nWhen you need a potentially infinite collection of items you should perhaps consider either a function with one or more yield statements or a generator expression. I'd love to be able to make Fibonacci numbers with a generator expression but apparently one can't.\n",
"Using Assignment Expression (python >= 3.8):\ns = [0, 1]\ns += [(s := [s[1], s[0] + s[1]]) and s[1] for k in range(10)]\n\nprint (s)\n# [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]\n\n",
"To build on what Willem van Onsem said:\nThe conventional way to calculate the nth term of the fibonacci sequence is to sum the n-1 and n-2 terms, as you're aware. A list comprehension is designed to create a list with no side effects during the comprehension (apart from the creation of the single list). Storing the last 2 terms of the sequence during calculation of the sequence is a side-effect, therefore a list comprehension is ill-suited to the task on its own.\nA safe way around this would be to make a closure generator (essentially a generator with some associated private state) that can be passed to the list comprehension such that the list comprehension does not have to worry about the details of what's being stored:\ndef fib_generator(n):\n\n def fib_n_generator():\n last = 1\n curr = 1\n\n if n == 0:\n return\n\n yield last\n if n == 1:\n return\n\n yield curr\n if n == 2:\n return\n\n ii = 2\n while ii < n:\n next = curr + last\n yield next\n last = curr\n curr = next\n ii += 1\n\n return fib_n_generator()\n\nfib = [xx for xx in fib_generator(10)]\nprint(fib)\n\n",
"Here's a one-line list comprehension solution that avoids the separate initialization step with nested ternary operators and the walrus operator (so needs Python 3.8), and also avoids the rapid onset of overflow problems that the explicit form can give you (with its **n component):\n[\n 0 if not i else\n (x := [0, 1]) and 1 if i == 1 else\n not x.append(x[-2] + x[-1]) and x[-1]\n for i in range(10)\n]\n\nGives:\n[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]\n\nThis is faster than the explicit form for generating all of the values up to N. If, however, you don't want all of the values then the explicit form could be much faster, but it does suffer from overflow for some N between 1000 and 2000:\nn = 2000\nint((((1 + 5**0.5) / 2)**n - ((1 - 5**0.5) / 2)**n) / 5**0.5)\n\ngives for me:\nOverflowError: (34, 'Numerical result out of range')\n\nwhereas the \"adding the last two values\" approach can generate higher values for larger N. On my machine, I can keep going until some N between 300000 and 400000 before I run out of memory.\nThanks to Jonathan Gregory for leading me most of the way to this approach.\n",
"List comprehension of the fibonacci serie, based on the explicit formula 1:\n[int((0.5+5**0.5/2)**n/5**0.5+0.5) for n in range(21)]\n\n",
"From Python One-Liners by Christian Mayer.\nn = 10\nx = [0,1]\nfibs = x[0:2] + [x.append(x[-1] + x[-2]) or x[-1] for i in range(n-2)]\nprint(fibs)\n# [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]\n\nThe answer is you can do this with a list comprehension without the assignment operator (works even in Python 2).\n",
"I did it this way:\ndef Phi(number:int):\nn = [1,1]\n[n.append(n[i-2]+n[i-1])for i in range(2,number)]\nreturn n\n\n",
"Simplification of @dhassel version (requires python 3.8 or later)\nseries = [i0 := 0, i1 := 1]+[i1 := i0 + (i0 := i1) for j in range(2, 5)]\n\nOne can also be written as a generator expression, but it's a bit tricky because for some reason, the obvious answer: fibo = (v for g in ((i0 := 0, i1 := 1), (i1 := i0 + (i0 := i1) for j in range(2,10))) for v in g) doesn't work (I do not exclude a bug). However, it is OK if you get the subgenerators list outside :\nglist = ((i0 := 0, i1 := 1), (i1 := i0 + (i0 := i1) for j in range(2, 5)))\nfibo = (v for g in glist for v in g)\n\n",
"# Get a number from the user.\nnumber = int(input(\"enter a number\"))\n\n# Create a empty list\nmylist=[] \n\n# create list comprehension following fibonaci series\n[mylist.append(0) if n==0 else mylist.append(1) if n==1 else mylist.append(mylist[-2]+mylist[-1]) for n in range(number+1)]\n\nprint(mylist) \n\n"
] |
[
13,
10,
8,
8,
5,
1,
0,
0,
0,
0,
0
] |
[
"Using List comprehension : \nn = int(input())\nfibonacci_list = [0,1]\n[fibonacci_list.append(fibonacci_list[k-1]+fibonacci_list[k-2]) for k in range(2,n)]\n\nif n<=0:\n print('+ve numbers only')\nelif n == 1:\n fibonacci_list = [fibonacci_list[0]]\n print(fibonacci_list)\nelse:\n print(fibonacci_list)\n\nmaybe it's a feasible solution for this problem...\n"
] |
[
-1
] |
[
"fibonacci",
"list_comprehension",
"python"
] |
stackoverflow_0042370456_fibonacci_list_comprehension_python.txt
|
Q:
Extracting data from folders and putting it in excel using python
I dont know where to start and how to extract data from folder using pycharm
I am realy new to all of this can someone maybe direct me to what im looking for. I need to extract folder size data in Gb or kb and also name and write it as a defferent excel cell how do i do this?
thanks for any help.
|
Extracting data from folders and putting it in excel using python
|
I dont know where to start and how to extract data from folder using pycharm
I am realy new to all of this can someone maybe direct me to what im looking for. I need to extract folder size data in Gb or kb and also name and write it as a defferent excel cell how do i do this?
thanks for any help.
|
[] |
[] |
[
"Take a look to the os module and pandas library. For example:\nwith os.path.dirname() you get the folder name, and then with pandas you can create a new spreadsheet with that output.\n"
] |
[
-1
] |
[
"file",
"python"
] |
stackoverflow_0074500223_file_python.txt
|
Q:
Implement guild command testing in cog slash commands
I am trying to learn discord.py V2.0. If I create a slash command without entering a guild to use then I takes some time before discord updated the bot slash command list. The qustion is how should I provide the guilds in my cog python file?
Here is my main.py:
import os
import asyncio
#---
import discord
from discord import app_commands
from discord.ext import commands
#---
MY_GUILD = discord.Object(id=1041079018713260173)
TOKEN = "token goes here"
intents = discord.Intents.default()
bot = commands.Bot(command_prefix="!", intents=intents)
class abot(discord.Client):
def __init__(self, *, intents: discord.Intents):
super().__init__(intents=intents)
self.bot = bot
self.synced = False
self.tree = app_commands.CommandTree(self.bot)
async def on_ready(self):
await self.tree.sync(guild=MY_GUILD)
self.synced = True
async def load():
print("---Cogs---")
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
await bot.load_extension(f"cogs.{filename[:-3]}")
print(f'[i]: Loaded "{filename}" into cogs')
async def main():
await load()
await bot.start(TOKEN)
asyncio.run(main())
Here is the event.py file inside of "cogs" folder:
import asyncio
import os
#---
import discord
from discord import app_commands
from discord.ext import commands
status = "testar bara..."
MY_GUILD = discord.Object(id=1041079018713260173)
class events(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_ready(self):
print("---Info---")
print(f'Logged in as | "{self.bot.user}" | and is now online!')
await self.bot.change_presence(status=discord.Status.online, activity=discord.Game(status))
print(f'Updated status to -> "{status}"')
print("Running and listening for commands....")
print(f"----")
@app_commands.command(name = "latency", description="brrarar testar")
async def latencyf(self, interaction: discord.Interaction):
await interaction.response.send_message(f"test... test...")
async def setup(bot):
await bot.add_cog(events(bot))
A:
You do not need to provide the guilds yourself. You can use bot.guilds, which provides a list of all the guilds where the bot is connected to.
|
Implement guild command testing in cog slash commands
|
I am trying to learn discord.py V2.0. If I create a slash command without entering a guild to use then I takes some time before discord updated the bot slash command list. The qustion is how should I provide the guilds in my cog python file?
Here is my main.py:
import os
import asyncio
#---
import discord
from discord import app_commands
from discord.ext import commands
#---
MY_GUILD = discord.Object(id=1041079018713260173)
TOKEN = "token goes here"
intents = discord.Intents.default()
bot = commands.Bot(command_prefix="!", intents=intents)
class abot(discord.Client):
def __init__(self, *, intents: discord.Intents):
super().__init__(intents=intents)
self.bot = bot
self.synced = False
self.tree = app_commands.CommandTree(self.bot)
async def on_ready(self):
await self.tree.sync(guild=MY_GUILD)
self.synced = True
async def load():
print("---Cogs---")
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
await bot.load_extension(f"cogs.{filename[:-3]}")
print(f'[i]: Loaded "{filename}" into cogs')
async def main():
await load()
await bot.start(TOKEN)
asyncio.run(main())
Here is the event.py file inside of "cogs" folder:
import asyncio
import os
#---
import discord
from discord import app_commands
from discord.ext import commands
status = "testar bara..."
MY_GUILD = discord.Object(id=1041079018713260173)
class events(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_ready(self):
print("---Info---")
print(f'Logged in as | "{self.bot.user}" | and is now online!')
await self.bot.change_presence(status=discord.Status.online, activity=discord.Game(status))
print(f'Updated status to -> "{status}"')
print("Running and listening for commands....")
print(f"----")
@app_commands.command(name = "latency", description="brrarar testar")
async def latencyf(self, interaction: discord.Interaction):
await interaction.response.send_message(f"test... test...")
async def setup(bot):
await bot.add_cog(events(bot))
|
[
"You do not need to provide the guilds yourself. You can use bot.guilds, which provides a list of all the guilds where the bot is connected to.\n"
] |
[
1
] |
[] |
[] |
[
"discord",
"discord.py",
"python"
] |
stackoverflow_0074499980_discord_discord.py_python.txt
|
Q:
How to store every key that's generated in a variable?
How do I store every key that's generated here in a variable that I can access later?
for _ in range(int(amount)):
key = str(uuid.uuid4())
amount Is subject to change.
How do I make it so I can print all of the keys that it generated after the loop is done?
I tried doing:
for _ in range(int(amount)):
key = str(uuid.uuid4())
keys=''.join(f'{key}\n')
but it didn't work, only 1 key was stored into the variable.
A:
You can also store them in a list
keys = []
for _ in range(int(amount)):
keys.append(str(uuid.uuid4()))
You can read about python lists here and here.
You can then loop over your keys:
for key in keys:
print(key)
|
How to store every key that's generated in a variable?
|
How do I store every key that's generated here in a variable that I can access later?
for _ in range(int(amount)):
key = str(uuid.uuid4())
amount Is subject to change.
How do I make it so I can print all of the keys that it generated after the loop is done?
I tried doing:
for _ in range(int(amount)):
key = str(uuid.uuid4())
keys=''.join(f'{key}\n')
but it didn't work, only 1 key was stored into the variable.
|
[
"You can also store them in a list\nkeys = []\nfor _ in range(int(amount)):\n keys.append(str(uuid.uuid4()))\n\nYou can read about python lists here and here.\nYou can then loop over your keys:\nfor key in keys:\n print(key)\n\n"
] |
[
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0074500273_python.txt
|
Q:
Finding the index of an element in nested lists in python
I am trying to get the index of an element in nested lists in python - for example [[a, b, c], [d, e, f], [g,h]] (not all lists are the same size).
I have tried using
strand_value= [x[0] for x in np.where(min_value_of_non_empty_strands=="a")]
but this is only returning an empty list, even though the element is present. Any idea what I'm doing wrong?
A:
def find_in_list_of_list(mylist, char):
for sub_list in mylist:
if char in sub_list:
return (mylist.index(sub_list), sub_list.index(char))
raise ValueError("'{char}' is not in list".format(char = char))
example_list = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h']]
find_in_list_of_list(example_list, 'b')
(0, 1)
A:
suppose your list is like this:
lst = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g','h']]
list_no = 0
pos = 0
for x in range(0,len(lst)):
try:
pos = lst[x].index('e')
break
except:
pass
list_no = x
list_no gives the list number and pos gives the position in that list
A:
You could do this using List comprehension and enumerate
Code:
lst=[["a", "b", "c"], ["d", "e", "f"], ["g","h"]]
check="a"
print ["{} {}".format(index1,index2) for index1,value1 in enumerate(lst) for index2,value2 in enumerate(value1) if value2==check]
Output:
['0 0']
Steps:
I have enumerated through the List of List and got it's index and list
Then I have enumerated over the gotten list and checked if it matches the check variable and written it to list if so
This gives all possible output
i.e.)
Code2:
lst=[["a", "b", "c","a"], ["d", "e", "f"], ["g","h"]]
check="a"
print ["{} {}".format(index1,index2) for index1,value1 in enumerate(lst) for index2,value2 in enumerate(value1) if value2==check]
Gives:
['0 0', '0 3']
Notes:
You can easily turn this into list of list instead of string if you want
A:
does this suffice?
array = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h']]
for subarray in array:
if 'a' in subarray:
print(array.index(subarray), '-', subarray.index('a'))
This will return 0 - 0. First zero is the index of the subarray inside array, and the last zero is the 'a' index inside subarray.
A:
Reworked Bhrigu Srivastava's proposal:
def findinlst(lst, val):
for x in range(0, len(lst)):
try:
pos = lst[x].index(val)
return [x, pos]
except:
continue
return [False, False] # whatever one wants to get if value not found
arr = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h']]
findinlst(arr, 'b')
[0, 1]
findInLst(arr, 'g')
[2, 0]
findinlst(arr, 'w')
[False, False]
A:
You can implement your own findIndex function, this looks like Javascipt's Array.prototype.findIndex
def findIndex(callback, list):
for index, element in enumerate(list):
if callback(element):
return index
return -1
A:
A little bit of "amateur" approach and yet very easy to understand:
Creating a flag boolean value that will execute the result based on if it is True or False with a nested for loop.
entry=input()
listtt=[["a","b","c"],["d","e","f"],["g","h"]]
found=False
for sublist in listtt:
for charr in sublist:
if entry==charr:
print(f"'{entry}' found in sublist {listtt.index(sublist)} with index {sublist.index(charr)}")
found=True
break
if found==False:
print(f"'{entry}' not found")
|
Finding the index of an element in nested lists in python
|
I am trying to get the index of an element in nested lists in python - for example [[a, b, c], [d, e, f], [g,h]] (not all lists are the same size).
I have tried using
strand_value= [x[0] for x in np.where(min_value_of_non_empty_strands=="a")]
but this is only returning an empty list, even though the element is present. Any idea what I'm doing wrong?
|
[
"def find_in_list_of_list(mylist, char):\n for sub_list in mylist:\n if char in sub_list:\n return (mylist.index(sub_list), sub_list.index(char))\n raise ValueError(\"'{char}' is not in list\".format(char = char))\n\nexample_list = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h']]\n\nfind_in_list_of_list(example_list, 'b')\n(0, 1)\n\n",
"suppose your list is like this:\nlst = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g','h']]\nlist_no = 0\npos = 0\nfor x in range(0,len(lst)):\n try:\n pos = lst[x].index('e')\n break\n except:\n pass\n\nlist_no = x\n\nlist_no gives the list number and pos gives the position in that list\n",
"You could do this using List comprehension and enumerate\nCode:\nlst=[[\"a\", \"b\", \"c\"], [\"d\", \"e\", \"f\"], [\"g\",\"h\"]]\ncheck=\"a\"\nprint [\"{} {}\".format(index1,index2) for index1,value1 in enumerate(lst) for index2,value2 in enumerate(value1) if value2==check]\n\nOutput:\n['0 0']\n\nSteps:\n\nI have enumerated through the List of List and got it's index and list\nThen I have enumerated over the gotten list and checked if it matches the check variable and written it to list if so \n\nThis gives all possible output \ni.e.)\nCode2:\nlst=[[\"a\", \"b\", \"c\",\"a\"], [\"d\", \"e\", \"f\"], [\"g\",\"h\"]]\ncheck=\"a\"\nprint [\"{} {}\".format(index1,index2) for index1,value1 in enumerate(lst) for index2,value2 in enumerate(value1) if value2==check]\n\nGives:\n['0 0', '0 3']\n\nNotes:\n\nYou can easily turn this into list of list instead of string if you want \n\n",
"does this suffice?\narray = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h']]\nfor subarray in array:\n if 'a' in subarray:\n print(array.index(subarray), '-', subarray.index('a'))\n\nThis will return 0 - 0. First zero is the index of the subarray inside array, and the last zero is the 'a' index inside subarray.\n",
"Reworked Bhrigu Srivastava's proposal:\ndef findinlst(lst, val):\n for x in range(0, len(lst)):\n try:\n pos = lst[x].index(val)\n return [x, pos]\n except:\n continue\n return [False, False] # whatever one wants to get if value not found\n\narr = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h']]\n\nfindinlst(arr, 'b')\n[0, 1]\n\nfindInLst(arr, 'g')\n[2, 0]\n\nfindinlst(arr, 'w')\n[False, False]\n\n",
"You can implement your own findIndex function, this looks like Javascipt's Array.prototype.findIndex\ndef findIndex(callback, list):\n for index, element in enumerate(list):\n if callback(element):\n return index\n return -1\n\n",
"A little bit of \"amateur\" approach and yet very easy to understand:\nCreating a flag boolean value that will execute the result based on if it is True or False with a nested for loop.\nentry=input()\nlisttt=[[\"a\",\"b\",\"c\"],[\"d\",\"e\",\"f\"],[\"g\",\"h\"]]\nfound=False\nfor sublist in listtt:\n for charr in sublist:\n if entry==charr:\n print(f\"'{entry}' found in sublist {listtt.index(sublist)} with index {sublist.index(charr)}\")\n found=True\n break\nif found==False:\n print(f\"'{entry}' not found\")\n\n"
] |
[
8,
2,
2,
0,
0,
0,
0
] |
[] |
[] |
[
"nested_lists",
"python"
] |
stackoverflow_0033938488_nested_lists_python.txt
|
Q:
How to prevent class contructor from blocking other threads?
I am new to threading, so this question might be too basic.
I have two classes A and B. If I put their respective instances and methods in two threads as below:
from threading import Thread
from time import sleep
class A:
def __init__(self):
sleep(10)
print('class A __init__ awake')
def method_a(self):
sleep(10)
print('method_a awake')
class B:
def __init__(self):
sleep(1)
print('class B __init__ awake')
def method_b(self):
sleep(5)
print('method_b awake')
thread_a = Thread(target=A().method_a)
thread_b = Thread(target=B().method_b)
thread_a.start()
thread_b.start()
my expected result would be:
class B __init__ awake
method_b awake
class A __init__ awake
method_a awake
but I am getting:
class A __init__ awake
class B __init__ awake
method_b awake
method_a awake
What am I doing wrong? Is it the way I am passing my methods to Thread instance or something more fundamental?
Thanks.
A:
the most straight forward way to do it is to wrap the object creation and function execution in a function that does both, that will be executed entirely in another thread.
thread_a = Thread(target=lambda: A().method_a())
thread_b = Thread(target=lambda: B().method_b())
|
How to prevent class contructor from blocking other threads?
|
I am new to threading, so this question might be too basic.
I have two classes A and B. If I put their respective instances and methods in two threads as below:
from threading import Thread
from time import sleep
class A:
def __init__(self):
sleep(10)
print('class A __init__ awake')
def method_a(self):
sleep(10)
print('method_a awake')
class B:
def __init__(self):
sleep(1)
print('class B __init__ awake')
def method_b(self):
sleep(5)
print('method_b awake')
thread_a = Thread(target=A().method_a)
thread_b = Thread(target=B().method_b)
thread_a.start()
thread_b.start()
my expected result would be:
class B __init__ awake
method_b awake
class A __init__ awake
method_a awake
but I am getting:
class A __init__ awake
class B __init__ awake
method_b awake
method_a awake
What am I doing wrong? Is it the way I am passing my methods to Thread instance or something more fundamental?
Thanks.
|
[
"the most straight forward way to do it is to wrap the object creation and function execution in a function that does both, that will be executed entirely in another thread.\nthread_a = Thread(target=lambda: A().method_a())\nthread_b = Thread(target=lambda: B().method_b())\n\n"
] |
[
1
] |
[] |
[] |
[
"multithreading",
"python",
"python_class"
] |
stackoverflow_0074500138_multithreading_python_python_class.txt
|
Q:
matplotlib pyplot ParasiteAxes not allowing formatting of x label
The following can independently set the color, font and font size for the left and right y-axis, but can not set the font or font size for the x-axis. It can set the x-axis color. I'm using ParasiteAxes as they allow me to modify the plot formatting in other ways while working with matplotlib.animation. The goal is to be able to set the font, font size, and color differently for each of the axis labels and those should be independent of the ticklabels (at least the size).
`
from mpl_toolkits.axisartist.parasite_axes import HostAxes, ParasiteAxes
import matplotlib.pyplot as plt
plt.rcParams.update({'font.size': 16})
plt.rcParams.update({'font.weight': 'normal'})
plt.rcParams.update({'font.family': 'times new roman'})
x = [0, 1, 2]
y1 = [0, 1, 2]
y2 = [1, 2, 3]
fig = plt.figure(figsize=(8, 4.5))
host = fig.add_axes([0.10, 0.1, 0.60, 0.85], axes_class=HostAxes)
host.set_xlim(0, 2)
host.axis["right"].set_visible(False)
host.axis["left"].set_visible(False)
host.set_xlabel('X Axis', fontsize=24, fontfamily='courier new', color='tab:green')
y1_color = 'tab:red'
y1_axis = ParasiteAxes(host, sharex=host)
host.parasites.append(y1_axis)
y1_axis.axis['y1'] = y1_axis.new_fixed_axis(loc='left', offset=(0, 0))
y1_axis.set_ylim(0, 4)
y1_axis.set_ylabel('Y1 Axis')
y1_axis.axis['y1'].label.set(fontsize=12, color=y1_color, fontfamily='courier new')
y1_line, = y1_axis.plot([], [], lw=2, color=y1_color)
y1_line.set_data(x, y1)
y2_color = 'tab:blue'
y2_axis = ParasiteAxes(host, sharex=host)
host.parasites.append(y2_axis)
y2_axis.axis['y2'] = y2_axis.new_fixed_axis(loc='right', offset=(0, 0))
y2_axis.set_ylim(0, 4)
y2_axis.set_ylabel('y2 Axis')
y2_axis.axis['y2'].label.set(fontsize=24, color=y2_color, fontfamily='arial')
y2_line, = y2_axis.plot([], [], lw=2, color=y2_color)
y2_line.set_data(x, y2)
plt.show()
`
Here's the resulting plot:
I was expecting the x-axis label in the code above to be green 24-point Courier New, but in the plot it appears at green 16-point Times New Roman (taken on the rcParams except for the color. If the rcParams are modified then the ticklabels are modified which I want to remain independent of the x-axis label. I would appreciate a solution and also an explanation as to why the two axis objects are behaving differently.
A:
I can't speak to why the way you are currently setting your xlabel properties is not working but it looks like using
host.set_xlabel('X Axis')
host.axis["bottom"].label.set(fontsize=24, fontfamily='courier new', color='tab:green')
instead of host.set_xlabel('X Axis', fontsize=24, fontfamily='courier new', color='tab:green') solves it with matplotlib 3.6.2.
|
matplotlib pyplot ParasiteAxes not allowing formatting of x label
|
The following can independently set the color, font and font size for the left and right y-axis, but can not set the font or font size for the x-axis. It can set the x-axis color. I'm using ParasiteAxes as they allow me to modify the plot formatting in other ways while working with matplotlib.animation. The goal is to be able to set the font, font size, and color differently for each of the axis labels and those should be independent of the ticklabels (at least the size).
`
from mpl_toolkits.axisartist.parasite_axes import HostAxes, ParasiteAxes
import matplotlib.pyplot as plt
plt.rcParams.update({'font.size': 16})
plt.rcParams.update({'font.weight': 'normal'})
plt.rcParams.update({'font.family': 'times new roman'})
x = [0, 1, 2]
y1 = [0, 1, 2]
y2 = [1, 2, 3]
fig = plt.figure(figsize=(8, 4.5))
host = fig.add_axes([0.10, 0.1, 0.60, 0.85], axes_class=HostAxes)
host.set_xlim(0, 2)
host.axis["right"].set_visible(False)
host.axis["left"].set_visible(False)
host.set_xlabel('X Axis', fontsize=24, fontfamily='courier new', color='tab:green')
y1_color = 'tab:red'
y1_axis = ParasiteAxes(host, sharex=host)
host.parasites.append(y1_axis)
y1_axis.axis['y1'] = y1_axis.new_fixed_axis(loc='left', offset=(0, 0))
y1_axis.set_ylim(0, 4)
y1_axis.set_ylabel('Y1 Axis')
y1_axis.axis['y1'].label.set(fontsize=12, color=y1_color, fontfamily='courier new')
y1_line, = y1_axis.plot([], [], lw=2, color=y1_color)
y1_line.set_data(x, y1)
y2_color = 'tab:blue'
y2_axis = ParasiteAxes(host, sharex=host)
host.parasites.append(y2_axis)
y2_axis.axis['y2'] = y2_axis.new_fixed_axis(loc='right', offset=(0, 0))
y2_axis.set_ylim(0, 4)
y2_axis.set_ylabel('y2 Axis')
y2_axis.axis['y2'].label.set(fontsize=24, color=y2_color, fontfamily='arial')
y2_line, = y2_axis.plot([], [], lw=2, color=y2_color)
y2_line.set_data(x, y2)
plt.show()
`
Here's the resulting plot:
I was expecting the x-axis label in the code above to be green 24-point Courier New, but in the plot it appears at green 16-point Times New Roman (taken on the rcParams except for the color. If the rcParams are modified then the ticklabels are modified which I want to remain independent of the x-axis label. I would appreciate a solution and also an explanation as to why the two axis objects are behaving differently.
|
[
"I can't speak to why the way you are currently setting your xlabel properties is not working but it looks like using\nhost.set_xlabel('X Axis')\nhost.axis[\"bottom\"].label.set(fontsize=24, fontfamily='courier new', color='tab:green')\n\ninstead of host.set_xlabel('X Axis', fontsize=24, fontfamily='courier new', color='tab:green') solves it with matplotlib 3.6.2.\n\n"
] |
[
1
] |
[] |
[] |
[
"matplotlib",
"python"
] |
stackoverflow_0074485369_matplotlib_python.txt
|
Q:
Jupyter notebook not showing output on vs code mac
I installed the Jupyter Notebook to VS Code, but when I try to run anything it does not show me an output. Does anyone know why? And how I can fix this?
A:
It looks like you aren't connected to any Jupyter servers, so the cells are actually waiting to be run. Please see Visual Studio Docs on how to set up:
Setting up your environment
To work with Python in Jupyter Notebooks, you must activate an Anaconda environment in VS Code, or another Python environment in which you've installed the Jupyter package. To select an environment, use the Python: Select Interpreter command from the Command Palette (Ctrl+Shift+P).
Once the appropriate environment is activated, you can create and open a Jupyter Notebook, connect to a remote Jupyter server for running code cells, and export a Jupyter Notebook as a Python file.
Once a cell is ran properly, there should be a green tick under the cell like below:
|
Jupyter notebook not showing output on vs code mac
|
I installed the Jupyter Notebook to VS Code, but when I try to run anything it does not show me an output. Does anyone know why? And how I can fix this?
|
[
"It looks like you aren't connected to any Jupyter servers, so the cells are actually waiting to be run. Please see Visual Studio Docs on how to set up:\n\nSetting up your environment\nTo work with Python in Jupyter Notebooks, you must activate an Anaconda environment in VS Code, or another Python environment in which you've installed the Jupyter package. To select an environment, use the Python: Select Interpreter command from the Command Palette (Ctrl+Shift+P).\nOnce the appropriate environment is activated, you can create and open a Jupyter Notebook, connect to a remote Jupyter server for running code cells, and export a Jupyter Notebook as a Python file.\n\nOnce a cell is ran properly, there should be a green tick under the cell like below: \n"
] |
[
0
] |
[] |
[] |
[
"jupyter_notebook",
"python",
"visual_studio_code"
] |
stackoverflow_0074499671_jupyter_notebook_python_visual_studio_code.txt
|
Q:
How to select elements property in an array? python
I have a lot of similar arrays, i need to select properties of 'geo_lon' and 'geo_lat'. This one is just for an example:
[{'value': '658747', 'unrestricted_value': 'Алтайский край, Крутихинский р-н, с Волчно-Бурлинское, ул Партизанская, д 98', 'data': {'postal_code': '658747', 'is_closed': False, 'type_code': 'СОПС', 'address_str': 'Алтайский край, Крутихинский р-н, с Волчно-Бурлинское, ул Партизанская, д 98', 'address_kladr_id': '2202300000600', 'address_qc': '0', 'geo_lat': 54.053755, 'geo_lon': 80.768417, 'schedule_mon': '09:00-17:00, обед 13:00-14:00', 'schedule_tue': None, 'schedule_wed': '09:00-17:00, обед 13:00-14:00', 'schedule_thu': '09:00-17:00, обед 13:00-14:00', 'schedule_fri': '09:00-17:00, обед 13:00-14:00', 'schedule_sat': '09:00-16:00, обед 13:00-14:00', 'schedule_sun': None}}]
Im trying to do this (list_1 is an array, which i ve shown, im getting as a response)
for index, element in enumerate(list_1):
d = dadata.suggest("postal_unit", element)
for feature in d['data']:
coor = feature['geo_lon']
print(coor)
But this gives me an error:
for feature in d['data']:
TypeError: list indices must be integers or slices, not str
Im new to python
A:
Can you please try the following code.
for index, element in enumerate(list_1):
data = element["data"]
geo_lat = data["geo_lat"]
geo_lon = data["geo_lon"]
print("geo_lat: " + str(geo_lat) )
print("geo_lon: " + str(geo_lon) )
|
How to select elements property in an array? python
|
I have a lot of similar arrays, i need to select properties of 'geo_lon' and 'geo_lat'. This one is just for an example:
[{'value': '658747', 'unrestricted_value': 'Алтайский край, Крутихинский р-н, с Волчно-Бурлинское, ул Партизанская, д 98', 'data': {'postal_code': '658747', 'is_closed': False, 'type_code': 'СОПС', 'address_str': 'Алтайский край, Крутихинский р-н, с Волчно-Бурлинское, ул Партизанская, д 98', 'address_kladr_id': '2202300000600', 'address_qc': '0', 'geo_lat': 54.053755, 'geo_lon': 80.768417, 'schedule_mon': '09:00-17:00, обед 13:00-14:00', 'schedule_tue': None, 'schedule_wed': '09:00-17:00, обед 13:00-14:00', 'schedule_thu': '09:00-17:00, обед 13:00-14:00', 'schedule_fri': '09:00-17:00, обед 13:00-14:00', 'schedule_sat': '09:00-16:00, обед 13:00-14:00', 'schedule_sun': None}}]
Im trying to do this (list_1 is an array, which i ve shown, im getting as a response)
for index, element in enumerate(list_1):
d = dadata.suggest("postal_unit", element)
for feature in d['data']:
coor = feature['geo_lon']
print(coor)
But this gives me an error:
for feature in d['data']:
TypeError: list indices must be integers or slices, not str
Im new to python
|
[
"Can you please try the following code.\nfor index, element in enumerate(list_1):\n data = element[\"data\"]\n geo_lat = data[\"geo_lat\"]\n geo_lon = data[\"geo_lon\"]\n print(\"geo_lat: \" + str(geo_lat) )\n print(\"geo_lon: \" + str(geo_lon) )\n\n"
] |
[
0
] |
[] |
[] |
[
"arrays",
"json",
"python"
] |
stackoverflow_0074500278_arrays_json_python.txt
|
Q:
Python Regex to match a colon either side (left and right) of a word
At a complete loss here - trying to match a a colon either side of any given word in a passage of text.
For example:
:wave: Hello guys! :partyface: another huge win for us all to celebrate!
An appropriate regex that would match:
:wave:
:partyface:
Really appreciate your help!
\w*:\b
A:
To catch all the content
:[^:]*:
To catch the content between
(?<=:)[^:]*(?=:)
|
Python Regex to match a colon either side (left and right) of a word
|
At a complete loss here - trying to match a a colon either side of any given word in a passage of text.
For example:
:wave: Hello guys! :partyface: another huge win for us all to celebrate!
An appropriate regex that would match:
:wave:
:partyface:
Really appreciate your help!
\w*:\b
|
[
"To catch all the content\n:[^:]*:\n\nTo catch the content between\n(?<=:)[^:]*(?=:)\n\n"
] |
[
0
] |
[] |
[] |
[
"nlp",
"python",
"regex"
] |
stackoverflow_0074500309_nlp_python_regex.txt
|
Q:
Error while reading xlsm file by Pandas : "Conditional Formatting extension is not supported"
I want to read a xlsm file by Pandas:
pd.read_excel("data.xlsm", engine='openpyxl', sheet_name="sheet1")
But, I get the error:
C:\Users\anaconda3\lib\site-packages\openpyxl\worksheet\_read_only.py:79: UserWarning: Unknown extension is not supported and will be removed
for idx, row in parser.parse():
C:\Users\anaconda3\lib\site-packages\openpyxl\worksheet\_read_only.py:79: UserWarning: Conditional Formatting extension is not supported and will be removed
for idx, row in parser.parse():
Another try: I saved the data file by xlsx format and tried to read that by:
pd.read_excel("data.xlsx", engine='openpyxl', sheet_name="sheet1")
And this time, I get the following error:
File "C:\Users\AppData\Local\Temp\ipykernel_28028\1689108907.py", line 1, in <module>
data = pd.read_excel(data_original_filepath, engine='openpyxl', sheet_name=sheet_name)
File "C:\Users\anaconda3\lib\site-packages\pandas\util\_decorators.py", line 311, in wrapper
return func(*args, **kwargs)
File "C:\Users\anaconda3\lib\site-packages\pandas\io\excel\_base.py", line 457, in read_excel
io = ExcelFile(io, storage_options=storage_options, engine=engine)
File "C:\Users\anaconda3\lib\site-packages\pandas\io\excel\_base.py", line 1419, in __init__
self._reader = self._engines[engine](self._io, storage_options=storage_options)
File "C:\Users\anaconda3\lib\site-packages\pandas\io\excel\_openpyxl.py", line 525, in __init__
super().__init__(filepath_or_buffer, storage_options=storage_options)
File "C:\Users\anaconda3\lib\site-packages\pandas\io\excel\_base.py", line 518, in __init__
self.book = self.load_workbook(self.handles.handle)
File "C:\Users\anaconda3\lib\site-packages\pandas\io\excel\_openpyxl.py", line 536, in load_workbook
return load_workbook(
File "C:\Users\anaconda3\lib\site-packages\openpyxl\reader\excel.py", line 317, in load_workbook
reader.read()
File "C:\Users\anaconda3\lib\site-packages\openpyxl\reader\excel.py", line 278, in read
self.read_workbook()
File "C:\Users\anaconda3\lib\site-packages\openpyxl\reader\excel.py", line 150, in read_workbook
self.parser.parse()
File "C:\Users\anaconda3\lib\site-packages\openpyxl\reader\workbook.py", line 49, in parse
package = WorkbookPackage.from_tree(node)
File "C:\Users\anaconda3\lib\site-packages\openpyxl\descriptors\serialisable.py", line 83, in from_tree
obj = desc.from_tree(el)
File "C:\Users\anaconda3\lib\site-packages\openpyxl\descriptors\sequence.py", line 85, in from_tree
return [self.expected_type.from_tree(el) for el in node]
File "C:\Users\anaconda3\lib\site-packages\openpyxl\descriptors\sequence.py", line 85, in <listcomp>
return [self.expected_type.from_tree(el) for el in node]
File "C:\Users\anaconda3\lib\site-packages\openpyxl\descriptors\serialisable.py", line 103, in from_tree
return cls(**attrib)
TypeError: __init__() missing 1 required positional argument: 'id'
Any idea how to solve this issue?
In fact, I have to read the xlsm file. Changing the format to xlsx was only for trial purpose.
A:
Please try this block of code.
import openpyxl
file='data.xlsm'
wb=openpyxl.load_workbook(file, data_only=True, read_only=False, keep_vba=True)
|
Error while reading xlsm file by Pandas : "Conditional Formatting extension is not supported"
|
I want to read a xlsm file by Pandas:
pd.read_excel("data.xlsm", engine='openpyxl', sheet_name="sheet1")
But, I get the error:
C:\Users\anaconda3\lib\site-packages\openpyxl\worksheet\_read_only.py:79: UserWarning: Unknown extension is not supported and will be removed
for idx, row in parser.parse():
C:\Users\anaconda3\lib\site-packages\openpyxl\worksheet\_read_only.py:79: UserWarning: Conditional Formatting extension is not supported and will be removed
for idx, row in parser.parse():
Another try: I saved the data file by xlsx format and tried to read that by:
pd.read_excel("data.xlsx", engine='openpyxl', sheet_name="sheet1")
And this time, I get the following error:
File "C:\Users\AppData\Local\Temp\ipykernel_28028\1689108907.py", line 1, in <module>
data = pd.read_excel(data_original_filepath, engine='openpyxl', sheet_name=sheet_name)
File "C:\Users\anaconda3\lib\site-packages\pandas\util\_decorators.py", line 311, in wrapper
return func(*args, **kwargs)
File "C:\Users\anaconda3\lib\site-packages\pandas\io\excel\_base.py", line 457, in read_excel
io = ExcelFile(io, storage_options=storage_options, engine=engine)
File "C:\Users\anaconda3\lib\site-packages\pandas\io\excel\_base.py", line 1419, in __init__
self._reader = self._engines[engine](self._io, storage_options=storage_options)
File "C:\Users\anaconda3\lib\site-packages\pandas\io\excel\_openpyxl.py", line 525, in __init__
super().__init__(filepath_or_buffer, storage_options=storage_options)
File "C:\Users\anaconda3\lib\site-packages\pandas\io\excel\_base.py", line 518, in __init__
self.book = self.load_workbook(self.handles.handle)
File "C:\Users\anaconda3\lib\site-packages\pandas\io\excel\_openpyxl.py", line 536, in load_workbook
return load_workbook(
File "C:\Users\anaconda3\lib\site-packages\openpyxl\reader\excel.py", line 317, in load_workbook
reader.read()
File "C:\Users\anaconda3\lib\site-packages\openpyxl\reader\excel.py", line 278, in read
self.read_workbook()
File "C:\Users\anaconda3\lib\site-packages\openpyxl\reader\excel.py", line 150, in read_workbook
self.parser.parse()
File "C:\Users\anaconda3\lib\site-packages\openpyxl\reader\workbook.py", line 49, in parse
package = WorkbookPackage.from_tree(node)
File "C:\Users\anaconda3\lib\site-packages\openpyxl\descriptors\serialisable.py", line 83, in from_tree
obj = desc.from_tree(el)
File "C:\Users\anaconda3\lib\site-packages\openpyxl\descriptors\sequence.py", line 85, in from_tree
return [self.expected_type.from_tree(el) for el in node]
File "C:\Users\anaconda3\lib\site-packages\openpyxl\descriptors\sequence.py", line 85, in <listcomp>
return [self.expected_type.from_tree(el) for el in node]
File "C:\Users\anaconda3\lib\site-packages\openpyxl\descriptors\serialisable.py", line 103, in from_tree
return cls(**attrib)
TypeError: __init__() missing 1 required positional argument: 'id'
Any idea how to solve this issue?
In fact, I have to read the xlsm file. Changing the format to xlsx was only for trial purpose.
|
[
"Please try this block of code.\nimport openpyxl\nfile='data.xlsm'\nwb=openpyxl.load_workbook(file, data_only=True, read_only=False, keep_vba=True)\n\n\n"
] |
[
0
] |
[] |
[] |
[
"pandas",
"python",
"readfile",
"xlsm",
"xlsx"
] |
stackoverflow_0074497948_pandas_python_readfile_xlsm_xlsx.txt
|
Q:
How to solve: ValueError: Invalid format specifier?
h=1
m=1
s=30
k=5
ks = ((h * 60) + m + (s / 60)) / k
s=(ks - int(ks)) * 0.6
print(f'0{ks:.0f}:{s:.2f:.02}')
I am trying run the code, but i recieve the error: ValueError: Invalid format specifier
A:
ValueError: Invalid format specifier '.2f:.02' for object of type 'float'
This is the full error, simply you can't use 2f:.02 as specifier in brackets.
>>> print(f'0{ks:.0f}:{s:.2f}')
012:0.18
This is a sample output changing the specifier in brackets.
|
How to solve: ValueError: Invalid format specifier?
|
h=1
m=1
s=30
k=5
ks = ((h * 60) + m + (s / 60)) / k
s=(ks - int(ks)) * 0.6
print(f'0{ks:.0f}:{s:.2f:.02}')
I am trying run the code, but i recieve the error: ValueError: Invalid format specifier
|
[
"ValueError: Invalid format specifier '.2f:.02' for object of type 'float'\n\nThis is the full error, simply you can't use 2f:.02 as specifier in brackets.\n>>> print(f'0{ks:.0f}:{s:.2f}')\n012:0.18\n\nThis is a sample output changing the specifier in brackets.\n"
] |
[
1
] |
[] |
[] |
[
"format",
"printing",
"python"
] |
stackoverflow_0074500311_format_printing_python.txt
|
Q:
fetch the first nonzero entry for each column and record the corresponding index value
I have a dataframe that looks something like:
IndexMonth Cus1 Cus2 Cus3 Cus4 ........ Cusn
2019-01 0 111 0 0 333
2019-02 0 111 0 666 0
2019-03 500 0 333 55 0
2019-04 600 0 333 111 0
2019-05 600 100 0 111 0
I am looking to fetch the first non zero month for each Cus column, and also the last non-zero month. If the Cus has a break and it starts again, i want to have the new start also added in the start column.
So my output should look something like :
StartMonth EndMonth
Cus1 2019-03 2019-05
Cus2 2019-01,2019-05 2019-02,2019-05
Cus3 2019-03 2019-04
Cus4 2019-02 2019-05
..
Cusn 2019-01 2019-01
Could you please confirm how efficiently i can achieve this.
A:
You can use masks to keep the first/last date per succession of non-zeros, then aggregate:
df2 = df.set_index('IndexMonth')
m = df2.ne(0)
start = (df2
.where(m&~m.shift(fill_value=False))
.stack()
.reset_index('IndexMonth')
.groupby(level=0)['IndexMonth']
.agg(','.join)
.rename('StartMonth')
)
end = (df2
.where(m&~m.shift(-1, fill_value=False))
.stack()
.reset_index('IndexMonth')
.groupby(level=0)['IndexMonth']
.agg(','.join)
.rename('EndMonth')
)
out = pd.concat([start, end], axis=1)
print(out)
Output:
StartMonth EndMonth
Cus1 2019-03 2019-05
Cus2 2019-01,2019-05 2019-02,2019-05
Cus3 2019-03 2019-04
Cus4 2019-02 2019-05
Cusn 2019-01 2019-01
A:
First i use the transpose function then i get the first value not equal to 0 with idxmax. I get the last value with last_valid_index
df2=df.T
df2['first']=df2.ne(0).idxmax(axis=1)
df2['last']=df2[df2.columns[0:5]].mask(df2==0).apply(pd.Series.last_valid_index, axis=1)
#You should set the numbers 0 and 5 according to the number of columns. Here I am only getting the month columns.
print(df2)
'''
IndexMonth 2019-01 2019-02 2019-03 2019-04 2019-05 first last
Cus1 0 0 500 600 600 2019-03 2019-05
Cus2 111 111 0 0 100 2019-01 2019-05
Cus3 0 0 333 333 0 2019-03 2019-04
Cus4 0 666 55 111 111 2019-02 2019-05
Cusn 333 0 0 0 0 2019-01 2019-01
'''
First step is ok. For the second phase, I tried something like this, it works with this data, but I'm not sure if it will work correctly when the number of months changes:
df2['check']=False
for i in range (0,len(df2.index)):
col_name=df2['first'][i] #which columns is the first ?
if len(df2.iloc[i].loc[lambda x : x == df2[col_name][i]]) >= 2: #if there is more than one of the same value
df2['check'][i]=True #return true and fill the first first value with 0. To be able to get the latter when using idxmax.
df2[col_name][i]=0
df2['first_2']=df2.ne(0).idxmax(axis=1)
df2['is_combine']=(df2['check']==True) & (df2['last'] != df2['first_2'])
df2['StartMonth']=np.where(df2['is_combine']==True,(df2['first'] +', '+df2['last']),df2['first'])
df2['EndMonth']=np.where(df2['is_combine']==True,(df2['first_2'] +', '+df2['last']),df2['last'])
df2=df2[['StartMonth','EndMonth']]
print(df2)
'''
IndexMonth StartMonth EndMonth
Cus1 2019-03 2019-05
Cus2 2019-01, 2019-05 2019-02, 2019-05
Cus3 2019-03 2019-04
Cus4 2019-02 2019-05
Cusn 2019-01 2019-01
'''
|
fetch the first nonzero entry for each column and record the corresponding index value
|
I have a dataframe that looks something like:
IndexMonth Cus1 Cus2 Cus3 Cus4 ........ Cusn
2019-01 0 111 0 0 333
2019-02 0 111 0 666 0
2019-03 500 0 333 55 0
2019-04 600 0 333 111 0
2019-05 600 100 0 111 0
I am looking to fetch the first non zero month for each Cus column, and also the last non-zero month. If the Cus has a break and it starts again, i want to have the new start also added in the start column.
So my output should look something like :
StartMonth EndMonth
Cus1 2019-03 2019-05
Cus2 2019-01,2019-05 2019-02,2019-05
Cus3 2019-03 2019-04
Cus4 2019-02 2019-05
..
Cusn 2019-01 2019-01
Could you please confirm how efficiently i can achieve this.
|
[
"You can use masks to keep the first/last date per succession of non-zeros, then aggregate:\ndf2 = df.set_index('IndexMonth')\nm = df2.ne(0)\n\nstart = (df2\n .where(m&~m.shift(fill_value=False))\n .stack()\n .reset_index('IndexMonth')\n .groupby(level=0)['IndexMonth']\n .agg(','.join)\n .rename('StartMonth')\n )\n\nend = (df2\n .where(m&~m.shift(-1, fill_value=False))\n .stack()\n .reset_index('IndexMonth')\n .groupby(level=0)['IndexMonth']\n .agg(','.join)\n .rename('EndMonth')\n )\n\nout = pd.concat([start, end], axis=1)\n\nprint(out)\n\nOutput:\n StartMonth EndMonth\nCus1 2019-03 2019-05\nCus2 2019-01,2019-05 2019-02,2019-05\nCus3 2019-03 2019-04\nCus4 2019-02 2019-05\nCusn 2019-01 2019-01\n\n",
"First i use the transpose function then i get the first value not equal to 0 with idxmax. I get the last value with last_valid_index\ndf2=df.T\ndf2['first']=df2.ne(0).idxmax(axis=1)\ndf2['last']=df2[df2.columns[0:5]].mask(df2==0).apply(pd.Series.last_valid_index, axis=1)\n#You should set the numbers 0 and 5 according to the number of columns. Here I am only getting the month columns.\n\nprint(df2)\n'''\nIndexMonth 2019-01 2019-02 2019-03 2019-04 2019-05 first last\nCus1 0 0 500 600 600 2019-03 2019-05\nCus2 111 111 0 0 100 2019-01 2019-05\nCus3 0 0 333 333 0 2019-03 2019-04\nCus4 0 666 55 111 111 2019-02 2019-05\nCusn 333 0 0 0 0 2019-01 2019-01\n'''\n\nFirst step is ok. For the second phase, I tried something like this, it works with this data, but I'm not sure if it will work correctly when the number of months changes:\ndf2['check']=False\nfor i in range (0,len(df2.index)):\n col_name=df2['first'][i] #which columns is the first ?\n if len(df2.iloc[i].loc[lambda x : x == df2[col_name][i]]) >= 2: #if there is more than one of the same value\n\n df2['check'][i]=True #return true and fill the first first value with 0. To be able to get the latter when using idxmax.\n\n df2[col_name][i]=0\ndf2['first_2']=df2.ne(0).idxmax(axis=1)\ndf2['is_combine']=(df2['check']==True) & (df2['last'] != df2['first_2'])\ndf2['StartMonth']=np.where(df2['is_combine']==True,(df2['first'] +', '+df2['last']),df2['first'])\ndf2['EndMonth']=np.where(df2['is_combine']==True,(df2['first_2'] +', '+df2['last']),df2['last'])\ndf2=df2[['StartMonth','EndMonth']]\nprint(df2)\n'''\nIndexMonth StartMonth EndMonth\nCus1 2019-03 2019-05\nCus2 2019-01, 2019-05 2019-02, 2019-05\nCus3 2019-03 2019-04\nCus4 2019-02 2019-05\nCusn 2019-01 2019-01\n'''\n\n"
] |
[
2,
1
] |
[] |
[] |
[
"pandas",
"python"
] |
stackoverflow_0074499023_pandas_python.txt
|
Q:
Getting "ParserError" when I try to read a .txt file using pd.read_csv()
I am trying to convert this dataset: COCOMO81 to arff.
Before converting to .arff, I am trying to convert it to .csv
I am following this LINK to do this.
I got that dataset from promise site. I copied the entire page to notepad as cocomo81.txt and now I am trying to convert that cocomo81.txt file to .csv using python.
(I intend to convert the .csv file to .arff later using weka)
However, when I run
import pandas as pd
read_file = pd.read_csv(r"cocomo81.txt")
I get THIS ParserError.
To fix this, I followed this solution and modified my command to
read_file = pd.read_csv(r"cocomo81.txt",on_bad_lines='warn')
I got a bunch of warnings - you can see what it looks like here
and then I ran
read_file.to_csv(r'.\cocomo81csv.csv',index=None)
But it seems that the fix for ParserError didn't work in my case because my cocomo81csv.csv file looks like THIS in Excel.
Can someone please help me understand where I am going wrong and how can I use datasets from the promise repository in .arff format?
A:
You first need to parse the txt file.
Column names can be taken after @attribute
@attribute rely numeric
@attribute data numeric
@attribute cplx numeric
@attribute time numeric
..............................
And in the csv file, load only the data after @data which is at the end of the file. You can just copy/paste.
0.88,1.16,0.7,1,1.06,1.15,1.07,1.19,1.13,1.17,1.1,1,1.24,1.1,1.04,113,2040
0.88,1.16,0.85,1,1.06,1,1.07,1,0.91,1,0.9,0.95,1.1,1,1,293,1600
1,1.16,0.85,1,1,0.87,0.94,0.86,0.82,0.86,0.9,0.95,0.91,0.91,1,132,243
0.75,1.16,0.7,1,1,0.87,1,1.19,0.91,1.42,1,0.95,1.24,1,1.04,60,240
...................................................................
And then read the resulting csv file
pd.read_csv(file, names=["rely", "data", "cplx", ...])
A:
Looks like it's a csv file with comments as the first lines. The comment lines are indicated by % characters, but also @(?), and the actual csv data starts at line 230.
You should skip the first rows and manually set the column names, try something like this:
# set column names manually
col_names = ["rely", "data", "cplx", "time", "stor", "virt", "turn", "acap", "aexp", "pcap", "vexp", "lexp", "modp", "tool", "sced", "loc", "actual" ]
filename = "cocomo81.arff.txt"
# read csv data
df = pd.read_csv(filename, skiprows=229, sep=',', decimal='.', header=None, names=col_names)
print(df)
|
Getting "ParserError" when I try to read a .txt file using pd.read_csv()
|
I am trying to convert this dataset: COCOMO81 to arff.
Before converting to .arff, I am trying to convert it to .csv
I am following this LINK to do this.
I got that dataset from promise site. I copied the entire page to notepad as cocomo81.txt and now I am trying to convert that cocomo81.txt file to .csv using python.
(I intend to convert the .csv file to .arff later using weka)
However, when I run
import pandas as pd
read_file = pd.read_csv(r"cocomo81.txt")
I get THIS ParserError.
To fix this, I followed this solution and modified my command to
read_file = pd.read_csv(r"cocomo81.txt",on_bad_lines='warn')
I got a bunch of warnings - you can see what it looks like here
and then I ran
read_file.to_csv(r'.\cocomo81csv.csv',index=None)
But it seems that the fix for ParserError didn't work in my case because my cocomo81csv.csv file looks like THIS in Excel.
Can someone please help me understand where I am going wrong and how can I use datasets from the promise repository in .arff format?
|
[
"You first need to parse the txt file.\nColumn names can be taken after @attribute\n@attribute rely numeric\n@attribute data numeric\n@attribute cplx numeric\n@attribute time numeric\n..............................\n\nAnd in the csv file, load only the data after @data which is at the end of the file. You can just copy/paste.\n0.88,1.16,0.7,1,1.06,1.15,1.07,1.19,1.13,1.17,1.1,1,1.24,1.1,1.04,113,2040\n0.88,1.16,0.85,1,1.06,1,1.07,1,0.91,1,0.9,0.95,1.1,1,1,293,1600\n1,1.16,0.85,1,1,0.87,0.94,0.86,0.82,0.86,0.9,0.95,0.91,0.91,1,132,243\n0.75,1.16,0.7,1,1,0.87,1,1.19,0.91,1.42,1,0.95,1.24,1,1.04,60,240\n...................................................................\n\nAnd then read the resulting csv file\npd.read_csv(file, names=[\"rely\", \"data\", \"cplx\", ...])\n\n",
"Looks like it's a csv file with comments as the first lines. The comment lines are indicated by % characters, but also @(?), and the actual csv data starts at line 230.\nYou should skip the first rows and manually set the column names, try something like this:\n# set column names manually\ncol_names = [\"rely\", \"data\", \"cplx\", \"time\", \"stor\", \"virt\", \"turn\", \"acap\", \"aexp\", \"pcap\", \"vexp\", \"lexp\", \"modp\", \"tool\", \"sced\", \"loc\", \"actual\" ]\nfilename = \"cocomo81.arff.txt\"\n\n# read csv data\ndf = pd.read_csv(filename, skiprows=229, sep=',', decimal='.', header=None, names=col_names)\n\nprint(df)\n\n"
] |
[
1,
1
] |
[] |
[] |
[
"arff",
"csv",
"dataset",
"python",
"txt"
] |
stackoverflow_0074498991_arff_csv_dataset_python_txt.txt
|
Q:
Deploy Django Project Using Pyinstaller
I have a django project, that works similar to Jupyter Notebook, in terms of Being a program launched offline in localhost on a web browser, moreover my webapp has an opencv webcam pop-up, that will be launched when you press a button.
I want to deploy my django project, so it can be launched by just clicking a file in Windows.
According to what I read, There are two possible solutions:
Install Python Interpreter with Dependencies on client computer first, and using a bat file, to launch the django server.
Containerizing the Django project with Python and its dependencies, either using Docker or perhaps an exe file?
Which solution is better? I would prefer the second one personally, but I’m confused how to do so.
Can it be done as simple as using pyinstaller or not?
Here are my dependencies for reference:
Django
pillow
django-object-actions
django_user_agents
django-cleanup
opencv-python
imutils
cmake
dlib
face-recognition
A:
I think that the best practise would be to use containers like e.g. docker. After that you have the following benefits:
Dependencies inside the container machine (automatically with pip install from requirements file)
Multiplatform possibility
Versioning with tags
You can run database in a second container if needed (combined with docker compose)
Click and run with docker desktop
fyi: There a lots of tutorials on how to deploy django in docker containers :)
|
Deploy Django Project Using Pyinstaller
|
I have a django project, that works similar to Jupyter Notebook, in terms of Being a program launched offline in localhost on a web browser, moreover my webapp has an opencv webcam pop-up, that will be launched when you press a button.
I want to deploy my django project, so it can be launched by just clicking a file in Windows.
According to what I read, There are two possible solutions:
Install Python Interpreter with Dependencies on client computer first, and using a bat file, to launch the django server.
Containerizing the Django project with Python and its dependencies, either using Docker or perhaps an exe file?
Which solution is better? I would prefer the second one personally, but I’m confused how to do so.
Can it be done as simple as using pyinstaller or not?
Here are my dependencies for reference:
Django
pillow
django-object-actions
django_user_agents
django-cleanup
opencv-python
imutils
cmake
dlib
face-recognition
|
[
"I think that the best practise would be to use containers like e.g. docker. After that you have the following benefits:\n\nDependencies inside the container machine (automatically with pip install from requirements file)\nMultiplatform possibility\nVersioning with tags\nYou can run database in a second container if needed (combined with docker compose)\nClick and run with docker desktop\n\nfyi: There a lots of tutorials on how to deploy django in docker containers :)\n"
] |
[
1
] |
[] |
[] |
[
"batch_file",
"django",
"executable",
"pyinstaller",
"python"
] |
stackoverflow_0074499789_batch_file_django_executable_pyinstaller_python.txt
|
Q:
Can't install Django in visual studio code
So I'm creating a forum according to this tutorial: https://www.youtube.com/watch?v=YXmsi13cMhw&t=2594s
I'm stuck at 2:10.I've successfully created a virtual enviroment, can't go past this error.enter image description here
Where do I get project name?What on Earth is wrong here?Sorry if I got a little emotional.
I tried to do everything exactly like in aforementioned tutorial.
A:
python AutoDjango.py --django --project PROJECTNAME --app APPNAME solved it.
In the tutorial,for some reason, he used post_installation command assuming we are doind for the first time. and didnt clarify it. No offence though.
So, deleting post_installation solved it.
|
Can't install Django in visual studio code
|
So I'm creating a forum according to this tutorial: https://www.youtube.com/watch?v=YXmsi13cMhw&t=2594s
I'm stuck at 2:10.I've successfully created a virtual enviroment, can't go past this error.enter image description here
Where do I get project name?What on Earth is wrong here?Sorry if I got a little emotional.
I tried to do everything exactly like in aforementioned tutorial.
|
[
"python AutoDjango.py --django --project PROJECTNAME --app APPNAME solved it.\nIn the tutorial,for some reason, he used post_installation command assuming we are doind for the first time. and didnt clarify it. No offence though.\nSo, deleting post_installation solved it.\n"
] |
[
0
] |
[] |
[] |
[
"backend",
"django",
"python",
"web"
] |
stackoverflow_0074500247_backend_django_python_web.txt
|
Q:
dict.get or list check, which is faster?
If I want to get a bot with an ID, which is faster between:
storage = {
'bots': [
{ 'id': 123, 'auth': '81792367' },
{ 'id': 345, 'auth': '86908472' },
{ 'id': 543, 'auth': '12343321' }
]
}
id = 345
bot = next(bot['auth'] for bot in storage['bots'] if bot['id'] == id)
and
storage = {
'bots': {
123: '81792367',
345: '86908472',
543: '12343321',
}
}
id = 345
bot = storage['bots'][id]
and which must be used for the Python pep8 or most beautiful?
A:
Bear in mind that the time complexity of lookup (i.e using the in keyword) for a list is O(n) whereas, the same operation has a time complexity of O(1) for a dictionary (Time Complexity of Collection Ops)
Meanwhile the Time Complexity of Get Item is same (O(1)) for both. So, I would say you're better off with the second approach.
|
dict.get or list check, which is faster?
|
If I want to get a bot with an ID, which is faster between:
storage = {
'bots': [
{ 'id': 123, 'auth': '81792367' },
{ 'id': 345, 'auth': '86908472' },
{ 'id': 543, 'auth': '12343321' }
]
}
id = 345
bot = next(bot['auth'] for bot in storage['bots'] if bot['id'] == id)
and
storage = {
'bots': {
123: '81792367',
345: '86908472',
543: '12343321',
}
}
id = 345
bot = storage['bots'][id]
and which must be used for the Python pep8 or most beautiful?
|
[
"Bear in mind that the time complexity of lookup (i.e using the in keyword) for a list is O(n) whereas, the same operation has a time complexity of O(1) for a dictionary (Time Complexity of Collection Ops)\nMeanwhile the Time Complexity of Get Item is same (O(1)) for both. So, I would say you're better off with the second approach.\n"
] |
[
2
] |
[] |
[] |
[
"pep8",
"python"
] |
stackoverflow_0074500257_pep8_python.txt
|
Q:
Get values from variable in function and apply second conditional
I have this function,
def compare_date(x):
if pd.to_datetime(x) < pd.to_datetime('2019-09-01'):
return pd.to_datetime('2019-09-01')
else:
return pd.to_datetime(x)
file['Cash Received Date'] = file['CASH RECIEVED DATE'].apply(lambda x: compare_date(x))
that returns file as:
CASH RECIEVED DATE Cash Received Date
0 2018-07-23 2019-09-01
1 2019-09-26 2019-09-26
2 2017-05-02 2019-09-01
However, I need change the dates so they get the value of two variables that are Year (in format yyyy, it can be any year) and Month (in format MM, it can be any month), so I thought to change my function to something like this, that didn't work:
def compare_date(x):
if pd.to_datetime(x) > pd.to_datetime(Year + '-' + Month + '-01'):
return pd.to_datetime(Year + '-' + Month + '-01')
else:
return pd.to_datetime(x)
file['Cash Received Date'] = file['CASH RECIEVED DATE'].apply(lambda x: compare_date(x))
I tried to convert Year.astype('string') and Month.astype('string') and it didn't work either.
Furthermore, I'd like to add a second conditional to this function that if the column file['Policy'] is X then change dates as per above, else copy value of file['CASH RECIEVED DATE'] to file['Cash Received Date']
A:
Basically your problem is that you cannot use a lambda as you need to apply an operation to obtain your new column taking into account the value on several columns. You can still use apply method but as shown on code snippet below:
import pandas as pd
file = pd.DataFrame.from_dict({"month": ["10", "11", "12"],
"year": ["2020", "2018", "2021"],
"cash_received_date": ["2019-01-01", "2019-01-01", "2019-01-01"]})
def compare_date(row):
if pd.to_datetime(row["cash_received_date"]) > pd.to_datetime(row["year"] + '-' + row["month"] + '-01'):
return pd.to_datetime(row["year"] + '-' + row["month"] + '-01')
else:
return pd.to_datetime(row["cash_received_date"])
file['Cash Received Date'] = file.apply(compare_date, axis=1)
|
Get values from variable in function and apply second conditional
|
I have this function,
def compare_date(x):
if pd.to_datetime(x) < pd.to_datetime('2019-09-01'):
return pd.to_datetime('2019-09-01')
else:
return pd.to_datetime(x)
file['Cash Received Date'] = file['CASH RECIEVED DATE'].apply(lambda x: compare_date(x))
that returns file as:
CASH RECIEVED DATE Cash Received Date
0 2018-07-23 2019-09-01
1 2019-09-26 2019-09-26
2 2017-05-02 2019-09-01
However, I need change the dates so they get the value of two variables that are Year (in format yyyy, it can be any year) and Month (in format MM, it can be any month), so I thought to change my function to something like this, that didn't work:
def compare_date(x):
if pd.to_datetime(x) > pd.to_datetime(Year + '-' + Month + '-01'):
return pd.to_datetime(Year + '-' + Month + '-01')
else:
return pd.to_datetime(x)
file['Cash Received Date'] = file['CASH RECIEVED DATE'].apply(lambda x: compare_date(x))
I tried to convert Year.astype('string') and Month.astype('string') and it didn't work either.
Furthermore, I'd like to add a second conditional to this function that if the column file['Policy'] is X then change dates as per above, else copy value of file['CASH RECIEVED DATE'] to file['Cash Received Date']
|
[
"Basically your problem is that you cannot use a lambda as you need to apply an operation to obtain your new column taking into account the value on several columns. You can still use apply method but as shown on code snippet below:\nimport pandas as pd\n\nfile = pd.DataFrame.from_dict({\"month\": [\"10\", \"11\", \"12\"],\n \"year\": [\"2020\", \"2018\", \"2021\"],\n \"cash_received_date\": [\"2019-01-01\", \"2019-01-01\", \"2019-01-01\"]})\n\ndef compare_date(row):\n if pd.to_datetime(row[\"cash_received_date\"]) > pd.to_datetime(row[\"year\"] + '-' + row[\"month\"] + '-01'):\n return pd.to_datetime(row[\"year\"] + '-' + row[\"month\"] + '-01')\n else:\n return pd.to_datetime(row[\"cash_received_date\"])\n\nfile['Cash Received Date'] = file.apply(compare_date, axis=1)\n\n"
] |
[
0
] |
[] |
[] |
[
"function",
"jupyter_notebook",
"lambda",
"pandas",
"python"
] |
stackoverflow_0074499352_function_jupyter_notebook_lambda_pandas_python.txt
|
Q:
Writing to Console and File in Python Script
I am looking for some help on a project I am doing where I need to output the responses to the console as well as write them to a file. I am having trouble figuring that part out. I have been able to write the responses to a file successfully, but not both at the same time. Can someone help with that portion? The only lines that need to be written to the file are the ones that I have currently being written to a file
from datetime import datetime
import requests
import pytemperature
def main():
api_start = 'https://api.openweathermap.org/data/2.5/weather?q='
api_key = '&appid=91b8698c2ed6c192aabde7c9e75d23cb'
now = datetime.now()
filename = input("\nEnter the output filename: ")
myfile = None
try:
myfile = open(filename, "w")
except:
print("Unable to open file " + filename +
"\nData will not be saved to a file")
choice = "y"
print("ISQA 3900 Open Weather API", file=myfile)
print(now.strftime("%A, %B %d, %Y"), file=myfile)
while choice.lower() == "y":
# input city and country code
city = input("Enter city: ")
print("Use ISO letter country code like: https://countrycode.org/")
country = input("Enter country code: ")
# app configures url to generate json data
url = api_start + city + ',' + country + api_key
json_data = requests.get(url).json()
try:
# getting weather data from json
weather_description = json_data['weather'][0]['description']
# printing weather information
print("\nThe Weather Report for " + city + " in " + country + " is:", file=myfile)
print("\tCurrent conditions: ", weather_description, file=myfile)
# getting temperature data from json
current_temp_kelvin = json_data['main']['temp']
current_temp_fahrenheit = pytemperature.k2f(current_temp_kelvin)
# printing temperature information
print("\tCurrent temperature in Fahrenheit:", current_temp_fahrenheit, file=myfile)
# getting pressure data from json
current_pressure = json_data['main']['pressure']
# printing pressure information
print("\tCurrent pressure in HPA:", current_pressure, file=myfile)
# getting humidity data from json
current_humidity = json_data['main']['humidity']
# printing humidity information
print("\tCurrent humidity:", "%s%%" % current_humidity, file=myfile)
# getting expected low temp data from json
expected_low_temp = json_data['main']['temp_min']
expected_low_temp = pytemperature.k2f(expected_low_temp)
# printing expected low temp information
print("\tExpected low temperature in Fahrenheit:", expected_low_temp, file=myfile)
# getting expected high temp data from json
expected_high_temp = json_data['main']['temp_max']
expected_high_temp = pytemperature.k2f(expected_high_temp)
# printing expected high temp information
print("\tExpected high temperature in Fahrenheit:", expected_high_temp, file=myfile)
choice = input("Continue (y/n)?: ")
print()
except:
print("Unable to access ", city, " in ", country)
print("Verify city name and country code")
if myfile:
myfile.close()
print('Thank you - Goodbye')
if __name__ == "__main__":
main()
Honestly I am kind of at a loss on this one for some reason it is just kicking my butt.
A:
For printing a single object:
def mprint(text, file):
print(text)
print(text, file = file)
A more general one for printing several objects:
def mprint(*args):
print(*args[:-1])
print(*args[:-1],file = args[-1])
Usage: mprint(obj1, obj2, ... , myfile)
A:
A completely general print function replacement would look something like:
def myprint(*args, file=None, **kwargs):
print(*args, **kwargs) # print to screen
if file is not None:
print(*args, file=fp, **kwargs) # print to file
this will let you use end=.. etc. as well
filename = input("\nEnter the output filename: ")
myfile = None
try:
myfile = open(filename, "w")
except:
print("Unable to open file " + filename +
"\nData will not be saved to a file")
choice = "y"
myprint("ISQA 3900 Open Weather API", file=myfile)
myprint(now.strftime("%A, %B %d, %Y"), file=myfile)
if myfile couldn't be opened and is therefore None, the myprint function will only print to screen.
|
Writing to Console and File in Python Script
|
I am looking for some help on a project I am doing where I need to output the responses to the console as well as write them to a file. I am having trouble figuring that part out. I have been able to write the responses to a file successfully, but not both at the same time. Can someone help with that portion? The only lines that need to be written to the file are the ones that I have currently being written to a file
from datetime import datetime
import requests
import pytemperature
def main():
api_start = 'https://api.openweathermap.org/data/2.5/weather?q='
api_key = '&appid=91b8698c2ed6c192aabde7c9e75d23cb'
now = datetime.now()
filename = input("\nEnter the output filename: ")
myfile = None
try:
myfile = open(filename, "w")
except:
print("Unable to open file " + filename +
"\nData will not be saved to a file")
choice = "y"
print("ISQA 3900 Open Weather API", file=myfile)
print(now.strftime("%A, %B %d, %Y"), file=myfile)
while choice.lower() == "y":
# input city and country code
city = input("Enter city: ")
print("Use ISO letter country code like: https://countrycode.org/")
country = input("Enter country code: ")
# app configures url to generate json data
url = api_start + city + ',' + country + api_key
json_data = requests.get(url).json()
try:
# getting weather data from json
weather_description = json_data['weather'][0]['description']
# printing weather information
print("\nThe Weather Report for " + city + " in " + country + " is:", file=myfile)
print("\tCurrent conditions: ", weather_description, file=myfile)
# getting temperature data from json
current_temp_kelvin = json_data['main']['temp']
current_temp_fahrenheit = pytemperature.k2f(current_temp_kelvin)
# printing temperature information
print("\tCurrent temperature in Fahrenheit:", current_temp_fahrenheit, file=myfile)
# getting pressure data from json
current_pressure = json_data['main']['pressure']
# printing pressure information
print("\tCurrent pressure in HPA:", current_pressure, file=myfile)
# getting humidity data from json
current_humidity = json_data['main']['humidity']
# printing humidity information
print("\tCurrent humidity:", "%s%%" % current_humidity, file=myfile)
# getting expected low temp data from json
expected_low_temp = json_data['main']['temp_min']
expected_low_temp = pytemperature.k2f(expected_low_temp)
# printing expected low temp information
print("\tExpected low temperature in Fahrenheit:", expected_low_temp, file=myfile)
# getting expected high temp data from json
expected_high_temp = json_data['main']['temp_max']
expected_high_temp = pytemperature.k2f(expected_high_temp)
# printing expected high temp information
print("\tExpected high temperature in Fahrenheit:", expected_high_temp, file=myfile)
choice = input("Continue (y/n)?: ")
print()
except:
print("Unable to access ", city, " in ", country)
print("Verify city name and country code")
if myfile:
myfile.close()
print('Thank you - Goodbye')
if __name__ == "__main__":
main()
Honestly I am kind of at a loss on this one for some reason it is just kicking my butt.
|
[
"For printing a single object:\ndef mprint(text, file):\n print(text)\n print(text, file = file)\n\nA more general one for printing several objects:\ndef mprint(*args):\n print(*args[:-1])\n print(*args[:-1],file = args[-1])\n\nUsage: mprint(obj1, obj2, ... , myfile)\n",
"A completely general print function replacement would look something like:\ndef myprint(*args, file=None, **kwargs):\n print(*args, **kwargs) # print to screen\n if file is not None:\n print(*args, file=fp, **kwargs) # print to file\n\nthis will let you use end=.. etc. as well\n filename = input(\"\\nEnter the output filename: \")\n myfile = None\n try:\n myfile = open(filename, \"w\")\n except:\n print(\"Unable to open file \" + filename +\n \"\\nData will not be saved to a file\")\n\n choice = \"y\"\n\n myprint(\"ISQA 3900 Open Weather API\", file=myfile)\n myprint(now.strftime(\"%A, %B %d, %Y\"), file=myfile)\n\nif myfile couldn't be opened and is therefore None, the myprint function will only print to screen.\n"
] |
[
0,
0
] |
[] |
[] |
[
"console",
"file",
"output",
"python"
] |
stackoverflow_0074495268_console_file_output_python.txt
|
Q:
Seaborn: Histogram doesn't start at 0
I'm trying to plot differents histograms in SeaBorn with this code (I've translated from spanish to english, so everyone can understand it):
#We assign diffent colours for the mean, the median, and the mode (red, green, and blue), for the legend of the graphics plotted
ref_mean = mpatches.Patch(color='red', label='Mean')
ref_median = mpatches.Patch(color='green', label='Median')
ref_mode = mpatches.Patch(color='blue', label='Mode')
tags=[ref_mean,ref_median,ref_mode]
...
ax = sns.displot(data=districts,
x="POPULATION_DENSITY",
multiple="stack",
height=6,
aspect=2,
kind='hist',
bins=BINNING_VALUE,
stat='density',
kde=True).set(title='Density Population Histogram')
ax.set(xlabel='Density Population (hab/km´2)', ylabel='Relative quantity of districts')
plt.axvline(x=districts.POPULATION_DENSITY.mean(),
color='red')
plt.axvline(x=districts.POPULATION_DENSITY.median(),
color='green')
plt.axvline(x=mode(x=districts.POPULATION_DENSITY,BINNING_VALUE),
color='blue')
plt.legend(handles=tags)
ax = sns.displot(data=districts,
x="UBN_PERCENTAGE",
multiple="stack",
height=6,
aspect=2,
kind='hist',
bins=BINNING_VALUE,
stat='density',
ax=0,
kde=True).set(title='Percentage of unsatisfied basic needs histogram')
ax.set(xlabel='%UBN', ylabel='Relative quantity of districts')
plt.axvline(x=districts.UBN_PERCENTAGE.mean(),
color='red')
plt.axvline(x=districts.UBN_PERCENTAGE.median(),
color='green')
plt.axvline(x=mode(districts.UBN_PERCENTAGE,BINNING_VALUE),
color='blue')
plt.legend(handles=tags)
My result is this one:
Where 'Densidad Habitacional' means 'Population Density', and 'Necesidades Básicas Insatisfechas (NBI)' means 'Unsatisfied Basic Needs (UBN)'.
So then, in the first histogram plot shown at the screenshot, the first bar (at the left of all), starts at range 0. However, in the second one, we can see that the first bar doesn't start at 0, but in a greater value instead.
Also, viewing these values, I can also see that there's something wrong: in the second interval we have 60 observations, and in the third one, we have 30. However, at the histogram, we can see that the third bar has a lower height than the half or the second one, since 30 is exactly the half of 60.
I have defined a function which returns me a sequence with the frequency of every interval, and also a sequence with those delimiters, like this:
frequencies: [5.0, 60.0, 30.0, 17.0, 10.0, 11.0, 3.0, 2.0, 2.0, 0.0, 1.0]
delimiters: [0.0, 2.29, 4.57, 6.86, 9.15, 11.44, 13.72, 16.01, 18.3, 20.59, 22.87, 25.16]
Those are the corresponding values to the second histogram shown (UBN Percentage).
I've also used these values returned by that function, to calculate the mode of the variable in another defined function.
My code of these functions is this one:
import pandas as pd
import numpy as np
"""
In the constant 'BINNING_VALUE", we define the quantity of intervals in which we will subdivide
the statistical population (we refer here to the number of records, not to the number of habitants),
to carry out the corresponding analysis.
it just so happens that conveniently, we have a total of 141 records in our database, being such number
a perfect square of 12, so that this value it turns out to us ideal to carry out that binning.
#of intervals will correspond to this value less 1. That's it, if we have 12 delimiters, then we'll have 11 intervals.
As an important issue, this value determines the quantity of interval delimitations, whereby the quantity
""";
BINNING_VALUE=12
"""
This function recives as a parameter in 'column', a column of N observations, (which can be a Pandas Series),
and in 'bins, the quantity of delimitations of class intervals, in which we categorize those observations.
It returns both a list with the class intervals, with their corresponding frequency in each of its elements,
and a list of divisions, which defines the range of each interval.
For example, if recieve have a column of 16 rows, like this:
Index Value
0 15
1 9
2 2
3 5
4 27
5 1
6 7
7 18
8 25
9 1
10 42
11 48
12 37
13 31
14 45
15 33
And then, our bin value is 4, it will return the following sequences:
interval_list: [7,4,5]
ranges_list: [0,16,32,48]
""";
def intervals(column,bins):
#In 'max_value', I'll store the maximum value of the element in the recived column.
max_value=column.max()
#I generate a ranges list (converted from an array with 'tolist' function),
#with a length equal to the bins parameter (quantity of class intervals + 1),
#whose values will go from 0 to the maximum value of the column element, linearly subdivided.
ranges_list=np.linspace(0,max_value,bins).tolist()
#I generate an array with a length equal to the quantity of class intervals (bins -1),
#initially loaded with zeros.
intervals_array=np.zeros(bins-1)
#With a for loop (in which I need the indexes value, starting at position 1), I iterate over
#the ranges list with the 'i' variable, so I can also iterate over the class interval
for i in range(1,bins):
#I declare a variable, which will be reseted to 0 in each iteration of
#the outer loop, in which I'll count the column items located into each range
count_range_elements=0
#With a nested for, I'll iterate over each element of the column
for element in column:
#If the column element value where I'm standing now, lies within the class interval
#which I'm standing in the outer loop
if element > ranges_list[i-1] and element <= ranges_list[i]:
#I increase the element counter
count_range_elements+=1
#Once executed the inner for, I load in position i-1 of my class intervals array,
#the quantity of elements I've counted in the corresponding range
intervals_array[i-1]=count_range_elements
#Once executed both nested for loops, I have now my class intervals array loaded
#with the corresponding values
#I convert my class intervals array into a list
intervals_list=intervals_array.tolist()
#I return a tuple with both the class intervals list and the ranges list
return (intervals_list, ranges_list)
"""
This function recives as a parameter in 'column', a column of N observations, and in 'bins, the quantity of delimitations of class intervals, in which we categorize those observations.
It returns the approximate mode, calculated for such column, according to quantity of class intervlas quantity ('bins' value - 1 ), into we'll bin our data
""";
def mode(column,bins):
#From the 'intervals' function, to which I pass the recived parameters 'column' and 'bins',
#I'm getting the sequences with the needed values to calculate the mode
intervals_list, ranges_list = intervals(column,bins)
#From the intervals list, I'm storing the index to its maximum value.
#This will be the position of our modal class interval (where the mode is found)
ind_max_val = intervals_list.index(max(intervals_list))
#The lower limit of the modal class interval, will be the element of the ranges
#list, whose index is equal to the one correspondent to the maximum element of the
#class intervals list
lower_limit=ranges_list[ind_max_val]
#Values 'a' and 'b' represents:
#a: Difference between the height of the modal interval, and previous interval
#b: Difference between the height of the modal interval, and next interval
#Since these values are calculated based on the position of modal interval, depending if
#this one is located at and extreme of the list, or in the middle of it, we need this values
#outside of the scope of the 'if/else' sentences, so we declarate this variables here, with
#0 as it's initial value.
a=0
b=0
#In the 'c' value, we'll have the amplitude of class modal interval
#(as like any other, since the amplitude is the same for all intervals)
c=ranges_list[ind_max_val+1] - ranges_list[ind_max_val]
#We calculate the 'a' value, depending if the modal interval is at the
#start of the list (at the left of all), or if it doesn't
if ind_max_val > 0:
a=intervals_list[ind_max_val] - intervals_list[ind_max_val-1]
else:
a=intervals_list[ind_max_val]
#We calculate the 'b' value, depending if the modal interval is at the
#end of the list (at the right of all), or if it doesn't
if ind_max_val < (bins-1):
b=intervals_list[ind_max_val] - intervals_list[ind_max_val+1]
else:
b=intervals_list[ind_max_val]
#Once obtained every value needed, we'll apply it in the mode formula,
#and we store the result in a variable
mode= lower_limit + (a/(a+b))*c
#Finally, we return the calculated mode value
return mode
Since I'm not a native english speaker, if someone finds a grammar mistake somewhere, please correct me.
Does anyone have an idea of what should I do?
Thanks a lot!
|
Seaborn: Histogram doesn't start at 0
|
I'm trying to plot differents histograms in SeaBorn with this code (I've translated from spanish to english, so everyone can understand it):
#We assign diffent colours for the mean, the median, and the mode (red, green, and blue), for the legend of the graphics plotted
ref_mean = mpatches.Patch(color='red', label='Mean')
ref_median = mpatches.Patch(color='green', label='Median')
ref_mode = mpatches.Patch(color='blue', label='Mode')
tags=[ref_mean,ref_median,ref_mode]
...
ax = sns.displot(data=districts,
x="POPULATION_DENSITY",
multiple="stack",
height=6,
aspect=2,
kind='hist',
bins=BINNING_VALUE,
stat='density',
kde=True).set(title='Density Population Histogram')
ax.set(xlabel='Density Population (hab/km´2)', ylabel='Relative quantity of districts')
plt.axvline(x=districts.POPULATION_DENSITY.mean(),
color='red')
plt.axvline(x=districts.POPULATION_DENSITY.median(),
color='green')
plt.axvline(x=mode(x=districts.POPULATION_DENSITY,BINNING_VALUE),
color='blue')
plt.legend(handles=tags)
ax = sns.displot(data=districts,
x="UBN_PERCENTAGE",
multiple="stack",
height=6,
aspect=2,
kind='hist',
bins=BINNING_VALUE,
stat='density',
ax=0,
kde=True).set(title='Percentage of unsatisfied basic needs histogram')
ax.set(xlabel='%UBN', ylabel='Relative quantity of districts')
plt.axvline(x=districts.UBN_PERCENTAGE.mean(),
color='red')
plt.axvline(x=districts.UBN_PERCENTAGE.median(),
color='green')
plt.axvline(x=mode(districts.UBN_PERCENTAGE,BINNING_VALUE),
color='blue')
plt.legend(handles=tags)
My result is this one:
Where 'Densidad Habitacional' means 'Population Density', and 'Necesidades Básicas Insatisfechas (NBI)' means 'Unsatisfied Basic Needs (UBN)'.
So then, in the first histogram plot shown at the screenshot, the first bar (at the left of all), starts at range 0. However, in the second one, we can see that the first bar doesn't start at 0, but in a greater value instead.
Also, viewing these values, I can also see that there's something wrong: in the second interval we have 60 observations, and in the third one, we have 30. However, at the histogram, we can see that the third bar has a lower height than the half or the second one, since 30 is exactly the half of 60.
I have defined a function which returns me a sequence with the frequency of every interval, and also a sequence with those delimiters, like this:
frequencies: [5.0, 60.0, 30.0, 17.0, 10.0, 11.0, 3.0, 2.0, 2.0, 0.0, 1.0]
delimiters: [0.0, 2.29, 4.57, 6.86, 9.15, 11.44, 13.72, 16.01, 18.3, 20.59, 22.87, 25.16]
Those are the corresponding values to the second histogram shown (UBN Percentage).
I've also used these values returned by that function, to calculate the mode of the variable in another defined function.
My code of these functions is this one:
import pandas as pd
import numpy as np
"""
In the constant 'BINNING_VALUE", we define the quantity of intervals in which we will subdivide
the statistical population (we refer here to the number of records, not to the number of habitants),
to carry out the corresponding analysis.
it just so happens that conveniently, we have a total of 141 records in our database, being such number
a perfect square of 12, so that this value it turns out to us ideal to carry out that binning.
#of intervals will correspond to this value less 1. That's it, if we have 12 delimiters, then we'll have 11 intervals.
As an important issue, this value determines the quantity of interval delimitations, whereby the quantity
""";
BINNING_VALUE=12
"""
This function recives as a parameter in 'column', a column of N observations, (which can be a Pandas Series),
and in 'bins, the quantity of delimitations of class intervals, in which we categorize those observations.
It returns both a list with the class intervals, with their corresponding frequency in each of its elements,
and a list of divisions, which defines the range of each interval.
For example, if recieve have a column of 16 rows, like this:
Index Value
0 15
1 9
2 2
3 5
4 27
5 1
6 7
7 18
8 25
9 1
10 42
11 48
12 37
13 31
14 45
15 33
And then, our bin value is 4, it will return the following sequences:
interval_list: [7,4,5]
ranges_list: [0,16,32,48]
""";
def intervals(column,bins):
#In 'max_value', I'll store the maximum value of the element in the recived column.
max_value=column.max()
#I generate a ranges list (converted from an array with 'tolist' function),
#with a length equal to the bins parameter (quantity of class intervals + 1),
#whose values will go from 0 to the maximum value of the column element, linearly subdivided.
ranges_list=np.linspace(0,max_value,bins).tolist()
#I generate an array with a length equal to the quantity of class intervals (bins -1),
#initially loaded with zeros.
intervals_array=np.zeros(bins-1)
#With a for loop (in which I need the indexes value, starting at position 1), I iterate over
#the ranges list with the 'i' variable, so I can also iterate over the class interval
for i in range(1,bins):
#I declare a variable, which will be reseted to 0 in each iteration of
#the outer loop, in which I'll count the column items located into each range
count_range_elements=0
#With a nested for, I'll iterate over each element of the column
for element in column:
#If the column element value where I'm standing now, lies within the class interval
#which I'm standing in the outer loop
if element > ranges_list[i-1] and element <= ranges_list[i]:
#I increase the element counter
count_range_elements+=1
#Once executed the inner for, I load in position i-1 of my class intervals array,
#the quantity of elements I've counted in the corresponding range
intervals_array[i-1]=count_range_elements
#Once executed both nested for loops, I have now my class intervals array loaded
#with the corresponding values
#I convert my class intervals array into a list
intervals_list=intervals_array.tolist()
#I return a tuple with both the class intervals list and the ranges list
return (intervals_list, ranges_list)
"""
This function recives as a parameter in 'column', a column of N observations, and in 'bins, the quantity of delimitations of class intervals, in which we categorize those observations.
It returns the approximate mode, calculated for such column, according to quantity of class intervlas quantity ('bins' value - 1 ), into we'll bin our data
""";
def mode(column,bins):
#From the 'intervals' function, to which I pass the recived parameters 'column' and 'bins',
#I'm getting the sequences with the needed values to calculate the mode
intervals_list, ranges_list = intervals(column,bins)
#From the intervals list, I'm storing the index to its maximum value.
#This will be the position of our modal class interval (where the mode is found)
ind_max_val = intervals_list.index(max(intervals_list))
#The lower limit of the modal class interval, will be the element of the ranges
#list, whose index is equal to the one correspondent to the maximum element of the
#class intervals list
lower_limit=ranges_list[ind_max_val]
#Values 'a' and 'b' represents:
#a: Difference between the height of the modal interval, and previous interval
#b: Difference between the height of the modal interval, and next interval
#Since these values are calculated based on the position of modal interval, depending if
#this one is located at and extreme of the list, or in the middle of it, we need this values
#outside of the scope of the 'if/else' sentences, so we declarate this variables here, with
#0 as it's initial value.
a=0
b=0
#In the 'c' value, we'll have the amplitude of class modal interval
#(as like any other, since the amplitude is the same for all intervals)
c=ranges_list[ind_max_val+1] - ranges_list[ind_max_val]
#We calculate the 'a' value, depending if the modal interval is at the
#start of the list (at the left of all), or if it doesn't
if ind_max_val > 0:
a=intervals_list[ind_max_val] - intervals_list[ind_max_val-1]
else:
a=intervals_list[ind_max_val]
#We calculate the 'b' value, depending if the modal interval is at the
#end of the list (at the right of all), or if it doesn't
if ind_max_val < (bins-1):
b=intervals_list[ind_max_val] - intervals_list[ind_max_val+1]
else:
b=intervals_list[ind_max_val]
#Once obtained every value needed, we'll apply it in the mode formula,
#and we store the result in a variable
mode= lower_limit + (a/(a+b))*c
#Finally, we return the calculated mode value
return mode
Since I'm not a native english speaker, if someone finds a grammar mistake somewhere, please correct me.
Does anyone have an idea of what should I do?
Thanks a lot!
|
[] |
[] |
[
"I've resolved this issues by setting the 'bins' attribute with the list of class intervals returned by my 'intervals' function, instead of the number of bins, like this:\n#We assign diffent colours for the mean, the median, and the mode (red, green, and blue), for the legend of the graphics plotted\nref_mean = mpatches.Patch(color='red', label='Mean')\nref_median = mpatches.Patch(color='green', label='Median')\nref_mode = mpatches.Patch(color='blue', label='Mode')\ntags=[ref_mean,ref_median,ref_mode]\n\n...\n\nax = sns.displot(data=districts,\n x=\"POPULATION_DENSITY\",\n multiple=\"stack\",\n height=6,\n aspect=2,\n kind='hist', \n bins=intervals(districts.POPULATION_DENSITY,BINNING_VALUE)[1], #Instead of bins=BINNING_VALUE, \n stat='density',\n kde=True).set(title='Density Population Histogram')\n\nax.set(xlabel='Density Population (hab/km´2)', ylabel='Relative quantity of districts')\n\nplt.axvline(x=districts.POPULATION_DENSITY.mean(),\n color='red')\nplt.axvline(x=districts.POPULATION_DENSITY.median(),\n color='green')\nplt.axvline(x=mode(x=districts.POPULATION_DENSITY,BINNING_VALUE),\n color='blue')\n\nplt.legend(handles=tags)\n\nax = sns.displot(data=districts,\n x=\"UBN_PERCENTAGE\",\n multiple=\"stack\",\n height=6,\n aspect=2,\n kind='hist', \n bins=intervals(districts.UBN_PERCENTAGE,BINNING_VALUE)[1], #Instead of bins=BINNING_VALUE, \n stat='density',\n ax=0,\n kde=True).set(title='Percentage of unsatisfied basic needs histogram')\n\nax.set(xlabel='%UBN', ylabel='Relative quantity of districts')\n\n\nplt.axvline(x=districts.UBN_PERCENTAGE.mean(),\n color='red')\nplt.axvline(x=districts.UBN_PERCENTAGE.median(),\n color='green')\nplt.axvline(x=mode(districts.UBN_PERCENTAGE,BINNING_VALUE),\n color='blue')\n\nplt.legend(handles=tags)\n\nSo then, my result is this one:\n\nNow, we can see that the calculated mode value by the function, concides exactly with the graphic method used to find it.\nAs a detail, here's the value of each measure:\nMean: 6.468369\nMedian: 5.000000\nMode: 3.767273\n"
] |
[
-1
] |
[
"jupyter_notebook",
"matplotlib",
"pandas",
"python",
"seaborn"
] |
stackoverflow_0074497202_jupyter_notebook_matplotlib_pandas_python_seaborn.txt
|
Q:
Why isn't my class variable changed for all instances?
I'm learning about classes and don't understand this:
class MyClass:
var = 1
one = MyClass()
two = MyClass()
print(one.var, two.var) # out: 1 1
one.var = 2
print(one.var, two.var) # out: 2 1
I thought that class variables are accessible by all instances, but why doesn't it change for all of them?
A:
It doesn't change for all of them because doing this: one.var = 2, creates a new instance variable
with the same name as the class variable, but only for the instance one.
After that, one will first find its instance variable and return that, while two will only find the class variable and return that.
To change the class variable I suggest two options:
create a class method to change the class variable (my preference)
change it by using the class directly
class MyClass:
var = 1
@classmethod
def change_var(cls, var):
cls.var = var
one = MyClass()
two = MyClass()
print(one.var, two.var) # out: 1 1
one.change_var(2) # option 1
print(one.var, two.var) # out: 2 2
MyClass.var = 3 # option 2
print(one.var, two.var) # out: 3 3
A:
Assignment to an attribute via an instance always creates/updates an instance variable, whether or not a class attribute of the same name exists. To update a class attribute, you must use a reference to the class.
>>> type(one).var = 2
>>> print(one.var, two.var)
2 2
In practice, type(one) might return the wrong class to update a particular class attribute, but also in practice, you don't need to change class attributes when you only have an instance of the class available.
A:
one.var = 2 actually adds the new instance variable var by object but doesn't change the class variable var and after adding the new instance variable var, one.var accesses the new instance variable var as shown below. *If there are the same name class and instance variables, the same name instance variable is prioritized while the same name class variable is ignored when accessed by object:
class MyClass:
var = 1
one = MyClass()
two = MyClass()
print(one.var, two.var)
one.var = 2 # Adds the new instance variable by object
# ↓ Accesses the class variable by object
print(one.var, two.var)
# ↑
# Accesses the new instance variable by object
Output:
1 1
2 1
So, to change the class variable var, you need to use the class name MyClass as shown below:
class MyClass:
var = 1
one = MyClass()
two = MyClass()
print(one.var, two.var)
MyClass.var = 2 # Changes the class variable by the class name
print(one.var, two.var)
Output:
1 1
2 2
And basically, you should use class name to access class variables because you can always access class variables whether or not there are the same name instance variables. So, using class name is safer than using object to access class variables as shown below:
class MyClass:
var = 1
one = MyClass()
two = MyClass()
# Here # Here
print(MyClass.var, MyClass.var)
MyClass.var = 2 # Changes the class variable by the class name
# Here # Here
print(MyClass.var, MyClass.var)
Output:
1 1
2 2
My answer for How to access "static" class variables in Python? explains more about accessing class variables.
|
Why isn't my class variable changed for all instances?
|
I'm learning about classes and don't understand this:
class MyClass:
var = 1
one = MyClass()
two = MyClass()
print(one.var, two.var) # out: 1 1
one.var = 2
print(one.var, two.var) # out: 2 1
I thought that class variables are accessible by all instances, but why doesn't it change for all of them?
|
[
"It doesn't change for all of them because doing this: one.var = 2, creates a new instance variable\nwith the same name as the class variable, but only for the instance one.\nAfter that, one will first find its instance variable and return that, while two will only find the class variable and return that.\nTo change the class variable I suggest two options:\n\ncreate a class method to change the class variable (my preference)\n\nchange it by using the class directly\n\n\nclass MyClass:\n var = 1\n\n @classmethod\n def change_var(cls, var): \n cls.var = var\n\n\none = MyClass()\ntwo = MyClass()\n\nprint(one.var, two.var) # out: 1 1\n\none.change_var(2) # option 1\nprint(one.var, two.var) # out: 2 2\n\nMyClass.var = 3 # option 2\nprint(one.var, two.var) # out: 3 3\n\n",
"Assignment to an attribute via an instance always creates/updates an instance variable, whether or not a class attribute of the same name exists. To update a class attribute, you must use a reference to the class.\n>>> type(one).var = 2\n>>> print(one.var, two.var)\n2 2\n\nIn practice, type(one) might return the wrong class to update a particular class attribute, but also in practice, you don't need to change class attributes when you only have an instance of the class available.\n",
"one.var = 2 actually adds the new instance variable var by object but doesn't change the class variable var and after adding the new instance variable var, one.var accesses the new instance variable var as shown below. *If there are the same name class and instance variables, the same name instance variable is prioritized while the same name class variable is ignored when accessed by object:\nclass MyClass:\n var = 1\n\none = MyClass()\ntwo = MyClass()\n\nprint(one.var, two.var) \none.var = 2 # Adds the new instance variable by object\n # ↓ Accesses the class variable by object \nprint(one.var, two.var)\n # ↑\n # Accesses the new instance variable by object\n\nOutput:\n1 1\n2 1\n\nSo, to change the class variable var, you need to use the class name MyClass as shown below:\nclass MyClass:\n var = 1\n\none = MyClass()\ntwo = MyClass()\n\nprint(one.var, two.var) \nMyClass.var = 2 # Changes the class variable by the class name\n\nprint(one.var, two.var)\n\nOutput:\n1 1\n2 2\n\nAnd basically, you should use class name to access class variables because you can always access class variables whether or not there are the same name instance variables. So, using class name is safer than using object to access class variables as shown below:\nclass MyClass:\n var = 1\n\none = MyClass()\ntwo = MyClass()\n # Here # Here\nprint(MyClass.var, MyClass.var)\nMyClass.var = 2 # Changes the class variable by the class name\n # Here # Here\nprint(MyClass.var, MyClass.var)\n\nOutput:\n1 1\n2 2\n\nMy answer for How to access \"static\" class variables in Python? explains more about accessing class variables.\n"
] |
[
3,
2,
0
] |
[] |
[] |
[
"class",
"class_variables",
"instance",
"python"
] |
stackoverflow_0069856889_class_class_variables_instance_python.txt
|
Q:
Using for loop to create scatterpolar subplot with Plotly
I want to create Scatterpolar (subplot) with Plotly, the plot shows information about 2 players.
Here is my code.
def Polar(Player_data, Selected_Player_data):
data_copy = Selected_Player_data.copy().iloc[0:1,:-3]
# select player
name = data_Sample[data_Sample["Player"] == Player_data]
# select features in data_sample dataset
feature = name[[i for i in data_copy.columns.tolist()]]
data = pd.concat([feature, data_copy])
fig = make_subplots(rows=1, cols=2,specs=[[{"type": "Polar"},{"type": "Polar"}]])
for i in data.columns[1:]:
if max(data[i]) < 50:
fig.add_trace(go.Scatterpolar(
r = [feature[i].values[0]],
theta = [i],
fill = 'toself',
marker_color='rgb(47,138,196)',
name = Player_data),row=1, col=1)
fig.add_trace(go.Scatterpolar(
r = [data_copy[i].values[0]],
theta = [i],
fill = 'toself',
marker_color='rgb(237,100,90)',
name = Selected_Player_data.Player.values[0]),row=1, col=1)
else:
fig.add_trace(go.Scatterpolar(
r = [feature[i].values[0]],
theta = [i],
fill = 'toself',
marker_color='rgb(47,138,196)',
name = Player_data),row=1, col=2)
fig.add_trace(go.Scatterpolar(
r = [data_copy[i].values[0]],
theta = [i],
fill = 'toself',
marker_color='rgb(237,100,90)',
name = Selected_Player_data.Player.values[0]),row=1, col=2)
fig.layout.update(
go.Layout(
polar = dict(
radialaxis = dict(
visible = True,)),
showlegend = True,
height=400, width=1000,
))
return py.iplot(fig)
Polar('J. Sands', data_JSands)
After running this function, I got this.
There are two questions.
Why are there only dots in the plot?
Why are there many legends?
A:
You can change the type of markers by:
fig.update_traces(mode = 'lines') # you can also change it to "markers+lines"
There is a legend for each subplot in the grid. If all legends are the same, you can solve this problem by adding this attribute to all subplots except the last one.
fig.add_trace(go.Scatterpolar(
r = [data_copy[i].values[0]],
theta = [i],
fill = 'toself',
marker_color='rgb(237,100,90)',
showlegend= False, #<--------- Add to all subplots except the last one
name = Selected_Player_data.Player.values[0]),row=1, col=1)
|
Using for loop to create scatterpolar subplot with Plotly
|
I want to create Scatterpolar (subplot) with Plotly, the plot shows information about 2 players.
Here is my code.
def Polar(Player_data, Selected_Player_data):
data_copy = Selected_Player_data.copy().iloc[0:1,:-3]
# select player
name = data_Sample[data_Sample["Player"] == Player_data]
# select features in data_sample dataset
feature = name[[i for i in data_copy.columns.tolist()]]
data = pd.concat([feature, data_copy])
fig = make_subplots(rows=1, cols=2,specs=[[{"type": "Polar"},{"type": "Polar"}]])
for i in data.columns[1:]:
if max(data[i]) < 50:
fig.add_trace(go.Scatterpolar(
r = [feature[i].values[0]],
theta = [i],
fill = 'toself',
marker_color='rgb(47,138,196)',
name = Player_data),row=1, col=1)
fig.add_trace(go.Scatterpolar(
r = [data_copy[i].values[0]],
theta = [i],
fill = 'toself',
marker_color='rgb(237,100,90)',
name = Selected_Player_data.Player.values[0]),row=1, col=1)
else:
fig.add_trace(go.Scatterpolar(
r = [feature[i].values[0]],
theta = [i],
fill = 'toself',
marker_color='rgb(47,138,196)',
name = Player_data),row=1, col=2)
fig.add_trace(go.Scatterpolar(
r = [data_copy[i].values[0]],
theta = [i],
fill = 'toself',
marker_color='rgb(237,100,90)',
name = Selected_Player_data.Player.values[0]),row=1, col=2)
fig.layout.update(
go.Layout(
polar = dict(
radialaxis = dict(
visible = True,)),
showlegend = True,
height=400, width=1000,
))
return py.iplot(fig)
Polar('J. Sands', data_JSands)
After running this function, I got this.
There are two questions.
Why are there only dots in the plot?
Why are there many legends?
|
[
"You can change the type of markers by:\nfig.update_traces(mode = 'lines') # you can also change it to \"markers+lines\"\n\nThere is a legend for each subplot in the grid. If all legends are the same, you can solve this problem by adding this attribute to all subplots except the last one.\nfig.add_trace(go.Scatterpolar(\n r = [data_copy[i].values[0]],\n theta = [i],\n fill = 'toself',\n marker_color='rgb(237,100,90)',\n showlegend= False, #<--------- Add to all subplots except the last one\n name = Selected_Player_data.Player.values[0]),row=1, col=1)\n\n"
] |
[
0
] |
[] |
[] |
[
"plotly",
"python",
"radar_chart",
"scatter_plot",
"visualization"
] |
stackoverflow_0072022040_plotly_python_radar_chart_scatter_plot_visualization.txt
|
Q:
Replace value from a column based on condition of another column, Pandas
Starting DataFrame
df = pd.DataFrame({'Column A' : ['red','green','yellow', 'orange', 'red', 'blue'],
'Column B' : [NaN, 'blue', 'purple', NaN, NaN, NaN],
'Column C' : [1, 2, 3, 2, 3, 7]})
Column A
Column B
Column C
'red'
NaN
1
'green'
'blue'
2
'yellow'
'purple'
3
'orange'
NaN
2
'red'
NaN
3
'blue'
NaN
7
Desired Result
Column A
Column B
Column C
'red'
NaN
1
'blue'
'blue'
2
'purple'
'purple'
3
'orange'
NaN
2
'red'
NaN
3
'blue'
NaN
7
I want to replace values in column A only if the value in Column B is not NaN, and to replace column A with the value in Column B
So that I can run the following code:
df[[Column_A, Column_C]].groupby(Column_A).sum()
Which would result in the following DataFrame:
Column A
Column C
'red'
4
'blue'
9
'purple'
3
'orange'
2
I am trying to replace categories before doing a groupby call.
Attempts:
The DataFrame I am working with has a sequential numerical based index going from 0 to N.
So I could hard code the following:
df.iloc[[index], column] = some_string
I do not want to do this as it is not dynamic and the DataFrame data could change.
I believe I could use .agg() or .apply() on either the df or the df.groupby() but this is where I have struggled.
Particularly with how to write a function to use with .agg() or .apply()
Say:
def my_func(x):
print(x)
Then:
df.apply(my_func)
The result is the first column of df printed.
Or:
df.apply(my_func, axis = 1)
The result is the following format for each row:
Column A red
Column B Nan
Column C 1
Name: 0, dtype: object
Column A green
Column B blue
Column C 2
Name: 1, dtype: object
I am not sure how to access each column per row in my_func.
Edit:
I am trying to find a way to change the value in Column A if the value, for that row, in Column B is not NaN. The value to use for replacing is the value in Column B, the value to replace is the value in Column A if Column B is not NaN.
But I want to do this dynamically, meaning not hardcoded as I showed with:
df.iloc[[index], column] = some_string
A:
As you mentioned, you could use pd.apply like this:
df['Column A'] = df.apply(lambda x: x['Column B'] if str(x['Column B']) not in ['nan', 'NaN'] else x['Column A'], axis=1)
Column A Column B Column C
0 red NaN 1
1 blue blue 2
2 purple purple 3
3 orange NaN 2
4 red NaN 3
5 blue NaN 7
Notice that apply is not fast at for very large dataset is not advisable. There are some good answers out there for alternative methods
|
Replace value from a column based on condition of another column, Pandas
|
Starting DataFrame
df = pd.DataFrame({'Column A' : ['red','green','yellow', 'orange', 'red', 'blue'],
'Column B' : [NaN, 'blue', 'purple', NaN, NaN, NaN],
'Column C' : [1, 2, 3, 2, 3, 7]})
Column A
Column B
Column C
'red'
NaN
1
'green'
'blue'
2
'yellow'
'purple'
3
'orange'
NaN
2
'red'
NaN
3
'blue'
NaN
7
Desired Result
Column A
Column B
Column C
'red'
NaN
1
'blue'
'blue'
2
'purple'
'purple'
3
'orange'
NaN
2
'red'
NaN
3
'blue'
NaN
7
I want to replace values in column A only if the value in Column B is not NaN, and to replace column A with the value in Column B
So that I can run the following code:
df[[Column_A, Column_C]].groupby(Column_A).sum()
Which would result in the following DataFrame:
Column A
Column C
'red'
4
'blue'
9
'purple'
3
'orange'
2
I am trying to replace categories before doing a groupby call.
Attempts:
The DataFrame I am working with has a sequential numerical based index going from 0 to N.
So I could hard code the following:
df.iloc[[index], column] = some_string
I do not want to do this as it is not dynamic and the DataFrame data could change.
I believe I could use .agg() or .apply() on either the df or the df.groupby() but this is where I have struggled.
Particularly with how to write a function to use with .agg() or .apply()
Say:
def my_func(x):
print(x)
Then:
df.apply(my_func)
The result is the first column of df printed.
Or:
df.apply(my_func, axis = 1)
The result is the following format for each row:
Column A red
Column B Nan
Column C 1
Name: 0, dtype: object
Column A green
Column B blue
Column C 2
Name: 1, dtype: object
I am not sure how to access each column per row in my_func.
Edit:
I am trying to find a way to change the value in Column A if the value, for that row, in Column B is not NaN. The value to use for replacing is the value in Column B, the value to replace is the value in Column A if Column B is not NaN.
But I want to do this dynamically, meaning not hardcoded as I showed with:
df.iloc[[index], column] = some_string
|
[
"As you mentioned, you could use pd.apply like this:\ndf['Column A'] = df.apply(lambda x: x['Column B'] if str(x['Column B']) not in ['nan', 'NaN'] else x['Column A'], axis=1)\n\n Column A Column B Column C\n0 red NaN 1\n1 blue blue 2\n2 purple purple 3\n3 orange NaN 2\n4 red NaN 3\n5 blue NaN 7\n\nNotice that apply is not fast at for very large dataset is not advisable. There are some good answers out there for alternative methods\n"
] |
[
0
] |
[] |
[] |
[
"pandas",
"python"
] |
stackoverflow_0074494037_pandas_python.txt
|
Q:
python cv2.error: Unknown C++ exception from OpenCV code
I have this code:
class CamThread(threading.Thread):
def __init__(self, previewname, camid):
threading.Thread.__init__(self)
self.previewname = previewname
self.camid = camid
def run(self):
print("Starting " + self.previewname)
previewcam(self.previewname, self.camid)
# Function to preview the camera.
def previewcam(previewname, camid):
cv2.namedWindow(previewname)
cam = cv2.VideoCapture(camid)
if cam.isOpened():
rval, frame = cam.read()
else:
rval = False
while rval:
cv2.imshow(previewname, frame)
rval, frame = cam.read()
key = cv2.waitKey(20)
if key == 27: # Press ESC to exit/close each window.
break
cv2.destroyWindow(previewname)
when I run my python file, I get this error:
self.run()
File "swann.py", line 17, in run
previewcam(self.previewname, self.camid)
File "swann.py", line 21, in previewcam
cv2.namedWindow(previewname)
cv2.error: Unknown C++ exception from OpenCV code
Assertion failed: (NSViewIsCurrentlyBuildingLayerTreeForDisplay() != currentlyBuildingLayerTree), function NSViewSetCurrentlyBuildingLayerTreeForDisplay, file NSView.m, line 13477.
zsh: illegal hardware instruction
I've never used the cv2 package before, so I'm not sure if I am doing something wrong. Could someone help me out?
A:
This is known issue, see here.
This is macOS specific problem, when cv2 tries to interact with UI in newly spawned thread, it throws this error. Use UI interactions on main thread only.
|
python cv2.error: Unknown C++ exception from OpenCV code
|
I have this code:
class CamThread(threading.Thread):
def __init__(self, previewname, camid):
threading.Thread.__init__(self)
self.previewname = previewname
self.camid = camid
def run(self):
print("Starting " + self.previewname)
previewcam(self.previewname, self.camid)
# Function to preview the camera.
def previewcam(previewname, camid):
cv2.namedWindow(previewname)
cam = cv2.VideoCapture(camid)
if cam.isOpened():
rval, frame = cam.read()
else:
rval = False
while rval:
cv2.imshow(previewname, frame)
rval, frame = cam.read()
key = cv2.waitKey(20)
if key == 27: # Press ESC to exit/close each window.
break
cv2.destroyWindow(previewname)
when I run my python file, I get this error:
self.run()
File "swann.py", line 17, in run
previewcam(self.previewname, self.camid)
File "swann.py", line 21, in previewcam
cv2.namedWindow(previewname)
cv2.error: Unknown C++ exception from OpenCV code
Assertion failed: (NSViewIsCurrentlyBuildingLayerTreeForDisplay() != currentlyBuildingLayerTree), function NSViewSetCurrentlyBuildingLayerTreeForDisplay, file NSView.m, line 13477.
zsh: illegal hardware instruction
I've never used the cv2 package before, so I'm not sure if I am doing something wrong. Could someone help me out?
|
[
"This is known issue, see here.\nThis is macOS specific problem, when cv2 tries to interact with UI in newly spawned thread, it throws this error. Use UI interactions on main thread only.\n"
] |
[
0
] |
[] |
[] |
[
"macos",
"opencv",
"python"
] |
stackoverflow_0074256913_macos_opencv_python.txt
|
Q:
Flask WTForms always give false on validate_on_submit()
I have created a signup form using wtforms. I am using FormField in it so that I don't have to repeat some of the elements of the form again. But whenever I click on the Submit button it always give me false on validate_on_submit method invocation. Not getting why is this happening.
My form.py is as follows:
class ProfileInfoForm(Form):
firstname = TextField('firstname', validators=
[validators.Required("Please enter First name.")])
lastname = TextField('lastname', validators=
[validators.Required("Please enter Last name.")])
email = EmailField('email', validators=
[validators.Required("Please enter your valid email.")])
gender = RadioField('gender', validators=
[validators.Required("Please select gender")],
choices=[('female', 'Female'), ('male', 'Male')])
dob = TextField('dob', validators=
[validators.Required("Please select date of birth.")])
languages = SelectMultipleField('languages', choices=[('', '')],
validators=
[validators.Required("Please select\
atleast one \
language.")])
class RegistrationForm(Form):
profilefield = FormField(ProfileInfoForm)
password = PasswordField('password',
validators=
[validators.Required("Please enter password."),
validators.Length(min=8),
validators.EqualTo('confirm_password',
message='Password and confirm\
password must match')])
confirm_password = PasswordField('confirm_password',
validators=
[validators.Required("Please enter\
confirm password.")])
tnc = BooleanField('tnc', validators=
[validators.Required("Please select Terms and \
Conditions")], default=False)
submit = SubmitField('Create My Account')
Signup method is as follows:
@module.route('/signup', methods=['GET', 'POST'])
@handle_error
def signup():
if hasattr(g, 'user') and g.user:
# TODO: do some operations if needed else keep it blank
return redirect(url_for('index'))
else:
signup_form = RegistrationForm()
# Add choices for the user
signup_form.profilefield.languages.choices = getLanguages()
if signup_form.validate_on_submit():
firstname = signup_form.profilefield.firstname.data
lastname = signup_form.profilefield.lastname.data
email = signup_form.profilefield.email.data
password = signup_form.password.data
# confirm_password = signup_form.confirm_password.data
gender = signup_form.profilefield.gender.data
dob = signup_form.profilefield.dob.data
languages = signup_form.profilefield.languages.data
tnc = signup_form.tnc.data
payload = {'firstname': firstname, 'lastname': lastname,
'email': email, 'password': password, 'gender': gender,
'dob': dob, 'languages': languages,
'tnc': ('1' if tnc else '0')}
try:
buildApiUrl = BuildApiUrl()
response = requests.post(buildApiUrl.getUrl("user", "signup"),
data=payload)
if response.status_code == requests.codes.ok:
data = json.loads(response.text)
if 'status' in data and data['status'] != 200:
flash(data['message'], category="error")
else:
flash(data['message'] +
': Your account is created successfully! ' +
'Please login to your account!',
category="success")
return redirect(url_for('index'))
except requests.exceptions.RequestException:
flash('Internal Server side error occured', category="error")
return redirect(url_for('server_error', e='500'))
return render_template('public/index.html',
signup_form=signup_form, login_form=LoginForm())
HTML form is present on gist here
FYI: I am putting all the required fields with actual data needed. Still getting false when I call validate_on_submit(). What is wrong in my code?
EDIT: getLanguages is a method that retrieves languages from database and put in select list. This functionality is happening as expected and I can get list of languages.
Edit 2: Realize one thing here. This is happening due to FormField, since I tested by adding all the fields of ProfileInfoForm() into RegistrationForm() method, and everything worked just fine and I could signup. So some issue with the FormField or the way I am using it, but not sure where it is going wrong.
Found out that the problem is not with FormField but with my ProfileInfoForm(). It returns false always. Not yet got reason but I think I may have to write my own validation for that matter. Any thoughts?
Edit:
On dump I got following (used pprint here):
{'SECRET_KEY': '1e4c35233e50840483467e8d6cfe556c',
'_errors': None,
'_fields': {'csrf_token': <wtforms.ext.csrf.fields.CSRFTokenField object at 0x2207290>,
'dob': <wtforms.fields.simple.TextField object at 0x2207650>,
'email': <flask_wtf.html5.EmailField object at 0x22074d0>,
'firstname': <wtforms.fields.simple.TextField object at 0x2207350>,
'gender': <wtforms.fields.core.RadioField object at 0x2207590>,
'languages': <wtforms.fields.core.SelectMultipleField object at 0x2207710>,
'lastname': <wtforms.fields.simple.TextField object at 0x2207410>},
'_prefix': u'profilefield-',
'csrf_enabled': True,
'csrf_token': <wtforms.ext.csrf.fields.CSRFTokenField object at 0x2207290>,
'dob': <wtforms.fields.simple.TextField object at 0x2207650>,
'email': <flask_wtf.html5.EmailField object at 0x22074d0>,
'firstname': <wtforms.fields.simple.TextField object at 0x2207350>,
'gender': <wtforms.fields.core.RadioField object at 0x2207590>,
'languages': <wtforms.fields.core.SelectMultipleField object at 0x2207710>,
'lastname': <wtforms.fields.simple.TextField object at 0x2207410>}
Edit:
I dig little bit and found that the error is generated is due to csrf token missing. But I have included {{ signup_form.hidden_tag() }} in my form template in html. and I can see hidden tag in html generated when I do inspect element and can see csrf_token field with hash value. So what is wrong in here?
A:
I solved my problem with the following function:
def __init__(self, *args, **kwargs):
kwargs['csrf_enabled'] = False
super(ProfileInfoForm, self).__init__(*args, **kwargs)
I added this function in ProfileInfoForm()
The issue was FormField includes csrf_token field as well as Actual form, i.e., RegistrationForm was also including csrf_token, so there were two csrf_token which were to be verified and only one was getting rendered actually in form. So, I disabled csrf_token in ProfileInfoForm so when FormField rendered it, it had csrf_token = False.
And RegistrationForm does have csrf_token enabled still now so the form is still safe.
My Guess is this does also required to be done in FormField as well.
FYI: This solution might be wrong due to my interpretation of the FormField code. SO please correct me if I am wrong in above solution.
A:
I had the same issue and I was able to fix it.
The problem was related to the fact that the LoginForm had the id and username with a validators while the html form was not requiring the information
<h1>Login</h1>
<form action="" method="POST" name="login">
{{ login_form.csrf_token }}
{{ login_form.hidden_tag() }}
<p>
{{ login_form.email.label }}<br>
{{ login_form.email(size=64) }}<br>
{% for error in login_form.email.errors %}
<span style="color: red;">[{{ error }}]</span>
{% endfor %}
</p>
<p>
{{ login_form.password.label }}<br>
{{ login_form.password(size=32) }}<br>
{% for error in login_form.password.errors %}
<span style="color: red;">[{{ error }}]</span>
{% endfor %}
</p>
<p>{{ login_form.remember_me }} Remember Me</p>
{# <input type="submit" value="Sign In">#}
<p>{{ login_form.submit() }}</p>
</form>
class LoginForm(FlaskForm):
***# user_id = StringField('user_id',validators=[DataRequired()])
# user_name = StringField('user_name',validators=[DataRequired(), Length(min=3, max=20)])***
email = StringField('Email', validators=[DataRequired(), Email()])
password = PasswordField('Password', validators=[DataRequired()])
remember_me = BooleanField('remember_me', default=False)
submit = SubmitField('LogIn')
A:
Just print csrf_token with jinja and it will return True.
|
Flask WTForms always give false on validate_on_submit()
|
I have created a signup form using wtforms. I am using FormField in it so that I don't have to repeat some of the elements of the form again. But whenever I click on the Submit button it always give me false on validate_on_submit method invocation. Not getting why is this happening.
My form.py is as follows:
class ProfileInfoForm(Form):
firstname = TextField('firstname', validators=
[validators.Required("Please enter First name.")])
lastname = TextField('lastname', validators=
[validators.Required("Please enter Last name.")])
email = EmailField('email', validators=
[validators.Required("Please enter your valid email.")])
gender = RadioField('gender', validators=
[validators.Required("Please select gender")],
choices=[('female', 'Female'), ('male', 'Male')])
dob = TextField('dob', validators=
[validators.Required("Please select date of birth.")])
languages = SelectMultipleField('languages', choices=[('', '')],
validators=
[validators.Required("Please select\
atleast one \
language.")])
class RegistrationForm(Form):
profilefield = FormField(ProfileInfoForm)
password = PasswordField('password',
validators=
[validators.Required("Please enter password."),
validators.Length(min=8),
validators.EqualTo('confirm_password',
message='Password and confirm\
password must match')])
confirm_password = PasswordField('confirm_password',
validators=
[validators.Required("Please enter\
confirm password.")])
tnc = BooleanField('tnc', validators=
[validators.Required("Please select Terms and \
Conditions")], default=False)
submit = SubmitField('Create My Account')
Signup method is as follows:
@module.route('/signup', methods=['GET', 'POST'])
@handle_error
def signup():
if hasattr(g, 'user') and g.user:
# TODO: do some operations if needed else keep it blank
return redirect(url_for('index'))
else:
signup_form = RegistrationForm()
# Add choices for the user
signup_form.profilefield.languages.choices = getLanguages()
if signup_form.validate_on_submit():
firstname = signup_form.profilefield.firstname.data
lastname = signup_form.profilefield.lastname.data
email = signup_form.profilefield.email.data
password = signup_form.password.data
# confirm_password = signup_form.confirm_password.data
gender = signup_form.profilefield.gender.data
dob = signup_form.profilefield.dob.data
languages = signup_form.profilefield.languages.data
tnc = signup_form.tnc.data
payload = {'firstname': firstname, 'lastname': lastname,
'email': email, 'password': password, 'gender': gender,
'dob': dob, 'languages': languages,
'tnc': ('1' if tnc else '0')}
try:
buildApiUrl = BuildApiUrl()
response = requests.post(buildApiUrl.getUrl("user", "signup"),
data=payload)
if response.status_code == requests.codes.ok:
data = json.loads(response.text)
if 'status' in data and data['status'] != 200:
flash(data['message'], category="error")
else:
flash(data['message'] +
': Your account is created successfully! ' +
'Please login to your account!',
category="success")
return redirect(url_for('index'))
except requests.exceptions.RequestException:
flash('Internal Server side error occured', category="error")
return redirect(url_for('server_error', e='500'))
return render_template('public/index.html',
signup_form=signup_form, login_form=LoginForm())
HTML form is present on gist here
FYI: I am putting all the required fields with actual data needed. Still getting false when I call validate_on_submit(). What is wrong in my code?
EDIT: getLanguages is a method that retrieves languages from database and put in select list. This functionality is happening as expected and I can get list of languages.
Edit 2: Realize one thing here. This is happening due to FormField, since I tested by adding all the fields of ProfileInfoForm() into RegistrationForm() method, and everything worked just fine and I could signup. So some issue with the FormField or the way I am using it, but not sure where it is going wrong.
Found out that the problem is not with FormField but with my ProfileInfoForm(). It returns false always. Not yet got reason but I think I may have to write my own validation for that matter. Any thoughts?
Edit:
On dump I got following (used pprint here):
{'SECRET_KEY': '1e4c35233e50840483467e8d6cfe556c',
'_errors': None,
'_fields': {'csrf_token': <wtforms.ext.csrf.fields.CSRFTokenField object at 0x2207290>,
'dob': <wtforms.fields.simple.TextField object at 0x2207650>,
'email': <flask_wtf.html5.EmailField object at 0x22074d0>,
'firstname': <wtforms.fields.simple.TextField object at 0x2207350>,
'gender': <wtforms.fields.core.RadioField object at 0x2207590>,
'languages': <wtforms.fields.core.SelectMultipleField object at 0x2207710>,
'lastname': <wtforms.fields.simple.TextField object at 0x2207410>},
'_prefix': u'profilefield-',
'csrf_enabled': True,
'csrf_token': <wtforms.ext.csrf.fields.CSRFTokenField object at 0x2207290>,
'dob': <wtforms.fields.simple.TextField object at 0x2207650>,
'email': <flask_wtf.html5.EmailField object at 0x22074d0>,
'firstname': <wtforms.fields.simple.TextField object at 0x2207350>,
'gender': <wtforms.fields.core.RadioField object at 0x2207590>,
'languages': <wtforms.fields.core.SelectMultipleField object at 0x2207710>,
'lastname': <wtforms.fields.simple.TextField object at 0x2207410>}
Edit:
I dig little bit and found that the error is generated is due to csrf token missing. But I have included {{ signup_form.hidden_tag() }} in my form template in html. and I can see hidden tag in html generated when I do inspect element and can see csrf_token field with hash value. So what is wrong in here?
|
[
"I solved my problem with the following function:\ndef __init__(self, *args, **kwargs):\n kwargs['csrf_enabled'] = False\n super(ProfileInfoForm, self).__init__(*args, **kwargs)\n\nI added this function in ProfileInfoForm()\nThe issue was FormField includes csrf_token field as well as Actual form, i.e., RegistrationForm was also including csrf_token, so there were two csrf_token which were to be verified and only one was getting rendered actually in form. So, I disabled csrf_token in ProfileInfoForm so when FormField rendered it, it had csrf_token = False.\nAnd RegistrationForm does have csrf_token enabled still now so the form is still safe.\nMy Guess is this does also required to be done in FormField as well. \nFYI: This solution might be wrong due to my interpretation of the FormField code. SO please correct me if I am wrong in above solution.\n",
"I had the same issue and I was able to fix it.\nThe problem was related to the fact that the LoginForm had the id and username with a validators while the html form was not requiring the information\n <h1>Login</h1>\n\n <form action=\"\" method=\"POST\" name=\"login\">\n {{ login_form.csrf_token }}\n {{ login_form.hidden_tag() }}\n\n <p>\n {{ login_form.email.label }}<br>\n {{ login_form.email(size=64) }}<br>\n {% for error in login_form.email.errors %}\n <span style=\"color: red;\">[{{ error }}]</span>\n {% endfor %}\n </p>\n <p>\n {{ login_form.password.label }}<br>\n {{ login_form.password(size=32) }}<br>\n {% for error in login_form.password.errors %}\n <span style=\"color: red;\">[{{ error }}]</span>\n {% endfor %}\n </p>\n <p>{{ login_form.remember_me }} Remember Me</p>\n{# <input type=\"submit\" value=\"Sign In\">#}\n <p>{{ login_form.submit() }}</p>\n </form>\n\n\n\nclass LoginForm(FlaskForm):\n ***# user_id = StringField('user_id',validators=[DataRequired()])\n # user_name = StringField('user_name',validators=[DataRequired(), Length(min=3, max=20)])***\n email = StringField('Email', validators=[DataRequired(), Email()])\n password = PasswordField('Password', validators=[DataRequired()])\n remember_me = BooleanField('remember_me', default=False)\n submit = SubmitField('LogIn')\n\n",
"Just print csrf_token with jinja and it will return True.\n"
] |
[
5,
0,
0
] |
[] |
[] |
[
"flask",
"flask_wtforms",
"python",
"wtforms"
] |
stackoverflow_0018716920_flask_flask_wtforms_python_wtforms.txt
|
Q:
I don't have the option to fold code anymore in vscode in python
Recently I discovered that the little arrow next to lines in vscode, that allows you to fold parts of the code, had disappeared. I then noticed this was the case only in my Python files.
I scoped the internet looking for an answer, but nothing worked
I'v tried fixing the setting (by checking that the "folding" setting in the settings UI was ticked) but it did nothing, I tried removing the last extensions I had installed to see if they were interfering or something, but no.
Thanks for the info on #region, but even that doesn't allow me to fold the code. I've tried with the command "fold" from the command palette and with 'Ctrl+Shift+[' and 'Ctrl+Shift+]' but it didn't work
I'm on Arch Linux using VsCode-OSS btw
A:
Sort of expanding on the other answer, I've worked around it by changing settings for my python-specific workspace and changing the "Folding Strategy" to "indentation" instead of "auto", which seems to be a perfect workaround (for me at least) since Python requires proper indentation anyway and this doesn't mess with global settings
image of the settings in question
I'm experiencing the exact same issue in VSCode on Windows (which is how I found this question) - only Python code folding seems to be broken, C++ etc seems to be fine, never noticed it happening before so I think a recent update broke it
A:
Search folding in settings, and then check the first one.
You can also use the following code to test whether it is valid
# region
# endregion
For example:
# region hi
print("HelloWorld")
# endregion
A:
If none of other answers helps you, you can create your custom folding range using Ctrl+K Ctrl+, on windows (I hope smth like that is in linux also, try searching folding range). Selected lines willbe folded. To delete folding region, use Ctrl+K Ctrl+..
|
I don't have the option to fold code anymore in vscode in python
|
Recently I discovered that the little arrow next to lines in vscode, that allows you to fold parts of the code, had disappeared. I then noticed this was the case only in my Python files.
I scoped the internet looking for an answer, but nothing worked
I'v tried fixing the setting (by checking that the "folding" setting in the settings UI was ticked) but it did nothing, I tried removing the last extensions I had installed to see if they were interfering or something, but no.
Thanks for the info on #region, but even that doesn't allow me to fold the code. I've tried with the command "fold" from the command palette and with 'Ctrl+Shift+[' and 'Ctrl+Shift+]' but it didn't work
I'm on Arch Linux using VsCode-OSS btw
|
[
"Sort of expanding on the other answer, I've worked around it by changing settings for my python-specific workspace and changing the \"Folding Strategy\" to \"indentation\" instead of \"auto\", which seems to be a perfect workaround (for me at least) since Python requires proper indentation anyway and this doesn't mess with global settings\nimage of the settings in question\nI'm experiencing the exact same issue in VSCode on Windows (which is how I found this question) - only Python code folding seems to be broken, C++ etc seems to be fine, never noticed it happening before so I think a recent update broke it\n",
"\nSearch folding in settings, and then check the first one.\nYou can also use the following code to test whether it is valid\n# region\n\n# endregion\n\nFor example:\n# region hi\nprint(\"HelloWorld\")\n# endregion\n\n",
"If none of other answers helps you, you can create your custom folding range using Ctrl+K Ctrl+, on windows (I hope smth like that is in linux also, try searching folding range). Selected lines willbe folded. To delete folding region, use Ctrl+K Ctrl+..\n"
] |
[
1,
0,
0
] |
[] |
[] |
[
"code_folding",
"python",
"visual_studio_code"
] |
stackoverflow_0074117813_code_folding_python_visual_studio_code.txt
|
Q:
Loading data from dict with nested dicts and lists flattened or as many-to-many tables to sql
To simplify, I have a list as follows:
lst = [
{
“person_id”: HZT998, “name”: ‘john’, “skills”: [‘python’, ‘sql’, ‘r’],
“extras”: {“likes_swimming”: False, “likes_cooking”: True}},
{
“person_id”: HTY954, “name”: ‘peter, “skills”: [‘python’, ‘r’, ‘c#’],
“extras”: {“likes_swimming”: True, “likes_cooking”: False}}
]
And I want to insert them to SQL tables as follows:
People table:
person_inner_id (PK)
person_id
name
likes_swimming
likes_cooking
1
HZT998
john
False
True
2
HTY954
peter
True
False
Skills table:
skill_id (PK)
skill
1
python
2
sql
3
r
4
c#
Skills_People table
person_inner_id (FK)
skill_id (FK)
1
1
1
2
1
3
2
1
2
3
2
4
So I want to flatten the inner dictionaries (insert them as columns), and the lists organize in a different table and create a relationship table. Also I dont want to use the 'person_id' column as my primary key because I feel its bad for data integrity to use an outside ID as the primary key. However this makes it much harder to implement using python, and I am not sure how to do so.
I will also need to keep making these calls and inserting their output to the relevant tables.
I first tried dumping the entire original list into json with the open method:
with open("data.json", "w") as fp:
json.dump(lst, fp)
and then I tried importing that json straight into sql through the mysql workbench table import wizard. This was successful in importing a general schema but not in inserting data, im guessing because of the nested dictionaries and lists that mysql doesn't know how to handle.
Thank you!
A:
Assuming that the key values in the list "lst" (e.g. "person_id" etc.) are always present, you just need to modify the complex list into normalized lists for this 3 pieces of tables:
lst = [
{
"person_id": "HZT998", "name": "john", "skills": ["python", "sql", "r"], "extras": {"likes_swimming": False, "likes_cooking": True}
},
{
"person_id": "HTY954", "name": "peter", "skills": ["python", "r", "c#"], "extras": {"likes_swimming": True, "likes_cooking": False}
}
]
data_for_first_table = [] # saves each user dictonary without 'skills'
data_dict_first_table = {} # user-dictonary-instance without 'skills'
data_for_second_table = [] # save each 'skill' separately
data_for_third_table = [] # save each skill-user dictonary matches
data_dict_third_table = {} # skill-user-dictonary-instance
######################################
# modify complex List for SQL-Qeruies
######################################
for entry in lst:
for key in entry:
if key == "skills":
for skills in entry[key]:
#print(skills)
data_for_second_table.append(skills)
# Third Table - "Match Table"
data_dict_third_table[skills] = entry["person_id"]
elif key == "extras":
for extra in entry[key]:
#print(extra + ": " + str(entry[key][extra]))
data_dict_first_table[extra] = entry[key][extra]
else:
#print(key + ": " + entry[key])
data_dict_first_table[key] = entry[key]
# store user-dictonary-instance without 'skills'
dict_copy = data_dict_first_table.copy()
data_for_first_table.append(dict_copy)
# store skill-user-dictonary-instance
dict_copy = data_dict_third_table.copy()
data_for_third_table.append(dict_copy)
### remove duplicates from 2nd list ###
data_for_second_table = list(dict.fromkeys(data_for_second_table))
print("####### TEST1 #########")
print(data_for_first_table)
print("####### TEST2 #########")
print(data_for_second_table)
print("####### TEST3 #########")
print(data_for_third_table)
... and to avoid duplicate data-entries (e.g. if you get the same file twice) set People.person_id and Skills.skill to primary-key.
Then you just need to make your SQL-queries:
######################
# Create SQL-Queries
######################
print("/* #### SQL-TEST #### */")
# INSERT(S)/UPDATE(S) for "Peaople"-Table
for entry in data_for_first_table:
raw_sql1 = "INSERT INTO People ( " + str([k for k in entry]).replace("[","").replace("]","").replace("'","") + " ) VALUES ( " + str([str(entry[k]) for k in entry]).replace("[","").replace("]","") + " ) ON DUPLICATE KEY UPDATE " + str([ k + " = " + str(entry[k]) for k in entry if k != 'person_id'] ).replace("[","").replace("]","").replace("'","").replace("= ","= '").replace(",","',") + "';"
print(raw_sql1)
# ONLY INSERT(S) for "Skills"-Table
for entry in data_for_second_table:
raw_sql2 = "INSERT IGNORE INTO Skills ( skill ) VALUES ( '" + entry + "' );"
print(raw_sql2)
# ONLY INSERT(S) for "Skills_People"-Table
for entry in data_for_third_table:
for multiple_entry in entry:
raw_sql3= "INSERT IGNORE INTO Skills_People ( person_id, skill_id ) VALUES ( '" + entry[multiple_entry] + "', '" + multiple_entry + "' );"
print(raw_sql3)
Note: This only works if the table-column-names exactly match the list-key-names.
In addition, the keys and values (Type = 'CHAR') were modified with simple Python-string-operations ".replace()" so that a valid SQL query is generated.
/* #### SQL-TEST #### */
INSERT INTO People ( person_id, name, likes_swimming, likes_cooking ) VALUES ( 'HZT998', 'john', 'False', 'True' ) ON DUPLICATE KEY UPDATE name = 'john', likes_swimming = 'False', likes_cooking = 'True';
INSERT INTO People ( person_id, name, likes_swimming, likes_cooking ) VALUES ( 'HTY954', 'peter', 'True', 'False' ) ON DUPLICATE KEY UPDATE name = 'peter', likes_swimming = 'True', likes_cooking = 'False';
INSERT IGNORE INTO Skills ( skill ) VALUES ( 'python' );
INSERT IGNORE INTO Skills ( skill ) VALUES ( 'sql' );
INSERT IGNORE INTO Skills ( skill ) VALUES ( 'r' );
INSERT IGNORE INTO Skills ( skill ) VALUES ( 'c#' );
INSERT IGNORE INTO Skills_People ( person_id, skill_id ) VALUES ( 'HZT998', 'python' );
INSERT IGNORE INTO Skills_People ( person_id, skill_id ) VALUES ( 'HZT998', 'sql' );
INSERT IGNORE INTO Skills_People ( person_id, skill_id ) VALUES ( 'HZT998', 'r' );
INSERT IGNORE INTO Skills_People ( person_id, skill_id ) VALUES ( 'HTY954', 'python' );
INSERT IGNORE INTO Skills_People ( person_id, skill_id ) VALUES ( 'HZT998', 'sql' );
INSERT IGNORE INTO Skills_People ( person_id, skill_id ) VALUES ( 'HTY954', 'r' );
INSERT IGNORE INTO Skills_People ( person_id, skill_id ) VALUES ( 'HTY954', 'c#' );
|
Loading data from dict with nested dicts and lists flattened or as many-to-many tables to sql
|
To simplify, I have a list as follows:
lst = [
{
“person_id”: HZT998, “name”: ‘john’, “skills”: [‘python’, ‘sql’, ‘r’],
“extras”: {“likes_swimming”: False, “likes_cooking”: True}},
{
“person_id”: HTY954, “name”: ‘peter, “skills”: [‘python’, ‘r’, ‘c#’],
“extras”: {“likes_swimming”: True, “likes_cooking”: False}}
]
And I want to insert them to SQL tables as follows:
People table:
person_inner_id (PK)
person_id
name
likes_swimming
likes_cooking
1
HZT998
john
False
True
2
HTY954
peter
True
False
Skills table:
skill_id (PK)
skill
1
python
2
sql
3
r
4
c#
Skills_People table
person_inner_id (FK)
skill_id (FK)
1
1
1
2
1
3
2
1
2
3
2
4
So I want to flatten the inner dictionaries (insert them as columns), and the lists organize in a different table and create a relationship table. Also I dont want to use the 'person_id' column as my primary key because I feel its bad for data integrity to use an outside ID as the primary key. However this makes it much harder to implement using python, and I am not sure how to do so.
I will also need to keep making these calls and inserting their output to the relevant tables.
I first tried dumping the entire original list into json with the open method:
with open("data.json", "w") as fp:
json.dump(lst, fp)
and then I tried importing that json straight into sql through the mysql workbench table import wizard. This was successful in importing a general schema but not in inserting data, im guessing because of the nested dictionaries and lists that mysql doesn't know how to handle.
Thank you!
|
[
"Assuming that the key values in the list \"lst\" (e.g. \"person_id\" etc.) are always present, you just need to modify the complex list into normalized lists for this 3 pieces of tables:\nlst = [ \n {\n \"person_id\": \"HZT998\", \"name\": \"john\", \"skills\": [\"python\", \"sql\", \"r\"], \"extras\": {\"likes_swimming\": False, \"likes_cooking\": True}\n }, \n {\n \"person_id\": \"HTY954\", \"name\": \"peter\", \"skills\": [\"python\", \"r\", \"c#\"], \"extras\": {\"likes_swimming\": True, \"likes_cooking\": False}\n } \n ]\n\ndata_for_first_table = [] # saves each user dictonary without 'skills'\ndata_dict_first_table = {} # user-dictonary-instance without 'skills'\ndata_for_second_table = [] # save each 'skill' separately\ndata_for_third_table = [] # save each skill-user dictonary matches\ndata_dict_third_table = {} # skill-user-dictonary-instance\n\n\n######################################\n# modify complex List for SQL-Qeruies\n######################################\nfor entry in lst:\n for key in entry:\n if key == \"skills\":\n for skills in entry[key]:\n #print(skills)\n data_for_second_table.append(skills)\n # Third Table - \"Match Table\"\n data_dict_third_table[skills] = entry[\"person_id\"]\n elif key == \"extras\":\n for extra in entry[key]:\n #print(extra + \": \" + str(entry[key][extra]))\n data_dict_first_table[extra] = entry[key][extra] \n else:\n #print(key + \": \" + entry[key])\n data_dict_first_table[key] = entry[key]\n \n # store user-dictonary-instance without 'skills'\n dict_copy = data_dict_first_table.copy()\n data_for_first_table.append(dict_copy)\n # store skill-user-dictonary-instance\n dict_copy = data_dict_third_table.copy()\n data_for_third_table.append(dict_copy)\n \n\n### remove duplicates from 2nd list ###\ndata_for_second_table = list(dict.fromkeys(data_for_second_table))\n \nprint(\"####### TEST1 #########\")\nprint(data_for_first_table)\nprint(\"####### TEST2 #########\")\nprint(data_for_second_table)\nprint(\"####### TEST3 #########\")\nprint(data_for_third_table)\n\n... and to avoid duplicate data-entries (e.g. if you get the same file twice) set People.person_id and Skills.skill to primary-key.\nThen you just need to make your SQL-queries:\n######################\n# Create SQL-Queries\n######################\nprint(\"/* #### SQL-TEST #### */\")\n# INSERT(S)/UPDATE(S) for \"Peaople\"-Table\nfor entry in data_for_first_table:\n raw_sql1 = \"INSERT INTO People ( \" + str([k for k in entry]).replace(\"[\",\"\").replace(\"]\",\"\").replace(\"'\",\"\") + \" ) VALUES ( \" + str([str(entry[k]) for k in entry]).replace(\"[\",\"\").replace(\"]\",\"\") + \" ) ON DUPLICATE KEY UPDATE \" + str([ k + \" = \" + str(entry[k]) for k in entry if k != 'person_id'] ).replace(\"[\",\"\").replace(\"]\",\"\").replace(\"'\",\"\").replace(\"= \",\"= '\").replace(\",\",\"',\") + \"';\"\n print(raw_sql1)\n\n# ONLY INSERT(S) for \"Skills\"-Table\nfor entry in data_for_second_table:\n raw_sql2 = \"INSERT IGNORE INTO Skills ( skill ) VALUES ( '\" + entry + \"' );\"\n print(raw_sql2)\n\n# ONLY INSERT(S) for \"Skills_People\"-Table \nfor entry in data_for_third_table:\n for multiple_entry in entry:\n raw_sql3= \"INSERT IGNORE INTO Skills_People ( person_id, skill_id ) VALUES ( '\" + entry[multiple_entry] + \"', '\" + multiple_entry + \"' );\"\n print(raw_sql3)\n\nNote: This only works if the table-column-names exactly match the list-key-names.\nIn addition, the keys and values (Type = 'CHAR') were modified with simple Python-string-operations \".replace()\" so that a valid SQL query is generated.\n/* #### SQL-TEST #### */\nINSERT INTO People ( person_id, name, likes_swimming, likes_cooking ) VALUES ( 'HZT998', 'john', 'False', 'True' ) ON DUPLICATE KEY UPDATE name = 'john', likes_swimming = 'False', likes_cooking = 'True';\nINSERT INTO People ( person_id, name, likes_swimming, likes_cooking ) VALUES ( 'HTY954', 'peter', 'True', 'False' ) ON DUPLICATE KEY UPDATE name = 'peter', likes_swimming = 'True', likes_cooking = 'False';\nINSERT IGNORE INTO Skills ( skill ) VALUES ( 'python' );\nINSERT IGNORE INTO Skills ( skill ) VALUES ( 'sql' );\nINSERT IGNORE INTO Skills ( skill ) VALUES ( 'r' );\nINSERT IGNORE INTO Skills ( skill ) VALUES ( 'c#' );\nINSERT IGNORE INTO Skills_People ( person_id, skill_id ) VALUES ( 'HZT998', 'python' );\nINSERT IGNORE INTO Skills_People ( person_id, skill_id ) VALUES ( 'HZT998', 'sql' );\nINSERT IGNORE INTO Skills_People ( person_id, skill_id ) VALUES ( 'HZT998', 'r' );\nINSERT IGNORE INTO Skills_People ( person_id, skill_id ) VALUES ( 'HTY954', 'python' );\nINSERT IGNORE INTO Skills_People ( person_id, skill_id ) VALUES ( 'HZT998', 'sql' );\nINSERT IGNORE INTO Skills_People ( person_id, skill_id ) VALUES ( 'HTY954', 'r' );\nINSERT IGNORE INTO Skills_People ( person_id, skill_id ) VALUES ( 'HTY954', 'c#' );\n\n"
] |
[
0
] |
[] |
[] |
[
"python",
"relational_database",
"sql"
] |
stackoverflow_0074498778_python_relational_database_sql.txt
|
Q:
Flask validate_on_submit always False
I know that there are similar problems which have been answered. The csrf_enabled is not an issue now if the Form inheriting FlaskForm, and the template has the form.hidden_tag().
I have the following flask app.
## Filenname: app.py
from flask import Flask, render_template, redirect, url_for, flash, request
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, SelectField
from wtforms.validators import DataRequired
app = Flask(__name__)
app.config["SECRET_KEY"] = "secret"
class DataForm(FlaskForm):
name = StringField("Name", validators=[DataRequired()])
gender = SelectField("Gender", validators=None, choices=[(1, 'M'), (2, "F")])
submit = SubmitField("Submit", validators=None)
@app.route('/index', methods=["GET", "POST"])
def index():
form = DataForm(request.form)
print(form.validate_on_submit())
if form.validate_on_submit():
print(form.validate())
print(form.name)
flash("THIS IS FLASH")
title="hello"
return redirect(url_for('output'))
return render_template('index.html', form=form)
@app.route('/output', methods=["GET", "POST"])
def output():
title = "hello"
form = DataForm()
print(form.validate())
return render_template('output.html', title=title)
app.run(debug=False)
The following is index.html template:
<html>
<body>
{% with messages = get_flashed_messages() %}
{{ messages }}
{% endwith %}
<form action="" method="GET">
{{ form.hidden_tag() }}
{{ form.name.label }}
{{ form.name() }}
{% for error in form.name.errors %}
<span style="color: red;">[{{ error }}]</span>
{% endfor %}
<hr>
{{ form.gender.label }}
{{ form.gender() }}
{{ form.submit() }}
</form>
</body>
</html>
After clicking the submit button the execution never goes in the if form.validate_on_submit() block in the index function.
I also removed all the validators, the code inside validate_on_submit block is still unreachable. Printing form.validate_on_submit() is always false.
A:
So there are multiple problems.
Change your choices to strings:
choices=[('1', 'M'), ('2', "F")]
Change your form method to POST, because validate_on_submit() requires it:
<form action="" method="POST">
Additionally, to debug other possible errors (like CSRF), add this to your template:
{% if form.errors %}
{{ form.errors }}
{% endif %}
That fixed your code for me.
A:
just make form without
2.form = FlaskForm(meta={'csrf': False})
A:
Just print csrf_token with jinja and it will return True.
<form method="POST" action="#">
{{ form.csrf_token }}
</form>
|
Flask validate_on_submit always False
|
I know that there are similar problems which have been answered. The csrf_enabled is not an issue now if the Form inheriting FlaskForm, and the template has the form.hidden_tag().
I have the following flask app.
## Filenname: app.py
from flask import Flask, render_template, redirect, url_for, flash, request
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, SelectField
from wtforms.validators import DataRequired
app = Flask(__name__)
app.config["SECRET_KEY"] = "secret"
class DataForm(FlaskForm):
name = StringField("Name", validators=[DataRequired()])
gender = SelectField("Gender", validators=None, choices=[(1, 'M'), (2, "F")])
submit = SubmitField("Submit", validators=None)
@app.route('/index', methods=["GET", "POST"])
def index():
form = DataForm(request.form)
print(form.validate_on_submit())
if form.validate_on_submit():
print(form.validate())
print(form.name)
flash("THIS IS FLASH")
title="hello"
return redirect(url_for('output'))
return render_template('index.html', form=form)
@app.route('/output', methods=["GET", "POST"])
def output():
title = "hello"
form = DataForm()
print(form.validate())
return render_template('output.html', title=title)
app.run(debug=False)
The following is index.html template:
<html>
<body>
{% with messages = get_flashed_messages() %}
{{ messages }}
{% endwith %}
<form action="" method="GET">
{{ form.hidden_tag() }}
{{ form.name.label }}
{{ form.name() }}
{% for error in form.name.errors %}
<span style="color: red;">[{{ error }}]</span>
{% endfor %}
<hr>
{{ form.gender.label }}
{{ form.gender() }}
{{ form.submit() }}
</form>
</body>
</html>
After clicking the submit button the execution never goes in the if form.validate_on_submit() block in the index function.
I also removed all the validators, the code inside validate_on_submit block is still unreachable. Printing form.validate_on_submit() is always false.
|
[
"So there are multiple problems.\n\nChange your choices to strings:\nchoices=[('1', 'M'), ('2', \"F\")]\n\nChange your form method to POST, because validate_on_submit() requires it:\n<form action=\"\" method=\"POST\">\n\nAdditionally, to debug other possible errors (like CSRF), add this to your template: \n{% if form.errors %}\n{{ form.errors }}\n{% endif %}\n\n\nThat fixed your code for me.\n",
"\njust make form without\n\n2.form = FlaskForm(meta={'csrf': False})\n",
"Just print csrf_token with jinja and it will return True.\n<form method=\"POST\" action=\"#\">\n {{ form.csrf_token }}\n</form>\n\n"
] |
[
10,
0,
0
] |
[] |
[] |
[
"flask",
"jinja2",
"python"
] |
stackoverflow_0048455689_flask_jinja2_python.txt
|
Q:
Get certain date index values in a dataframe based on conditions met
python newb here.
I have a CSV with Date and Prices. The date is the index column.
I have a dataframe called data, with a column called 'Buy' which has only True and False values.
I want a column showing the associated indexed date only if True values.
I tried the following code:
data['Result'] = numpy.where(data['Buy'] == True, data.index, 0)
But I get the message: "The DType <class 'numpy.dtype[datetime64]'> could not be promoted by <class 'numpy.dtype[int64]'>. This means that no common DType exists for the given inputs. For example they cannot be stored in a single array unless the dtype is object."
Any idea how to resolve and keep the data['Result'] in date format? (since I need to do further calculations on the dates).
A:
The problem is that you are trying to assign both integer and datetime values to a column. Pandas cannot decide which type this column is. Therefore, you should combine them in a common data type:
data['Result'] = numpy.where(data['Buy'] == True, data.index.astype(str), 0)
#Result dtype: object
if you want to datetime column you can use pd.NaT instead of 0:
data['Result'] = numpy.where(data['Buy'] == True, data.index.astype(str), pd.NaT)
|
Get certain date index values in a dataframe based on conditions met
|
python newb here.
I have a CSV with Date and Prices. The date is the index column.
I have a dataframe called data, with a column called 'Buy' which has only True and False values.
I want a column showing the associated indexed date only if True values.
I tried the following code:
data['Result'] = numpy.where(data['Buy'] == True, data.index, 0)
But I get the message: "The DType <class 'numpy.dtype[datetime64]'> could not be promoted by <class 'numpy.dtype[int64]'>. This means that no common DType exists for the given inputs. For example they cannot be stored in a single array unless the dtype is object."
Any idea how to resolve and keep the data['Result'] in date format? (since I need to do further calculations on the dates).
|
[
"The problem is that you are trying to assign both integer and datetime values to a column. Pandas cannot decide which type this column is. Therefore, you should combine them in a common data type:\ndata['Result'] = numpy.where(data['Buy'] == True, data.index.astype(str), 0)\n#Result dtype: object\n\nif you want to datetime column you can use pd.NaT instead of 0:\ndata['Result'] = numpy.where(data['Buy'] == True, data.index.astype(str), pd.NaT)\n\n"
] |
[
0
] |
[] |
[] |
[
"date",
"indexing",
"python"
] |
stackoverflow_0074498549_date_indexing_python.txt
|
Q:
Selenium python hidden element cant be clicked unless hovered over
I want to create a program that will automatically host a krunker map when i run it but to host it the program has to click a button which only shows up if u hover over the map and i dont know how to do that with selenium (ps im gonna set the server to private and i dont think i can just do that with a link and i dont wanna use any code that moves the mouse like pyautogui. If there is a better way to host a pivate custom map (with password) please share.
driver = uc.Chrome()
driver.get('https://krunker.io')
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@id='onetrust-accept-btn-handler']"))).click()
WebDriverWait(driver, 30).until(EC.element_to_be_clickable((By.XPATH, "//div[@id='menuBtnHost' and contains(., 'Host Game')]"))).click()
WebDriverWait(driver, 30).until(EC.element_to_be_clickable((By.XPATH, "//div[@id='menuWindow' and contains(., 'Custom')]"))).click()
WebDriverWait(driver, 30).until(EC.element_to_be_clickable((By.XPATH, "//div[@id='hostCMapPickr']"))).click()
WebDriverWait(driver, 30).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='bigMenTab' and contains(., 'search')]"))).click()
WebDriverWait(driver, 30).until(EC.element_to_be_clickable((By.XPATH, "//div[@id='mapList']"))).click()
mapname = driver.find_element(By.ID,"mpSrch")
mapname.send_keys('Zombie_Bulwark')
mapname.send_keys(Keys.ENTER);
<<<what must i do here to click the button?
WebDriverWait(driver, 30).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='mapActionB']"))).click() <<<button i wanna click
A:
Update
There is a way to simulate the mousehover in selenium
You can try the following
import undetected_chromedriver as uc # pip install undetected-chromedriver
from selenium.webdriver.common.action_chains import ActionChains
driver = uc.Chrome()
mapp = driver.find_element(By.XPATH, 'put the map xpath here')
mousehover = ActionChains(driver)
mousehover.move_to_element(mapp)
mousehover.perform()
# your mouse click
# WebDriverWait(driver, 30).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='mapActionB']"))).click()
|
Selenium python hidden element cant be clicked unless hovered over
|
I want to create a program that will automatically host a krunker map when i run it but to host it the program has to click a button which only shows up if u hover over the map and i dont know how to do that with selenium (ps im gonna set the server to private and i dont think i can just do that with a link and i dont wanna use any code that moves the mouse like pyautogui. If there is a better way to host a pivate custom map (with password) please share.
driver = uc.Chrome()
driver.get('https://krunker.io')
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@id='onetrust-accept-btn-handler']"))).click()
WebDriverWait(driver, 30).until(EC.element_to_be_clickable((By.XPATH, "//div[@id='menuBtnHost' and contains(., 'Host Game')]"))).click()
WebDriverWait(driver, 30).until(EC.element_to_be_clickable((By.XPATH, "//div[@id='menuWindow' and contains(., 'Custom')]"))).click()
WebDriverWait(driver, 30).until(EC.element_to_be_clickable((By.XPATH, "//div[@id='hostCMapPickr']"))).click()
WebDriverWait(driver, 30).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='bigMenTab' and contains(., 'search')]"))).click()
WebDriverWait(driver, 30).until(EC.element_to_be_clickable((By.XPATH, "//div[@id='mapList']"))).click()
mapname = driver.find_element(By.ID,"mpSrch")
mapname.send_keys('Zombie_Bulwark')
mapname.send_keys(Keys.ENTER);
<<<what must i do here to click the button?
WebDriverWait(driver, 30).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='mapActionB']"))).click() <<<button i wanna click
|
[
"Update\nThere is a way to simulate the mousehover in selenium\nYou can try the following\nimport undetected_chromedriver as uc # pip install undetected-chromedriver\nfrom selenium.webdriver.common.action_chains import ActionChains\n\ndriver = uc.Chrome()\n\nmapp = driver.find_element(By.XPATH, 'put the map xpath here')\nmousehover = ActionChains(driver)\nmousehover.move_to_element(mapp)\nmousehover.perform()\n\n# your mouse click\n# WebDriverWait(driver, 30).until(EC.element_to_be_clickable((By.XPATH, \"//div[@class='mapActionB']\"))).click() \n\n"
] |
[
0
] |
[] |
[] |
[
"python",
"selenium_webdriver"
] |
stackoverflow_0074500532_python_selenium_webdriver.txt
|
Q:
How can I save the username in the database as an email?>
I want a signup page with 3 fields (email, password and repeat password). My goal is that when the user enters the email address, it is also saved in the database as a username. I would be super happy if someone could help me, I've been sitting for x hours trying to solve this problem. Thanks very much!
model.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
email_confirmed = models.BooleanField(default=False)
@receiver(post_save, sender=User)
def update_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
instance.profile.save()
forms.py
class CreateUserForm(UserCreationForm):
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
# Sign Up Form
class SignUpForm(UserCreationForm):
# first_name = forms.CharField(max_length=30, required=False, help_text='Optional')
# last_name = forms.CharField(max_length=30, required=False, help_text='Optional')
email = forms.EmailField(max_length=254, help_text='Enter a valid email address')
class Meta:
model = User
fields = [
'username',
'password1',
'password2',
]
views.py
from django.contrib import messages
from django.contrib.auth.models import Group
from django.contrib.sites.shortcuts import get_current_site
from django.utils.encoding import force_bytes
from django.utils.http import urlsafe_base64_encode
from django.template.loader import render_to_string
from .token import AccountActivationTokenGenerator, account_activation_token
from django.shortcuts import render, redirect
from .forms import *
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth import get_user_model, login
from django.utils.http import urlsafe_base64_decode
from django.views.generic import View, UpdateView
from django.contrib.auth.decorators import login_required
from .decorators import *
from django.urls import reverse_lazy
from django.utils.encoding import force_str
@unauthenticatedUser
def Example_login(request):
if request.method == 'POST':
email = request.POST.get('email')
password = request.POST.get('password')
user = authenticate(request, username=email, password=password)
if user is not None:
login(request, user)
return redirect('Example_dashboard')
else:
messages.info(request, 'Username OR password is incorrecct')
context = {}
return render(request, 'accounds/templates/Example_login.html', context)
def reset_passwrd(request):
return render(request, "reset_password.html")
@login_required(login_url='login')
def Example_dashboard(request):
form = MembersForm()
current_user = request.user
name = current_user.username.split(".")[0]
context = {'form': form, "cunrrent_user": name}
return render(request, 'example_dashboard.html', context)
def Login(request):
if request.method == 'POST':
email = request.POST.get('Benutzername')
password = request.POST.get('Passwort')
user = authenticate(request, username=email, password=password)
if user is not None:
login(request, user)
return redirect('Example_dashboard')
else:
messages.info(request, 'Username OR password is incorrecct')
return render(request, "login.html")
def logoutUser(request):
logout(request)
return redirect('login')
def registrierung(request):
return render(request, "registrierung.html")
@unauthenticatedUser
def Example_register(request):
form = CreateUserForm()
if request.method == 'POST':
form = CreateUserForm(request.POST)
if form.is_valid():
user = form.save()
#username = form.cleaned_data.get('usernname')
group = Group.objects.get(name='studends')
user.groups.add(group)
messages.success(request, 'Account was created' )
return redirect('login')
contex = {'form' : form}
return render(request, 'exampl_register.html',contex)
# Sign Up View
class SignUpView(View):
form_class = SignUpForm
template_name = 'signup.html'
def get(self, request, *args, **kwargs):
form = self.form_class()
return render(request, self.template_name, {'form': form})
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
if form.is_valid():
user = form.save(commit=False)
user.is_active = False # Deactivate account till it is confirmed
user.save()
current_site = get_current_site(request)
subject = 'Activate Your MySite Account'
message = render_to_string('account_activation_email.html', {
'user': user,
'domain': current_site.domain,
'uid': urlsafe_base64_encode(force_bytes(user.pk)),
'token': account_activation_token.make_token(user),
})
user.email_user(subject, message)
messages.success(request, ('Please Confirm your email to complete registration.'))
return redirect('login')
return render(request, self.template_name, {'form': form})
class ActivateAccount(View):
def get(self, request, uidb64, token, *args, **kwargs):
try:
uid = force_str(urlsafe_base64_decode(uidb64))
user = User.objects.get(pk=uid)
except (TypeError, ValueError, OverflowError, User.DoesNotExist):
user = None
if user is not None and account_activation_token.check_token(user, token):
user.is_active = True
user.profile.email_confirmed = True
user.save()
login(request, user)
messages.success(request, ('Your account have been confirmed.'))
return redirect('login')
else:
messages.warning(request, ('The confirmation link was invalid, possibly because it has already been used.'))
return redirect('login')
I Need your help
A:
If you want to use email instead of the default username, you have to overwrite the default User model with the custom one
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin
class User(AbstractBaseUser, PermissionsMixin):
# Use the email for logging in
email = models.EmailField(max_length=254, unique=True)
USERNAME_FIELD = 'email'
|
How can I save the username in the database as an email?>
|
I want a signup page with 3 fields (email, password and repeat password). My goal is that when the user enters the email address, it is also saved in the database as a username. I would be super happy if someone could help me, I've been sitting for x hours trying to solve this problem. Thanks very much!
model.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
email_confirmed = models.BooleanField(default=False)
@receiver(post_save, sender=User)
def update_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
instance.profile.save()
forms.py
class CreateUserForm(UserCreationForm):
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
# Sign Up Form
class SignUpForm(UserCreationForm):
# first_name = forms.CharField(max_length=30, required=False, help_text='Optional')
# last_name = forms.CharField(max_length=30, required=False, help_text='Optional')
email = forms.EmailField(max_length=254, help_text='Enter a valid email address')
class Meta:
model = User
fields = [
'username',
'password1',
'password2',
]
views.py
from django.contrib import messages
from django.contrib.auth.models import Group
from django.contrib.sites.shortcuts import get_current_site
from django.utils.encoding import force_bytes
from django.utils.http import urlsafe_base64_encode
from django.template.loader import render_to_string
from .token import AccountActivationTokenGenerator, account_activation_token
from django.shortcuts import render, redirect
from .forms import *
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth import get_user_model, login
from django.utils.http import urlsafe_base64_decode
from django.views.generic import View, UpdateView
from django.contrib.auth.decorators import login_required
from .decorators import *
from django.urls import reverse_lazy
from django.utils.encoding import force_str
@unauthenticatedUser
def Example_login(request):
if request.method == 'POST':
email = request.POST.get('email')
password = request.POST.get('password')
user = authenticate(request, username=email, password=password)
if user is not None:
login(request, user)
return redirect('Example_dashboard')
else:
messages.info(request, 'Username OR password is incorrecct')
context = {}
return render(request, 'accounds/templates/Example_login.html', context)
def reset_passwrd(request):
return render(request, "reset_password.html")
@login_required(login_url='login')
def Example_dashboard(request):
form = MembersForm()
current_user = request.user
name = current_user.username.split(".")[0]
context = {'form': form, "cunrrent_user": name}
return render(request, 'example_dashboard.html', context)
def Login(request):
if request.method == 'POST':
email = request.POST.get('Benutzername')
password = request.POST.get('Passwort')
user = authenticate(request, username=email, password=password)
if user is not None:
login(request, user)
return redirect('Example_dashboard')
else:
messages.info(request, 'Username OR password is incorrecct')
return render(request, "login.html")
def logoutUser(request):
logout(request)
return redirect('login')
def registrierung(request):
return render(request, "registrierung.html")
@unauthenticatedUser
def Example_register(request):
form = CreateUserForm()
if request.method == 'POST':
form = CreateUserForm(request.POST)
if form.is_valid():
user = form.save()
#username = form.cleaned_data.get('usernname')
group = Group.objects.get(name='studends')
user.groups.add(group)
messages.success(request, 'Account was created' )
return redirect('login')
contex = {'form' : form}
return render(request, 'exampl_register.html',contex)
# Sign Up View
class SignUpView(View):
form_class = SignUpForm
template_name = 'signup.html'
def get(self, request, *args, **kwargs):
form = self.form_class()
return render(request, self.template_name, {'form': form})
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
if form.is_valid():
user = form.save(commit=False)
user.is_active = False # Deactivate account till it is confirmed
user.save()
current_site = get_current_site(request)
subject = 'Activate Your MySite Account'
message = render_to_string('account_activation_email.html', {
'user': user,
'domain': current_site.domain,
'uid': urlsafe_base64_encode(force_bytes(user.pk)),
'token': account_activation_token.make_token(user),
})
user.email_user(subject, message)
messages.success(request, ('Please Confirm your email to complete registration.'))
return redirect('login')
return render(request, self.template_name, {'form': form})
class ActivateAccount(View):
def get(self, request, uidb64, token, *args, **kwargs):
try:
uid = force_str(urlsafe_base64_decode(uidb64))
user = User.objects.get(pk=uid)
except (TypeError, ValueError, OverflowError, User.DoesNotExist):
user = None
if user is not None and account_activation_token.check_token(user, token):
user.is_active = True
user.profile.email_confirmed = True
user.save()
login(request, user)
messages.success(request, ('Your account have been confirmed.'))
return redirect('login')
else:
messages.warning(request, ('The confirmation link was invalid, possibly because it has already been used.'))
return redirect('login')
I Need your help
|
[
"If you want to use email instead of the default username, you have to overwrite the default User model with the custom one\n\nfrom django.contrib.auth.models import AbstractBaseUser, PermissionsMixin\n\nclass User(AbstractBaseUser, PermissionsMixin):\n # Use the email for logging in\n email = models.EmailField(max_length=254, unique=True)\n\n USERNAME_FIELD = 'email'\n\n"
] |
[
0
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0074500695_django_python.txt
|
Q:
How are range and len being used in for loops
I just want to know what is going on in this program
sum = 0 #setting sum to 0
for i in range(len(m)):
for j in range(len(m[i])):
if i <= j:
sum = sum + m[i][j]
return sum
print((sum_above_diagonal([[6, 2, 0, 6, 1], [6, 8, 2, 5, 8], [0, 6, 3, 2, 3]])))
I understand the first part, but I am confused on the 'for i in range (len())' stuff.
A:
Imagine you have this array:
arr = [[0,1,2],[9,8,7]]
The first for will run 2 times because len(arr)=2 and the second for will run 3 times because len(arr[0])=3
A:
Pseudocode might help:
Start with counting the sum from zero
For each number i between zero and the number of rows in the matrix, do this:
For each number j between zero and the number of columns in row i, do this:
If i is equal to, or larger than, j, do this:
Add the value of this cell (i, j) to the sum, and save the new sum
And then we return the sum when we are done
So, this will, as the function name suggests, sum the number above and on the diagonal of the matrix you give to it. The matrix is a list of lists.
Edit:
len(thing) gives you the length of the thing
range(N) generates integers between 0 and N-1
So these combined gives you integers between 0 and the length of something minus one.
A:
That range(len(X)) combo is indeed a bit unusual, you can also use Python's builtin enumerate and write something like so:
for i, _ in enumerate(X):
...
|
How are range and len being used in for loops
|
I just want to know what is going on in this program
sum = 0 #setting sum to 0
for i in range(len(m)):
for j in range(len(m[i])):
if i <= j:
sum = sum + m[i][j]
return sum
print((sum_above_diagonal([[6, 2, 0, 6, 1], [6, 8, 2, 5, 8], [0, 6, 3, 2, 3]])))
I understand the first part, but I am confused on the 'for i in range (len())' stuff.
|
[
"Imagine you have this array:\narr = [[0,1,2],[9,8,7]]\n\nThe first for will run 2 times because len(arr)=2 and the second for will run 3 times because len(arr[0])=3\n",
"Pseudocode might help:\nStart with counting the sum from zero\nFor each number i between zero and the number of rows in the matrix, do this:\n For each number j between zero and the number of columns in row i, do this:\n If i is equal to, or larger than, j, do this:\n Add the value of this cell (i, j) to the sum, and save the new sum \n\nAnd then we return the sum when we are done\n\nSo, this will, as the function name suggests, sum the number above and on the diagonal of the matrix you give to it. The matrix is a list of lists.\nEdit:\nlen(thing) gives you the length of the thing\nrange(N) generates integers between 0 and N-1\nSo these combined gives you integers between 0 and the length of something minus one.\n",
"That range(len(X)) combo is indeed a bit unusual, you can also use Python's builtin enumerate and write something like so:\nfor i, _ in enumerate(X):\n ...\n\n"
] |
[
0,
0,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0074500511_python.txt
|
Q:
Grouping values in a clustered pie chart
I'm working with a dataset about when certain houses were constructed and my data stretches from the year 1873-2018(143 slices). I'm trying to visualise this data in the form of a piechart but because of the large number of indivdual slices the entire pie chart appears clustered and messy.
What I'm trying to implement to get aroud this is by grouping the values in 15-year time periods and displaying the periods on the pie chart instead. I seen a similiar post on StackOverflow where the suggested solution was using a dictionary and defining a threshold to group the values but implementing a version of that on my own piechart didn't work and I was wondering how I could tackle this problem
CODE
testing = df1.groupby("Year Built").size()
testing.plot.pie(autopct="%.2f",figsize=(10,10))
plt.ylabel(None)
plt.show()
Dataframe(testing)
Current Piechart
A:
For the future, always provide a reproducible example of the data you are working on (maybe use df.head().to_dict()). One solution to your problem could be achieved by using pd.resample.
# Data Used
df = pd.DataFrame( {'year':np.arange(1890, 2018), 'built':np.random.randint(1,150, size=(2018-1890))} )
>>> df.head()
year built
0 1890 34
1 1891 70
2 1892 92
3 1893 135
4 1894 16
# First, convert your 'year' values into DateTime values and set it as the index
df['year'] = pd.to_datetime(df['year'], format=('%Y'))
df_to_plot = df.set_index('year', drop=True).resample('15Y').sum()
>>> df_to_plot
built
year
1890-12-31 34
1905-12-31 983
1920-12-31 875
1935-12-31 1336
1950-12-31 1221
1965-12-31 1135
1980-12-31 1207
1995-12-31 1168
2010-12-31 1189
2025-12-31 757
Also you could use pd.cut()
df['group'] = pd.cut(df['year'], 15, precision=0)
df.groupby('group')[['year']].sum().plot(kind='pie', subplots=True, figsize=(10,10), legend=False)
|
Grouping values in a clustered pie chart
|
I'm working with a dataset about when certain houses were constructed and my data stretches from the year 1873-2018(143 slices). I'm trying to visualise this data in the form of a piechart but because of the large number of indivdual slices the entire pie chart appears clustered and messy.
What I'm trying to implement to get aroud this is by grouping the values in 15-year time periods and displaying the periods on the pie chart instead. I seen a similiar post on StackOverflow where the suggested solution was using a dictionary and defining a threshold to group the values but implementing a version of that on my own piechart didn't work and I was wondering how I could tackle this problem
CODE
testing = df1.groupby("Year Built").size()
testing.plot.pie(autopct="%.2f",figsize=(10,10))
plt.ylabel(None)
plt.show()
Dataframe(testing)
Current Piechart
|
[
"For the future, always provide a reproducible example of the data you are working on (maybe use df.head().to_dict()). One solution to your problem could be achieved by using pd.resample.\n# Data Used\ndf = pd.DataFrame( {'year':np.arange(1890, 2018), 'built':np.random.randint(1,150, size=(2018-1890))} )\n>>> df.head()\n year built\n0 1890 34\n1 1891 70\n2 1892 92\n3 1893 135\n4 1894 16\n\n# First, convert your 'year' values into DateTime values and set it as the index\n\ndf['year'] = pd.to_datetime(df['year'], format=('%Y'))\n\ndf_to_plot = df.set_index('year', drop=True).resample('15Y').sum()\n\n>>> df_to_plot\n\n built\nyear \n1890-12-31 34\n1905-12-31 983\n1920-12-31 875\n1935-12-31 1336\n1950-12-31 1221\n1965-12-31 1135\n1980-12-31 1207\n1995-12-31 1168\n2010-12-31 1189\n2025-12-31 757\n\nAlso you could use pd.cut()\ndf['group'] = pd.cut(df['year'], 15, precision=0)\n\ndf.groupby('group')[['year']].sum().plot(kind='pie', subplots=True, figsize=(10,10), legend=False)\n\n"
] |
[
0
] |
[] |
[] |
[
"dataframe",
"graph",
"pandas",
"pie_chart",
"python"
] |
stackoverflow_0074491126_dataframe_graph_pandas_pie_chart_python.txt
|
Q:
Trying to read a config file in order to connect to twitter API
I am brand new at all of this and I am completely lost even after Googling, watching hours of youtube videos, and reading posts on this site for the past week.
I am using Jupyter notebook
I have a config file with my api keys it is called config.ipynb
I have a different file where I am trying to call?? (I am not sure if this is the correct terminology) my config file so that I can connect to the twitter API but I getting an attribute error
Here is my code
import numpy as np
import pandas as pd
import tweepy as tw
import configparser
#Read info from the config file named config.ipynb
config = configparser.ConfigParser()
config.read(config.ipynb)
api_key = config[twitter][API_key]
print(api_key) #to test if I did this correctly`
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Cell In [17], line 4
1 #Read info from the config file named config.ipynb
3 config = configparser.ConfigParser()
----> 4 config.read(config.ipynb)
5 api_key = config[twitter][API_key]
AttributeError: 'ConfigParser' object has no attribute 'ipynb'
Thank you for your help
I corrected my mistake thank you.
After fixing my read() mistake I received a MissingSectionHeaderError.
MissingSectionHeaderError: File contains no section headers.
file: 'config.ipynb', line: 1 '{\n'.
My header in my config file is [twitter] but that gives me a NameError and say [twitter] is not defined... I have updated this many times per readings but I always get the same error.
My config.ipynb file code is below:
['twitter']
API_key = "" #key between the ""
API_secret = "" #key between the ""
Bearer_token = "" #key between the ""
Client_ID = "" #key between the ""
Client_Secret = "" #key between the ""
I have tried [twitter], ['twitter'], and ["twitter"] but all render a MissingSectionHeaderError:
Update - I have been able to call my config file and pull in my
keys. After doing so, I am being told I cannot authenticate.
Code below:
import tweepy
import configparser
import os
# Define file path and make sure path is correct
file_name = "config.txt"
# Config file stored in the same directory as the script.
# Get currect working directory with os.getcwd()
file_path = os.path.join(os.getcwd(), file_name)
#print(file_path) # Confirm file path is correct.
File path is correct
# Read info from the config file named config.txt
config = configparser.ConfigParser()
config.read(file_path)
# Will raise KeyError if the file path is not correct
api_key = config["twitter"]["API_key"]
api_secret = config["twitter"]["API_secret"]
client_id = config["twitter"]["Client_ID"]
client_secret = config["twitter"]["Client_Secret"]
#print(api_key, api_secret, client_id, client_secret)
Prints all keys and they are correct
#authentication
from tweepy.auth import OAuthHandler
auth = OAuthHandler("API_key", "API_secret")
auth.set_client_token = (client_id, client_secret)
api = tweepy.API(auth)
public_tweets = api.home_timeline() #all code above works,
this is the line that renders an error
print(public_tweets)
This is the error message I receive:
Unauthorized Traceback (most
recent call last)
Cell In [61], line 9
5 auth.set_client_token = (client_id, client_secret)
7 api = tweepy.API(auth)
----> 9 public_tweets = api.home_timeline()
11 print(public_tweets)
File ~/opt/miniconda3/lib/python3.9/site-
packages/tweepy/api.py:33, in pagination.<locals>.decorator.
<locals>.wrapper(*args, **kwargs)
31 @functools.wraps(method)
32 def wrapper(*args, **kwargs):
---> 33 return method(*args, **kwargs)
File ~/opt/miniconda3/lib/python3.9/site-
packages/tweepy/api.py:46, in payload.<locals>.decorator.
<locals>.wrapper(*args, **kwargs)
44 kwargs['payload_list'] = payload_list
45 kwargs['payload_type'] = payload_type
---> 46 return method(*args, **kwargs)
File ~/opt/miniconda3/lib/python3.9/site-
packages/tweepy/api.py:494, in API.home_timeline(self,
**kwargs)
461 @pagination(mode='id')
462 @payload('status', list=True)
463 def home_timeline(self, **kwargs):
464 """home_timeline(*, count, since_id, max_id,
trim_user,
\
465 exclude_replies, include_entities)
466
(...)
492 https://developer.twitter.com/en/docs/twitter-
api/v1/tweets/timelines/api-reference/get-statuses-
home_timeline
493 """
--> 494 return self.request(
495 'GET', 'statuses/home_timeline',
endpoint_parameters=(
496 'count', 'since_id', 'max_id', 'trim_user',
'exclude_replies',
497 'include_entities'
498 ), **kwargs
499 )
File ~/opt/miniconda3/lib/python3.9/site-
packages/tweepy/api.py:263, in API.request(self, method,
endpoint, endpoint_parameters, params, headers,
json_payload,
parser, payload_list, payload_type, post_data, files,
require_auth, return_cursors, upload_api, use_cache,
**kwargs)
261 raise BadRequest(resp)
262 if resp.status_code == 401:
--> 263 raise Unauthorized(resp)
264 if resp.status_code == 403:
265 raise Forbidden(resp)
Unauthorized: 401 Unauthorized
32 - Could not authenticate you.
I am not sure why it is saying that it cannot authenticate me.
I only have one set of keys and one twitter dev account
Twitter states the following for a 401 error:
401
Unauthorized
V1.1 V2
There was a problem authenticating your request. This could be
due to missing or incorrect authentication credentials. This
may also be returned in other undefined circumstances.
Check that you are using the correct authentication method and
that your credentials are correct. The link provided no longer works and I don't know what I am doing to check my authentication methods and credentials are correct (I only have the one set of credentials so I am thinking that it is my authentication method...maybe??)
A:
You are using the read() method incorrectly, the input should be a string of the filename, so if your filename is config.ipynb then you need to set the method to
config.read('config.ipynb')
A:
Per your last comment in Brance's answer, this is probably related to your file path. If your file path is not correct, configparser will raise a KeyError or NameError.
Tested and working in Jupyter:
Note that no quotation marks such as "twitter" are used
# stackoverflow.txt
[twitter]
API_key = 6556456fghhgf
API_secret = afsdfsdf45435
import configparser
import os
# Define file path and make sure path is correct
file_name = "stackoverflow.txt"
# Config file stored in the same directory as the script.
# Get currect working directory with os.getcwd()
file_path = os.path.join(os.getcwd(), file_name)
print(file_path) # Confirm file path is correct.
# Read info from the config file named stackoverflow.txt
config = configparser.ConfigParser()
config.read(file_path)
# Will raise KeyError if the file path is not correct
api_key = config["twitter"]["API_key"]
print(api_key)
|
Trying to read a config file in order to connect to twitter API
|
I am brand new at all of this and I am completely lost even after Googling, watching hours of youtube videos, and reading posts on this site for the past week.
I am using Jupyter notebook
I have a config file with my api keys it is called config.ipynb
I have a different file where I am trying to call?? (I am not sure if this is the correct terminology) my config file so that I can connect to the twitter API but I getting an attribute error
Here is my code
import numpy as np
import pandas as pd
import tweepy as tw
import configparser
#Read info from the config file named config.ipynb
config = configparser.ConfigParser()
config.read(config.ipynb)
api_key = config[twitter][API_key]
print(api_key) #to test if I did this correctly`
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Cell In [17], line 4
1 #Read info from the config file named config.ipynb
3 config = configparser.ConfigParser()
----> 4 config.read(config.ipynb)
5 api_key = config[twitter][API_key]
AttributeError: 'ConfigParser' object has no attribute 'ipynb'
Thank you for your help
I corrected my mistake thank you.
After fixing my read() mistake I received a MissingSectionHeaderError.
MissingSectionHeaderError: File contains no section headers.
file: 'config.ipynb', line: 1 '{\n'.
My header in my config file is [twitter] but that gives me a NameError and say [twitter] is not defined... I have updated this many times per readings but I always get the same error.
My config.ipynb file code is below:
['twitter']
API_key = "" #key between the ""
API_secret = "" #key between the ""
Bearer_token = "" #key between the ""
Client_ID = "" #key between the ""
Client_Secret = "" #key between the ""
I have tried [twitter], ['twitter'], and ["twitter"] but all render a MissingSectionHeaderError:
Update - I have been able to call my config file and pull in my
keys. After doing so, I am being told I cannot authenticate.
Code below:
import tweepy
import configparser
import os
# Define file path and make sure path is correct
file_name = "config.txt"
# Config file stored in the same directory as the script.
# Get currect working directory with os.getcwd()
file_path = os.path.join(os.getcwd(), file_name)
#print(file_path) # Confirm file path is correct.
File path is correct
# Read info from the config file named config.txt
config = configparser.ConfigParser()
config.read(file_path)
# Will raise KeyError if the file path is not correct
api_key = config["twitter"]["API_key"]
api_secret = config["twitter"]["API_secret"]
client_id = config["twitter"]["Client_ID"]
client_secret = config["twitter"]["Client_Secret"]
#print(api_key, api_secret, client_id, client_secret)
Prints all keys and they are correct
#authentication
from tweepy.auth import OAuthHandler
auth = OAuthHandler("API_key", "API_secret")
auth.set_client_token = (client_id, client_secret)
api = tweepy.API(auth)
public_tweets = api.home_timeline() #all code above works,
this is the line that renders an error
print(public_tweets)
This is the error message I receive:
Unauthorized Traceback (most
recent call last)
Cell In [61], line 9
5 auth.set_client_token = (client_id, client_secret)
7 api = tweepy.API(auth)
----> 9 public_tweets = api.home_timeline()
11 print(public_tweets)
File ~/opt/miniconda3/lib/python3.9/site-
packages/tweepy/api.py:33, in pagination.<locals>.decorator.
<locals>.wrapper(*args, **kwargs)
31 @functools.wraps(method)
32 def wrapper(*args, **kwargs):
---> 33 return method(*args, **kwargs)
File ~/opt/miniconda3/lib/python3.9/site-
packages/tweepy/api.py:46, in payload.<locals>.decorator.
<locals>.wrapper(*args, **kwargs)
44 kwargs['payload_list'] = payload_list
45 kwargs['payload_type'] = payload_type
---> 46 return method(*args, **kwargs)
File ~/opt/miniconda3/lib/python3.9/site-
packages/tweepy/api.py:494, in API.home_timeline(self,
**kwargs)
461 @pagination(mode='id')
462 @payload('status', list=True)
463 def home_timeline(self, **kwargs):
464 """home_timeline(*, count, since_id, max_id,
trim_user,
\
465 exclude_replies, include_entities)
466
(...)
492 https://developer.twitter.com/en/docs/twitter-
api/v1/tweets/timelines/api-reference/get-statuses-
home_timeline
493 """
--> 494 return self.request(
495 'GET', 'statuses/home_timeline',
endpoint_parameters=(
496 'count', 'since_id', 'max_id', 'trim_user',
'exclude_replies',
497 'include_entities'
498 ), **kwargs
499 )
File ~/opt/miniconda3/lib/python3.9/site-
packages/tweepy/api.py:263, in API.request(self, method,
endpoint, endpoint_parameters, params, headers,
json_payload,
parser, payload_list, payload_type, post_data, files,
require_auth, return_cursors, upload_api, use_cache,
**kwargs)
261 raise BadRequest(resp)
262 if resp.status_code == 401:
--> 263 raise Unauthorized(resp)
264 if resp.status_code == 403:
265 raise Forbidden(resp)
Unauthorized: 401 Unauthorized
32 - Could not authenticate you.
I am not sure why it is saying that it cannot authenticate me.
I only have one set of keys and one twitter dev account
Twitter states the following for a 401 error:
401
Unauthorized
V1.1 V2
There was a problem authenticating your request. This could be
due to missing or incorrect authentication credentials. This
may also be returned in other undefined circumstances.
Check that you are using the correct authentication method and
that your credentials are correct. The link provided no longer works and I don't know what I am doing to check my authentication methods and credentials are correct (I only have the one set of credentials so I am thinking that it is my authentication method...maybe??)
|
[
"You are using the read() method incorrectly, the input should be a string of the filename, so if your filename is config.ipynb then you need to set the method to\nconfig.read('config.ipynb')\n\n",
"Per your last comment in Brance's answer, this is probably related to your file path. If your file path is not correct, configparser will raise a KeyError or NameError.\nTested and working in Jupyter:\n\nNote that no quotation marks such as \"twitter\" are used\n\n# stackoverflow.txt\n[twitter]\nAPI_key = 6556456fghhgf\nAPI_secret = afsdfsdf45435\n\nimport configparser\nimport os\n\n# Define file path and make sure path is correct\nfile_name = \"stackoverflow.txt\"\n\n# Config file stored in the same directory as the script.\n# Get currect working directory with os.getcwd()\nfile_path = os.path.join(os.getcwd(), file_name)\n\nprint(file_path) # Confirm file path is correct.\n\n# Read info from the config file named stackoverflow.txt\nconfig = configparser.ConfigParser()\nconfig.read(file_path)\n\n# Will raise KeyError if the file path is not correct\napi_key = config[\"twitter\"][\"API_key\"]\nprint(api_key)\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"attributeerror",
"configuration_files",
"python"
] |
stackoverflow_0074499103_attributeerror_configuration_files_python.txt
|
Q:
Dense Rank changes the partition to 1 which is taking long time to save the df
I want to map string column to int:
st_id a
a 23
b 34
c 45
b 56
a 5
Expected Output:
st_id a st_id_int
a 23 1
b 34 2
c 45 3
b 56 2
a 5 1
So I used dense_rank() and row_number() to get that:
df = df.selectExpr('st_id', 'a', 'row_number() over (order by st_id) as st_id_int')
But this func changes partiton to just 1, which is creating problem while saving file as whole stage is just splitting into 1 task. I even tried to repartion later while saving file but still that stage is just getting split into 1 task.
Can someone provide the alternative way to map string to int or how can I tackle repartition problem.
Can
A:
If I understand your problem correctly, you want to index your string column with repeated hash value. If so, then you can use StringIndexer:
import pyspark.sql.functions as F
from pyspark.ml.feature import StringIndexer
df = spark.createDataFrame(data=[["a",23],["b",34],["c",45],["b",56],["a",5]], schema=["st_id", "a"])
indexer = StringIndexer(inputCol="st_id", outputCol="st_id_int")
df = indexer.fit(df).transform(df).withColumn("st_id_int", F.col("st_id_int").cast("int"))
[Out]:
+-----+---+---------+
|st_id|a |st_id_int|
+-----+---+---------+
|a |23 |0 |
|b |34 |1 |
|c |45 |2 |
|b |56 |1 |
|a |5 |0 |
+-----+---+---------+
It returns zero based index, though; but you can add an additional step to increment it by one, if required.
|
Dense Rank changes the partition to 1 which is taking long time to save the df
|
I want to map string column to int:
st_id a
a 23
b 34
c 45
b 56
a 5
Expected Output:
st_id a st_id_int
a 23 1
b 34 2
c 45 3
b 56 2
a 5 1
So I used dense_rank() and row_number() to get that:
df = df.selectExpr('st_id', 'a', 'row_number() over (order by st_id) as st_id_int')
But this func changes partiton to just 1, which is creating problem while saving file as whole stage is just splitting into 1 task. I even tried to repartion later while saving file but still that stage is just getting split into 1 task.
Can someone provide the alternative way to map string to int or how can I tackle repartition problem.
Can
|
[
"If I understand your problem correctly, you want to index your string column with repeated hash value. If so, then you can use StringIndexer:\nimport pyspark.sql.functions as F\nfrom pyspark.ml.feature import StringIndexer\n\ndf = spark.createDataFrame(data=[[\"a\",23],[\"b\",34],[\"c\",45],[\"b\",56],[\"a\",5]], schema=[\"st_id\", \"a\"])\n\nindexer = StringIndexer(inputCol=\"st_id\", outputCol=\"st_id_int\")\ndf = indexer.fit(df).transform(df).withColumn(\"st_id_int\", F.col(\"st_id_int\").cast(\"int\"))\n\n[Out]:\n+-----+---+---------+\n|st_id|a |st_id_int|\n+-----+---+---------+\n|a |23 |0 |\n|b |34 |1 |\n|c |45 |2 |\n|b |56 |1 |\n|a |5 |0 |\n+-----+---+---------+\n\nIt returns zero based index, though; but you can add an additional step to increment it by one, if required.\n"
] |
[
0
] |
[] |
[] |
[
"apache_spark",
"dense_rank",
"pyspark",
"python"
] |
stackoverflow_0074494465_apache_spark_dense_rank_pyspark_python.txt
|
Q:
Remove subplot matplotlib margin
I would like to fit several subplot inside an A4 figure.
With this code I have unwanted white gap. How can I remove them (see figure). Thanks
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
gs1 = gridspec.GridSpec(8, 2)
gs1.update(wspace=0.025, hspace=0.05) # set the spacing between axes.
plt.figure(figsize=(11.69,8.27)) # for landscape
colors=['c','m','y','k','b','g','r','w']
for i in range(16):
ax = plt.subplot(gs1[i])
ax.set_xticklabels([])
ax.set_yticklabels([])
ax.tick_params(left = False, bottom = False)
ax.set_facecolor(colors[i%8])
plt.savefig("toto.png")
A:
import matplotlib.pyplot as plt
gridspec_kw = {'wspace':0.025, 'hspace':0.05}
fig, ax = plt.subplots(8, 2,
figsize=(11.69,8.27),
gridspec_kw=gridspec_kw,
layout="constrained")
colors = ['c', 'm', 'y', 'k', 'b', 'g', 'r', 'w']
for i in range(8):
# left subplot
ax[i, 0].set_xticklabels([])
ax[i, 0].set_yticklabels([])
ax[i, 0].tick_params(left=False, bottom=False)
ax[i, 0].set_facecolor(colors[(2*i)%8])
# right subplot
ax[i, 1].set_xticklabels([])
ax[i, 1].set_yticklabels([])
ax[i, 1].tick_params(left=False, bottom=False)
ax[i, 1].set_facecolor(colors[(2*i)%8+1])
plt.savefig("toto_stack_overflow.png")
A:
There is another way that doesn't involve restructuring/splitting your plot:
fig = plt.figure(figsize=(11.69,8.27)) # for landscape
fig.subplots_adjust(bottom=0, top=1, left=0, right=1)
|
Remove subplot matplotlib margin
|
I would like to fit several subplot inside an A4 figure.
With this code I have unwanted white gap. How can I remove them (see figure). Thanks
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
gs1 = gridspec.GridSpec(8, 2)
gs1.update(wspace=0.025, hspace=0.05) # set the spacing between axes.
plt.figure(figsize=(11.69,8.27)) # for landscape
colors=['c','m','y','k','b','g','r','w']
for i in range(16):
ax = plt.subplot(gs1[i])
ax.set_xticklabels([])
ax.set_yticklabels([])
ax.tick_params(left = False, bottom = False)
ax.set_facecolor(colors[i%8])
plt.savefig("toto.png")
|
[
"import matplotlib.pyplot as plt\n\ngridspec_kw = {'wspace':0.025, 'hspace':0.05}\n\nfig, ax = plt.subplots(8, 2, \n figsize=(11.69,8.27), \n gridspec_kw=gridspec_kw,\n layout=\"constrained\")\n\ncolors = ['c', 'm', 'y', 'k', 'b', 'g', 'r', 'w']\n\nfor i in range(8):\n\n # left subplot\n ax[i, 0].set_xticklabels([])\n ax[i, 0].set_yticklabels([])\n ax[i, 0].tick_params(left=False, bottom=False)\n ax[i, 0].set_facecolor(colors[(2*i)%8])\n\n # right subplot \n ax[i, 1].set_xticklabels([])\n ax[i, 1].set_yticklabels([])\n ax[i, 1].tick_params(left=False, bottom=False)\n ax[i, 1].set_facecolor(colors[(2*i)%8+1])\n\nplt.savefig(\"toto_stack_overflow.png\")\n\n",
"There is another way that doesn't involve restructuring/splitting your plot:\nfig = plt.figure(figsize=(11.69,8.27)) # for landscape\nfig.subplots_adjust(bottom=0, top=1, left=0, right=1)\n\n"
] |
[
1,
0
] |
[] |
[] |
[
"matplotlib",
"python"
] |
stackoverflow_0074498961_matplotlib_python.txt
|
Q:
How to print new balance after adding amount to the initial one?
I'm learning Python and went with a simple ATM code. I've tested it and everything works DownStream - what I mean by this is:
I have a few options when the class is initialized - Balance, Deposit, Withdraw, Exit.
When I run Balance I receive the amount set.
2.1. I go with Deposit - it shows the new amount the person has in their account
2.2. When I use Withdraw I get correct amount as well
Question - When I Deposit and then type Balance I'm getting the initial Balance of the user - that is expected. How can I change the code so after Depositing Money and select Balance to show me the new Balance?
Is this possible to be performed without much complicating the code?
The code:
class User:
def __init__(self):
self.fname = input('Enter your first name: ')
self.lname = input('Enter your last name: ')
self.age = input('Enter your age: ')
def user_details(self):
print('Details:')
print(f"First Name: {self.fname}")
print(f"Last Name: {self.lname}")
print(f"User age: {self.age}")
def deposit_money(self):
self.deposit_amount = 100
return self.deposit_amount
def withdraw_money(self, withdraw_amount):
self.withdraw_amount = withdraw_amount
return self.withdraw_amount
class ATM:
atm_balance = 10000
def __init__(self):
self.machine_balance = self.atm_balance
def user_bank_balance(self):
self.user_balance = 300
print ('Your current balance is ${}'.format(self.user_balance))
def deposit_atm(self, user):
self.total_savings = 0
deposit_m = float(input('How much do you want to deposit? '))
if deposit_m > user.deposit_money():
print('You do not have enough money to deposit')
elif deposit_m == user.deposit_money():
print('Amount deposited: ${}'.format(deposit_m))
self.total_savings = self.user_balance + deposit_m
print('Total amount in your account: ${}'.format(self.total_savings))
def withdraw_atm(self):
savings_left = 0
sum_to_withdraw = float(input('How much do you want to withdraw? '))
if self.atm_balance > sum_to_withdraw and self.user_balance > sum_to_withdraw:
savings_left = self.total_savings - sum_to_withdraw
print("You have withdraw {}".format(sum_to_withdraw))
print('You balance is {}'.format(savings_left))
elif self.atm_balance > sum_to_withdraw and self.user_balance < sum_to_withdraw:
print('Daily limit eceeded')
else:
print('ATM out of service')
class ATMUsage:
@classmethod
def run(cls):
print('Bulbank ATM')
instructions = print("""
Type 'Balance' to check your current balance,
Type 'Deposit' to deposit amount into your account,
Type 'Withdraw' to withdraw from your account,
Type 'Exit' to exit from your account,
""")
active = True
user1 = User()
atm1 = ATM()
user1.user_details()
while active:
selection = input("What would you like to do: 'Balance', 'Deposit', 'Withdraw', 'Exit': ")
if selection == 'Balance'.lower():
atm1.user_bank_balance()
elif selection == 'Deposit'.lower():
atm1.deposit_atm(user1)
elif selection == "Withdraw".lower():
atm1.withdraw_atm()
elif selection == 'Exit'.lower():
print('Thanks for passing by. Have a good one!')
break
else:
print('Wrong selection. Please, try again')
ATMUsage.run()
A:
That's because every time you call the user_bank_balance method, you set the user_balance attribute to 300. So it wouldn't matter what updates you did on the user_balance, whenever you call the user_bank_balance method, you'll get 300
class ATM:
atm_balance = 10000
def __init__(self):
self.machine_balance = self.atm_balance
self.user_balance = 300
def user_bank_balance(self):
print ('Your current balance is ${}'.format(self.user_balance))
|
How to print new balance after adding amount to the initial one?
|
I'm learning Python and went with a simple ATM code. I've tested it and everything works DownStream - what I mean by this is:
I have a few options when the class is initialized - Balance, Deposit, Withdraw, Exit.
When I run Balance I receive the amount set.
2.1. I go with Deposit - it shows the new amount the person has in their account
2.2. When I use Withdraw I get correct amount as well
Question - When I Deposit and then type Balance I'm getting the initial Balance of the user - that is expected. How can I change the code so after Depositing Money and select Balance to show me the new Balance?
Is this possible to be performed without much complicating the code?
The code:
class User:
def __init__(self):
self.fname = input('Enter your first name: ')
self.lname = input('Enter your last name: ')
self.age = input('Enter your age: ')
def user_details(self):
print('Details:')
print(f"First Name: {self.fname}")
print(f"Last Name: {self.lname}")
print(f"User age: {self.age}")
def deposit_money(self):
self.deposit_amount = 100
return self.deposit_amount
def withdraw_money(self, withdraw_amount):
self.withdraw_amount = withdraw_amount
return self.withdraw_amount
class ATM:
atm_balance = 10000
def __init__(self):
self.machine_balance = self.atm_balance
def user_bank_balance(self):
self.user_balance = 300
print ('Your current balance is ${}'.format(self.user_balance))
def deposit_atm(self, user):
self.total_savings = 0
deposit_m = float(input('How much do you want to deposit? '))
if deposit_m > user.deposit_money():
print('You do not have enough money to deposit')
elif deposit_m == user.deposit_money():
print('Amount deposited: ${}'.format(deposit_m))
self.total_savings = self.user_balance + deposit_m
print('Total amount in your account: ${}'.format(self.total_savings))
def withdraw_atm(self):
savings_left = 0
sum_to_withdraw = float(input('How much do you want to withdraw? '))
if self.atm_balance > sum_to_withdraw and self.user_balance > sum_to_withdraw:
savings_left = self.total_savings - sum_to_withdraw
print("You have withdraw {}".format(sum_to_withdraw))
print('You balance is {}'.format(savings_left))
elif self.atm_balance > sum_to_withdraw and self.user_balance < sum_to_withdraw:
print('Daily limit eceeded')
else:
print('ATM out of service')
class ATMUsage:
@classmethod
def run(cls):
print('Bulbank ATM')
instructions = print("""
Type 'Balance' to check your current balance,
Type 'Deposit' to deposit amount into your account,
Type 'Withdraw' to withdraw from your account,
Type 'Exit' to exit from your account,
""")
active = True
user1 = User()
atm1 = ATM()
user1.user_details()
while active:
selection = input("What would you like to do: 'Balance', 'Deposit', 'Withdraw', 'Exit': ")
if selection == 'Balance'.lower():
atm1.user_bank_balance()
elif selection == 'Deposit'.lower():
atm1.deposit_atm(user1)
elif selection == "Withdraw".lower():
atm1.withdraw_atm()
elif selection == 'Exit'.lower():
print('Thanks for passing by. Have a good one!')
break
else:
print('Wrong selection. Please, try again')
ATMUsage.run()
|
[
"That's because every time you call the user_bank_balance method, you set the user_balance attribute to 300. So it wouldn't matter what updates you did on the user_balance, whenever you call the user_bank_balance method, you'll get 300\nclass ATM:\n\n atm_balance = 10000\n\n def __init__(self):\n self.machine_balance = self.atm_balance\n self.user_balance = 300\n\n def user_bank_balance(self):\n print ('Your current balance is ${}'.format(self.user_balance))\n\n"
] |
[
0
] |
[] |
[] |
[
"oop",
"python"
] |
stackoverflow_0074500561_oop_python.txt
|
Q:
How can I find where a point will touch a line given a vector?
Here, line segment ab is cast upward on arbitrary vector n where I do somethings to find the black point on the line segment cd. My question is, how do I find the point on ab that intersects with the inverted n vector coming down from the new point?
A:
Looks like it will have the same x-coordinate as the black point (call this x). The slope of ab is m = (by - ay) / (bx - ax), so the y coordinate is mx + ay.
A:
If the projection is parallel, by the Thales theorem the ratios are preserved.
|ae| / |ab| = |cf| / |cd| = r
which is known.
The searched point is, vectorially
e = a + r.ab = a + |cf|/|cd|.ab
|
How can I find where a point will touch a line given a vector?
|
Here, line segment ab is cast upward on arbitrary vector n where I do somethings to find the black point on the line segment cd. My question is, how do I find the point on ab that intersects with the inverted n vector coming down from the new point?
|
[
"Looks like it will have the same x-coordinate as the black point (call this x). The slope of ab is m = (by - ay) / (bx - ax), so the y coordinate is mx + ay.\n",
"If the projection is parallel, by the Thales theorem the ratios are preserved.\n|ae| / |ab| = |cf| / |cd| = r\n\nwhich is known.\nThe searched point is, vectorially\ne = a + r.ab = a + |cf|/|cd|.ab\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"algorithm",
"computational_geometry",
"math",
"python",
"vector"
] |
stackoverflow_0074497596_algorithm_computational_geometry_math_python_vector.txt
|
Q:
selecting mutliple items in python Tkinter Treeview with mouse event Button-1
I looked for and tested many similar questions/answers/possible duplicates here on SO and other sites but I'm interested specifically in using the solution below for simplicity's sake and minimal reproducible example constraint satisfaction.
Why does the following modification of this previous answer's code does not work/how to make it work?
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
tree = ttk.Treeview(root)
tree.pack(fill="both", expand=True)
items = []
for i in range(10):
item = tree.insert("", "end", text="Item {}".format(i+1))
items.append(item)
items_to_select = items[:]
def select_all_items(event):
tree.selection_set(items_to_select)
tree.bind('<Button-1>', select_all_items)
root.mainloop()
The original answer works as is.
I'm looking for a way to make it work with mouse event Button-1 click.
The result should execute the selection of all items in the treeview when users click on any one item with the left mouse button (Button-1).
A:
Try this:
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
tree = ttk.Treeview(root)
tree.pack(fill="both", expand=True)
items = []
for i in range(10):
item = tree.insert("", "end", text="Item {}".format(i+1))
items.append(item)
#items_to_select = []
for item in items:
tree.insert('', tk.END, values=item)
def select_all_items(event):
for selected_item in tree.selection():
item = tree.item(selected_item)
print(item)
#tree.selection_set(items_to_select)
tree.bind('<Button-1>', select_all_items)
root.mainloop()
You can also substitute for code. return "break" I commented out line 14.
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
tree = ttk.Treeview(root)
tree.pack(fill="both", expand=True)
items = []
for i in range(10):
item = tree.insert("", "end", text="Item {}".format(i+1))
items.append(item)
#items_to_select = []
for item in items:
tree.insert('', tk.END, values=item)
def select_all_items(event):
tree.selection_set(items)
return "break"
tree.bind('<Button-1>', select_all_items)
root.mainloop()
A:
Since the default action of a mouse click on any row of the treeview will clear previous selections and select the clicked row.
To disable the default action, return "break" from the callback:
def select_all_items(event):
tree.selection_set(items)
return "break"
Then clicking any row in the treeview will select all rows in it.
Note that you can use items directly and don't need to clone it to new variable.
|
selecting mutliple items in python Tkinter Treeview with mouse event Button-1
|
I looked for and tested many similar questions/answers/possible duplicates here on SO and other sites but I'm interested specifically in using the solution below for simplicity's sake and minimal reproducible example constraint satisfaction.
Why does the following modification of this previous answer's code does not work/how to make it work?
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
tree = ttk.Treeview(root)
tree.pack(fill="both", expand=True)
items = []
for i in range(10):
item = tree.insert("", "end", text="Item {}".format(i+1))
items.append(item)
items_to_select = items[:]
def select_all_items(event):
tree.selection_set(items_to_select)
tree.bind('<Button-1>', select_all_items)
root.mainloop()
The original answer works as is.
I'm looking for a way to make it work with mouse event Button-1 click.
The result should execute the selection of all items in the treeview when users click on any one item with the left mouse button (Button-1).
|
[
"Try this:\nimport tkinter as tk\nfrom tkinter import ttk\n \nroot = tk.Tk()\n \ntree = ttk.Treeview(root)\ntree.pack(fill=\"both\", expand=True)\n \nitems = []\nfor i in range(10):\n item = tree.insert(\"\", \"end\", text=\"Item {}\".format(i+1))\n items.append(item)\n \n#items_to_select = []\n \nfor item in items:\n tree.insert('', tk.END, values=item) \n \ndef select_all_items(event):\n for selected_item in tree.selection():\n item = tree.item(selected_item)\n print(item)\n #tree.selection_set(items_to_select)\n \ntree.bind('<Button-1>', select_all_items)\n \nroot.mainloop()\n\nYou can also substitute for code. return \"break\" I commented out line 14.\nimport tkinter as tk\nfrom tkinter import ttk\n \nroot = tk.Tk()\n \ntree = ttk.Treeview(root)\ntree.pack(fill=\"both\", expand=True)\n \nitems = []\nfor i in range(10):\n item = tree.insert(\"\", \"end\", text=\"Item {}\".format(i+1))\n items.append(item)\n \n#items_to_select = []\n \nfor item in items:\n tree.insert('', tk.END, values=item) \n \ndef select_all_items(event):\n tree.selection_set(items)\n return \"break\"\n \ntree.bind('<Button-1>', select_all_items)\n \nroot.mainloop()\n\n",
"Since the default action of a mouse click on any row of the treeview will clear previous selections and select the clicked row.\nTo disable the default action, return \"break\" from the callback:\ndef select_all_items(event):\n tree.selection_set(items)\n return \"break\"\n\nThen clicking any row in the treeview will select all rows in it.\nNote that you can use items directly and don't need to clone it to new variable.\n"
] |
[
1,
1
] |
[] |
[] |
[
"mouseevent",
"python",
"python_3.x",
"tkinter",
"treeview"
] |
stackoverflow_0074498330_mouseevent_python_python_3.x_tkinter_treeview.txt
|
Q:
Use Group By and Aggregate Function in pyspark?
I am looking for a Solution to how to use Group by Aggregate Functions together in Pyspark?
My Dataframe looks like this:
df = sc.parallelize([
('23-09-2020', 'CRICKET'),
('25-11-2020', 'CRICKET'),
('13-09-2021', 'FOOTBALL'),
('20-11-2021', 'BASKETBALL'),
('12-12-2021', 'FOOTBALL')]).toDF(['DATE', 'SPORTS_INTERESTED'])
I want to apply group by on the SPORTS_INTERESTED Column and select MIN of date From DATE Column .
Below is the Query i am using
from pyspark.sql.functions import min
df=df.groupby('SPORTS_INTERESTED').agg(count('SPORTS_INTERESTED').alias('FIRST_COUNT'),(F.min('DATE').alias('MIN_OF_DATE_COLUMN'))).filter((col('FIRST_COUNT')> 1))
But when i am applying the above Query , I dont know why it is giving MAX date rather than MIN date in Output values
DESIRED OUTPUT
## +-----------------+-------------------+
## |SPORTS_INTERESTED| MIN_OF_DATE_COLUMN|
## +------+----------+-------------------+
## | CRICKET |23-09-2020 |
## +------+----------+-------------------+
## | FOOTBALL |13-09-2021 |
+-----------------+-------------------+
Output i am getting:
## +-----------------+----------------------+
## |SPORTS_INTERESTED| MIN_OF_DATE_COLUMN|
## +------+----------+-------------------+
## | CRICKET |25-11-2020 |
## +------+----------+-------------------+
## | FOOTBALL |12-12-2021 |
+-----------------+-------------------+
BOTH COLUMNS ARE OF STRING DATATYPE
A:
First, convert string to date format, and then apply min:
import pyspark.sql.functions as F
df = spark.createDataFrame(data=[
('23-09-2020', 'CRICKET'),
('25-11-2020', 'CRICKET'),
('13-09-2021', 'FOOTBALL'),
('20-11-2021', 'BASKETBALL'),
('12-12-2021', 'FOOTBALL')
], schema=['DATE', 'SPORTS_INTERESTED'])
df = df.withColumn("DATE", F.to_date("DATE", format="dd-MM-yyyy"))
df = df.groupBy("SPORTS_INTERESTED").agg(F.min("DATE").alias("MIN_OF_DATE"))
[Out]:
+-----------------+-----------+
|SPORTS_INTERESTED|MIN_OF_DATE|
+-----------------+-----------+
|BASKETBALL |2021-11-20 |
|FOOTBALL |2021-09-13 |
|CRICKET |2020-09-23 |
+-----------------+-----------+
|
Use Group By and Aggregate Function in pyspark?
|
I am looking for a Solution to how to use Group by Aggregate Functions together in Pyspark?
My Dataframe looks like this:
df = sc.parallelize([
('23-09-2020', 'CRICKET'),
('25-11-2020', 'CRICKET'),
('13-09-2021', 'FOOTBALL'),
('20-11-2021', 'BASKETBALL'),
('12-12-2021', 'FOOTBALL')]).toDF(['DATE', 'SPORTS_INTERESTED'])
I want to apply group by on the SPORTS_INTERESTED Column and select MIN of date From DATE Column .
Below is the Query i am using
from pyspark.sql.functions import min
df=df.groupby('SPORTS_INTERESTED').agg(count('SPORTS_INTERESTED').alias('FIRST_COUNT'),(F.min('DATE').alias('MIN_OF_DATE_COLUMN'))).filter((col('FIRST_COUNT')> 1))
But when i am applying the above Query , I dont know why it is giving MAX date rather than MIN date in Output values
DESIRED OUTPUT
## +-----------------+-------------------+
## |SPORTS_INTERESTED| MIN_OF_DATE_COLUMN|
## +------+----------+-------------------+
## | CRICKET |23-09-2020 |
## +------+----------+-------------------+
## | FOOTBALL |13-09-2021 |
+-----------------+-------------------+
Output i am getting:
## +-----------------+----------------------+
## |SPORTS_INTERESTED| MIN_OF_DATE_COLUMN|
## +------+----------+-------------------+
## | CRICKET |25-11-2020 |
## +------+----------+-------------------+
## | FOOTBALL |12-12-2021 |
+-----------------+-------------------+
BOTH COLUMNS ARE OF STRING DATATYPE
|
[
"First, convert string to date format, and then apply min:\nimport pyspark.sql.functions as F\n\ndf = spark.createDataFrame(data=[\n ('23-09-2020', 'CRICKET'),\n ('25-11-2020', 'CRICKET'),\n ('13-09-2021', 'FOOTBALL'),\n ('20-11-2021', 'BASKETBALL'),\n ('12-12-2021', 'FOOTBALL') \n], schema=['DATE', 'SPORTS_INTERESTED'])\n\ndf = df.withColumn(\"DATE\", F.to_date(\"DATE\", format=\"dd-MM-yyyy\"))\ndf = df.groupBy(\"SPORTS_INTERESTED\").agg(F.min(\"DATE\").alias(\"MIN_OF_DATE\"))\n\n[Out]:\n+-----------------+-----------+\n|SPORTS_INTERESTED|MIN_OF_DATE|\n+-----------------+-----------+\n|BASKETBALL |2021-11-20 |\n|FOOTBALL |2021-09-13 |\n|CRICKET |2020-09-23 |\n+-----------------+-----------+\n\n"
] |
[
0
] |
[] |
[] |
[
"apache_spark",
"databricks",
"pyspark",
"python"
] |
stackoverflow_0074500675_apache_spark_databricks_pyspark_python.txt
|
Q:
how do i add an element with a key to th elist
let's say we have a list like:
list = [{'name': 'car', 'number': '2'}]
And i want to add {'name': 'fruit', 'number': '4'} element to it.
At the end list should look like:
list = [{'name': 'car', 'number': '2'},
{'name': 'fruit', 'number': '4'}]
I tried to solve it like this:
list = [{'name': 'car', 'number': '2'}]
list.extend({'name': 'fruit', 'number': '4'})
but it returns: [{'name': 'car', 'number': '2'}, 'name', 'number'], and it's not what i want.
How do i do it?
A:
Try doing:
list.append({'name': 'fruit', 'number': '4'})
The append() method adds the specified value to the end of the list.
|
how do i add an element with a key to th elist
|
let's say we have a list like:
list = [{'name': 'car', 'number': '2'}]
And i want to add {'name': 'fruit', 'number': '4'} element to it.
At the end list should look like:
list = [{'name': 'car', 'number': '2'},
{'name': 'fruit', 'number': '4'}]
I tried to solve it like this:
list = [{'name': 'car', 'number': '2'}]
list.extend({'name': 'fruit', 'number': '4'})
but it returns: [{'name': 'car', 'number': '2'}, 'name', 'number'], and it's not what i want.
How do i do it?
|
[
"Try doing:\nlist.append({'name': 'fruit', 'number': '4'})\n\nThe append() method adds the specified value to the end of the list.\n"
] |
[
0
] |
[] |
[] |
[
"list",
"python"
] |
stackoverflow_0074500875_list_python.txt
|
Q:
About perfect numbers
a = input('input a number :')
for i in range(1,int(a)):
b=0
for z in range(1,int(a)):
if i == z :
continue
elif i%z == 0:
print('i = ',i,'z =',z)
b += z
print('b = ',b)
if b == i:
print(i,'is a perfect number')
My question is about that why this program gives output '24' as 'perfect number' ?
I was coding a 'perfect number finder with for loop' machine.My question is about that why this program gives output '24' as 'perfect number' ?
A:
You are checking the sum of the divisors against the number itself inside the loop, before you finish iterating over all divisors. In the case of 24, its divisors are 1, 2, 3, 4, 6, 8, 12. But, their sum up to (and including) 8 is 1+2+3+4+6+8 = 24, so the condition b == i evaluates to true. Instead, you need to perform this check once, after the loop is finished. Also, you should only check for divisors up to i-1 (this can be improved upon mathematically to floor(i/2), but let's get the basics first), not a.
Here is a slightly cleaned up version of your code, with this correction
a = int(input('input a number :'))
for i in range(1, a):
b=0
for z in range(1, i):
if i%z == 0:
b += z
print(f'i = {i} z = {z} b = {b}')
if b == i:
print(i,'is a perfect number')
|
About perfect numbers
|
a = input('input a number :')
for i in range(1,int(a)):
b=0
for z in range(1,int(a)):
if i == z :
continue
elif i%z == 0:
print('i = ',i,'z =',z)
b += z
print('b = ',b)
if b == i:
print(i,'is a perfect number')
My question is about that why this program gives output '24' as 'perfect number' ?
I was coding a 'perfect number finder with for loop' machine.My question is about that why this program gives output '24' as 'perfect number' ?
|
[
"You are checking the sum of the divisors against the number itself inside the loop, before you finish iterating over all divisors. In the case of 24, its divisors are 1, 2, 3, 4, 6, 8, 12. But, their sum up to (and including) 8 is 1+2+3+4+6+8 = 24, so the condition b == i evaluates to true. Instead, you need to perform this check once, after the loop is finished. Also, you should only check for divisors up to i-1 (this can be improved upon mathematically to floor(i/2), but let's get the basics first), not a.\nHere is a slightly cleaned up version of your code, with this correction\na = int(input('input a number :'))\nfor i in range(1, a):\n b=0\n for z in range(1, i):\n if i%z == 0:\n b += z\n print(f'i = {i} z = {z} b = {b}')\n if b == i:\n print(i,'is a perfect number')\n\n"
] |
[
0
] |
[] |
[] |
[
"for_loop",
"perfect_numbers",
"python"
] |
stackoverflow_0074500859_for_loop_perfect_numbers_python.txt
|
Q:
What is the error in these function and how can i overcome it?
I asked a question and had a successful answer (link. Unfortunatelly, im having problems while using the suggested code in google colab. Could you help me either (i) getting the suggested code working in google colab; or (ii) suggest a new code for the problem I explained in the link, please?
Im using the code:
import requests
import pandas as pd
from bs4 import BeautifulSoup
html = requests.get("https://www.tce.sp.gov.br/jurisprudencia/exibir?proc=18955/989/20&offset=0")
soup = BeautifulSoup(html.content)
data = []
for e in soup.select('table:last-of-type tr:has(td)'):
it = iter(soup.table.stripped_strings)
d = dict(zip(it,it))
d.update({
'link': e.a.get('href'),
'date': e.select('td')[-2].text,
'type': e.select('td')[-1].text
})
data.append(d)
But it returns this error:
NotImplementedError Traceback (most recent call last)
<ipython-input-14-c9c2af04191b> in <module>
9 data = []
10
---> 11 for e in soup.select('table:last-of-type tr:has(td)'):
12 it = iter(soup.table.stripped_strings)
13 d = dict(zip(it,it))
/usr/local/lib/python3.7/dist-packages/bs4/element.py in select(self, selector, _candidate_generator, limit)
1526 else:
1527 raise NotImplementedError(
-> 1528 'Only the following pseudo-classes are implemented: nth-of-type.')
1529
1530 elif token == '*':
NotImplementedError: Only the following pseudo-classes are implemented: nth-of-type.
A:
Your code work perfectly there is no bug at all. Just upgrade "BeautifulSoup".
pip install --upgrade beautifulsoup4
and rest of code will be same.
NOTE: Once you upgrade BeautifulSoup library then restart runtime of your colab environment so that upgraded library come into force.
Step to restart runtime:
Click on Runtime menu.
Select Restart runtime.
Select Run all.
|
What is the error in these function and how can i overcome it?
|
I asked a question and had a successful answer (link. Unfortunatelly, im having problems while using the suggested code in google colab. Could you help me either (i) getting the suggested code working in google colab; or (ii) suggest a new code for the problem I explained in the link, please?
Im using the code:
import requests
import pandas as pd
from bs4 import BeautifulSoup
html = requests.get("https://www.tce.sp.gov.br/jurisprudencia/exibir?proc=18955/989/20&offset=0")
soup = BeautifulSoup(html.content)
data = []
for e in soup.select('table:last-of-type tr:has(td)'):
it = iter(soup.table.stripped_strings)
d = dict(zip(it,it))
d.update({
'link': e.a.get('href'),
'date': e.select('td')[-2].text,
'type': e.select('td')[-1].text
})
data.append(d)
But it returns this error:
NotImplementedError Traceback (most recent call last)
<ipython-input-14-c9c2af04191b> in <module>
9 data = []
10
---> 11 for e in soup.select('table:last-of-type tr:has(td)'):
12 it = iter(soup.table.stripped_strings)
13 d = dict(zip(it,it))
/usr/local/lib/python3.7/dist-packages/bs4/element.py in select(self, selector, _candidate_generator, limit)
1526 else:
1527 raise NotImplementedError(
-> 1528 'Only the following pseudo-classes are implemented: nth-of-type.')
1529
1530 elif token == '*':
NotImplementedError: Only the following pseudo-classes are implemented: nth-of-type.
|
[
"Your code work perfectly there is no bug at all. Just upgrade \"BeautifulSoup\".\npip install --upgrade beautifulsoup4\n\nand rest of code will be same.\nNOTE: Once you upgrade BeautifulSoup library then restart runtime of your colab environment so that upgraded library come into force.\nStep to restart runtime:\nClick on Runtime menu.\nSelect Restart runtime.\nSelect Run all.\n\n"
] |
[
0
] |
[] |
[] |
[
"beautifulsoup",
"google_colaboratory",
"python",
"select",
"web_scraping"
] |
stackoverflow_0074453340_beautifulsoup_google_colaboratory_python_select_web_scraping.txt
|
Q:
Eliminating rows and plotting a "customer country count in percentage" (Pandas, matplotlib)
If this is the dataframe
VisitorID visitNumber Country
1 1 USA
2 1 UK
3 1 CANADA
3 2 CANADA
4 1 MEXICO
I want to plot a piechart with matplotlib about the visitors of each country (so it'd be 33% for each country), so I don't want to count canada twice (because it has the same VisitorID)
I've been looking for hours and I can't get the solution.
I've tried:
df2 = df.groupby('VisitorID').agg({'visitNumber': 'max'}).reset_index()
but is deleting the other columns and I can't even see the shape anymore
If I try to run:
df2.shape()
the output is :
TypeError: 'tuple' object is not callable
A:
You can specify the aggregation function for Country as well:
df2 = df.groupby('VisitorID').agg({'visitNumber': 'max', 'Country': 'first'}).reset_index()
Also shape is a property, not a method. So remove the parenthesis:
df2.shape
|
Eliminating rows and plotting a "customer country count in percentage" (Pandas, matplotlib)
|
If this is the dataframe
VisitorID visitNumber Country
1 1 USA
2 1 UK
3 1 CANADA
3 2 CANADA
4 1 MEXICO
I want to plot a piechart with matplotlib about the visitors of each country (so it'd be 33% for each country), so I don't want to count canada twice (because it has the same VisitorID)
I've been looking for hours and I can't get the solution.
I've tried:
df2 = df.groupby('VisitorID').agg({'visitNumber': 'max'}).reset_index()
but is deleting the other columns and I can't even see the shape anymore
If I try to run:
df2.shape()
the output is :
TypeError: 'tuple' object is not callable
|
[
"You can specify the aggregation function for Country as well:\ndf2 = df.groupby('VisitorID').agg({'visitNumber': 'max', 'Country': 'first'}).reset_index()\n\nAlso shape is a property, not a method. So remove the parenthesis:\ndf2.shape\n\n"
] |
[
0
] |
[] |
[] |
[
"matplotlib",
"pandas",
"python"
] |
stackoverflow_0074500803_matplotlib_pandas_python.txt
|
Q:
Checking if mentioned user is online
I am working on my own Discord bot. I want to make it reply to messages, not really specific commands. One of my ideas is to make it respond to messages in which I am pinged. However, it's not enough for me. I want it to respond to people ONLY when I am offline, and don't respond when online/DND/BRB. Bellow, you can see how the command looks like. Do you have any idea how to transform it as to check my status?
`@client.event
async def on_message(message)
elif message.content == '<@(my user ID>':
response = "What do you need from the Mighty One?"
await message.channel.send(response)`
A:
Here is my code:
@client.event
async def on_message(message):
if message.content == '<@YourUserID>':
#if you are offline:
Me = message.guild.get_member(YourUserID)
if Me.status == discord.Status.offline:
response = "What do you need from the Mighty One?"
await message.channel.send(response)
#do whatever you want ....
basically it checks your status.
Hopefully this helps!
|
Checking if mentioned user is online
|
I am working on my own Discord bot. I want to make it reply to messages, not really specific commands. One of my ideas is to make it respond to messages in which I am pinged. However, it's not enough for me. I want it to respond to people ONLY when I am offline, and don't respond when online/DND/BRB. Bellow, you can see how the command looks like. Do you have any idea how to transform it as to check my status?
`@client.event
async def on_message(message)
elif message.content == '<@(my user ID>':
response = "What do you need from the Mighty One?"
await message.channel.send(response)`
|
[
"Here is my code:\n@client.event \nasync def on_message(message):\n if message.content == '<@YourUserID>':\n #if you are offline:\n Me = message.guild.get_member(YourUserID)\n if Me.status == discord.Status.offline:\n response = \"What do you need from the Mighty One?\"\n await message.channel.send(response)\n #do whatever you want ....\n\nbasically it checks your status.\nHopefully this helps!\n"
] |
[
0
] |
[] |
[] |
[
"bots",
"discord.py",
"python"
] |
stackoverflow_0074482890_bots_discord.py_python.txt
|
Q:
Scraping news articles using Selenium Python
I am Learning to scrape news articles from the website https://tribune.com.pk/pakistan/archives. The first thing is to scrape the link of every news article. Now the problem is that <a tag contains two href in it but I want to get the first href tag which I am unable to do
I am attaching the html of that particular part
The code I have written returns me 2 href tags but I only want the first one
def Url_Extraction():
category_name = driver.find_element(By.XPATH, '//*[@id="main-section"]/h1')
cat = category_name.text # Save category name in variable
print(f"{cat}")
news_articles = driver.find_elements(By.XPATH,"//div[contains(@class,'flex-wrap')]//a")
for element in news_articles:
URL = element.get_attribute('href')
print(URL)
Url.append(URL)
Category.append(cat)
current_time = time.time() - start_time
print(f'{len(Url)} urls extracted')
print(f'{len(Category)} categories extracted')
print(f'Current Time: {current_time / 3600:.2f} hr, {current_time / 60:.2f} min, {current_time:.2f} sec',
flush=True)
Moreover I am able to paginate but I can't get the full article by clicking the individual links given on the main page.
A:
You have to modify the below XPath:
Instead of this -
news_articles = driver.find_elements(By.XPATH,"//div[contains(@class,'flex-wrap')]//a")
Use this -
news_articles = driver.find_elements(By.XPATH,"//div[contains(@class,'flex-wrap')]/a")
|
Scraping news articles using Selenium Python
|
I am Learning to scrape news articles from the website https://tribune.com.pk/pakistan/archives. The first thing is to scrape the link of every news article. Now the problem is that <a tag contains two href in it but I want to get the first href tag which I am unable to do
I am attaching the html of that particular part
The code I have written returns me 2 href tags but I only want the first one
def Url_Extraction():
category_name = driver.find_element(By.XPATH, '//*[@id="main-section"]/h1')
cat = category_name.text # Save category name in variable
print(f"{cat}")
news_articles = driver.find_elements(By.XPATH,"//div[contains(@class,'flex-wrap')]//a")
for element in news_articles:
URL = element.get_attribute('href')
print(URL)
Url.append(URL)
Category.append(cat)
current_time = time.time() - start_time
print(f'{len(Url)} urls extracted')
print(f'{len(Category)} categories extracted')
print(f'Current Time: {current_time / 3600:.2f} hr, {current_time / 60:.2f} min, {current_time:.2f} sec',
flush=True)
Moreover I am able to paginate but I can't get the full article by clicking the individual links given on the main page.
|
[
"You have to modify the below XPath:\nInstead of this -\nnews_articles = driver.find_elements(By.XPATH,\"//div[contains(@class,'flex-wrap')]//a\")\nUse this -\nnews_articles = driver.find_elements(By.XPATH,\"//div[contains(@class,'flex-wrap')]/a\")\n"
] |
[
0
] |
[] |
[] |
[
"python",
"selenium",
"web_scraping"
] |
stackoverflow_0074500600_python_selenium_web_scraping.txt
|
Q:
Selenium: element click intercepted: Element is not clickable at point (774, 8907)
I am new to selenium, and I get the following error: element click intercepted: Element is not clickable at point (774, 8907) whenever I run this code on the webpage that has the show more button. My goal is to get every element of the "table" on the webpage, but in order to do so I need to click "show more" button if it is present:
driver = webdriver.Chrome(options=chrome_options)
driver.maximize_window()
for el in states_pages:
driver.get(el)
err = False
i = 0
while not err:
try:
more_button = driver.find_element(by=By.CLASS_NAME, value='tpl-showmore-content')
more_button.click()
except selexp.NoSuchElementException as e:
err = True
print(e)
except selexp.ElementClickInterceptedException as e:
err = True
print(e)
i+=1
I have tried using javascript executor, waiting until the button is clickable and crolling to the button by using actions, but this didn't work at all.
Sample website: https://www.privateschoolreview.com/sat-score-stats/california
A:
Because JavaScript interaction. So you have to click using JS execution.
import time
while not err:
try:
more_button = driver.find_element(by=By.CLASS_NAME, value='tpl-showmore-content')
driver.execute_script("arguments[0].click();" ,more_button)
time.sleep(1)
except selexp.NoSuchElementException as e:
err = True
print(e)
except selexp.ElementClickInterceptedException as e:
err = True
print(e)
break
Update:
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from bs4 import BeautifulSoup
import time
import pandas as pd
options = webdriver.ChromeOptions()
options.add_argument("--no-sandbox")
options.add_argument('--disable-blink-features=AutomationControlled')
options.add_argument("start-maximized")
#options.add_experimental_option("detach", True)
s=Service('./chromedriver')
driver= webdriver.Chrome(service=s, options=options)
url='https://www.privateschoolreview.com/sat-score-stats/california'
driver.get(url)
time.sleep(3)
data =[]
for x in range(4):
try:
soup = BeautifulSoup(driver.page_source, 'lxml')
cards = soup.select('[class="tp-list-row list-row-border-2 bg_hover_change"]')
print(len(cards))
for x in cards:
title = x.select_one('a[class="tpl-school-link top-school"]')
title = title.get_text(strip=True) if title else 'None'
data.append(title)
loadMoreButton = driver.find_element(By.CSS_SELECTOR, ".tpl-showmore-content")
if loadMoreButton:
driver.execute_script("arguments[0].click();" ,loadMoreButton)
time.sleep(1)
except Exception as e:
pass
#print(e)
break
df= pd.DataFrame(set(data))
print(df)
Output:
0
0 St. Lucys Priory High School
1 Glendale Adventist Academy
2 The Webb Schools
3 Desert Christian Academy
4 New Covenant Academy
.. ...
113 Renaissance Academy
114 Oak Grove School
115 Francis Parker School
116 Rolling Hills Preparatory School
117 Lake Tahoe Preparatory School
[118 rows x 1 columns]
A:
Try this, it works for me:
show_more_lnk = driver.find_element(By.CSS_SELECTOR, ".tpl-showmore-content")
driver.execute_script("arguments[0].scrollIntoView(true)", show_more_lnk)
time.sleep(2)
show_more_lnk.click()
|
Selenium: element click intercepted: Element is not clickable at point (774, 8907)
|
I am new to selenium, and I get the following error: element click intercepted: Element is not clickable at point (774, 8907) whenever I run this code on the webpage that has the show more button. My goal is to get every element of the "table" on the webpage, but in order to do so I need to click "show more" button if it is present:
driver = webdriver.Chrome(options=chrome_options)
driver.maximize_window()
for el in states_pages:
driver.get(el)
err = False
i = 0
while not err:
try:
more_button = driver.find_element(by=By.CLASS_NAME, value='tpl-showmore-content')
more_button.click()
except selexp.NoSuchElementException as e:
err = True
print(e)
except selexp.ElementClickInterceptedException as e:
err = True
print(e)
i+=1
I have tried using javascript executor, waiting until the button is clickable and crolling to the button by using actions, but this didn't work at all.
Sample website: https://www.privateschoolreview.com/sat-score-stats/california
|
[
"Because JavaScript interaction. So you have to click using JS execution.\n import time\n while not err:\n try:\n more_button = driver.find_element(by=By.CLASS_NAME, value='tpl-showmore-content')\n driver.execute_script(\"arguments[0].click();\" ,more_button)\n time.sleep(1)\n except selexp.NoSuchElementException as e:\n err = True\n print(e)\n except selexp.ElementClickInterceptedException as e:\n err = True\n print(e)\n break\n\nUpdate:\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.common.by import By\nfrom bs4 import BeautifulSoup\nimport time\nimport pandas as pd\n\noptions = webdriver.ChromeOptions()\noptions.add_argument(\"--no-sandbox\")\noptions.add_argument('--disable-blink-features=AutomationControlled')\noptions.add_argument(\"start-maximized\")\n#options.add_experimental_option(\"detach\", True)\n\n\ns=Service('./chromedriver')\ndriver= webdriver.Chrome(service=s, options=options)\nurl='https://www.privateschoolreview.com/sat-score-stats/california'\ndriver.get(url)\ntime.sleep(3)\n\ndata =[]\nfor x in range(4):\n try:\n soup = BeautifulSoup(driver.page_source, 'lxml')\n cards = soup.select('[class=\"tp-list-row list-row-border-2 bg_hover_change\"]')\n print(len(cards))\n for x in cards:\n title = x.select_one('a[class=\"tpl-school-link top-school\"]')\n title = title.get_text(strip=True) if title else 'None'\n data.append(title)\n\n \n loadMoreButton = driver.find_element(By.CSS_SELECTOR, \".tpl-showmore-content\")\n \n if loadMoreButton:\n driver.execute_script(\"arguments[0].click();\" ,loadMoreButton)\n time.sleep(1)\n\n \n except Exception as e:\n pass\n #print(e)\n break\n\ndf= pd.DataFrame(set(data))\nprint(df)\n\nOutput:\n 0\n0 St. Lucys Priory High School\n1 Glendale Adventist Academy\n2 The Webb Schools\n3 Desert Christian Academy\n4 New Covenant Academy\n.. ...\n113 Renaissance Academy\n114 Oak Grove School\n115 Francis Parker School\n116 Rolling Hills Preparatory School\n117 Lake Tahoe Preparatory School\n\n[118 rows x 1 columns]\n\n",
"Try this, it works for me:\nshow_more_lnk = driver.find_element(By.CSS_SELECTOR, \".tpl-showmore-content\")\ndriver.execute_script(\"arguments[0].scrollIntoView(true)\", show_more_lnk)\ntime.sleep(2)\nshow_more_lnk.click()\n\n"
] |
[
2,
0
] |
[] |
[] |
[
"python",
"selenium",
"web_scraping"
] |
stackoverflow_0074500670_python_selenium_web_scraping.txt
|
Q:
search data with multiple values in django
Want to filter data with multiple values in django.Currently i can only take two value from html but only one value filtering
This is my views code
p = request.GET.getlist('passout',[])
c = request.GET.getlist('course',[])
s = request.GET.getlist('skill',[])
search_variables = {}
if p:
for l in p:
search_variables['passout__yearofpassing__contains'] = l
print("@@@@@",p)
if s:
for j in s:
search_variables['skill__skill_name__contains'] = j
if c:
for k in c:
search_variables['course__course_name__contains'] = k
print("@@kk",k)
datas_list = Student.objects.filter(
**search_variables, status="Active").order_by('id')
This is html code
<div class="col col-sm-3" style="margin-right:-80px;">
<select class="selectpicker" id="passout" name="passout" placeholder="Select YOP" multiple >
{% for j in p %}<option value="{{ j }}" selected>{{i.yearofpassing}}</option> {% endfor %}
{% for i in yr %}
<option value="{{i.yearofpassing}}">{{i.yearofpassing}}</option>
{% endfor %}
</select>
</div>
<div class="col col-sm-3" style="margin-right:-80px;" >
<select class="selectpicker" name="course" id="course" placeholder="Select Course" multiple >
{% for j in c %}<option value="{{ j }}" selected >{{i.course_name}}</option> {% endfor %}
{% for i in cr %}
<option value="{{i.course_name}}">{{i.course_name}}</option>
{% endfor %}
</select>
</div>
<div class="col col-sm-3" style="margin-right: -350px;">
<select class="selectpicker" id="skill" name="skill" placeholder="Select Skills" multiple >
{% for j in s %}<option value="{{ j }}" selected >{{i.skill_name}}</option>{% endfor %}
{% for i in sl %}
<option value="{{i.skill_name}}" >{{i.skill_name}}</option>
{% endfor %}
</select>
</div>
<button id="search4" style="margin-left: 320px; " class="au-btn btn-info btn-sm" >Search </button>
<button id="search" style="margin-left: 1px; " class="au-btn btn-info " > <a href=" {% url 'publicpage' %}" style="margin-left: 8px; height: 40px; color: white;" title="Reset"> <i style="font-size:medium; margin-bottom: 1px; " class='fas fa-sync'></i></a></button>
in this image i search student with year of passout 2019 it shows a result
if i search with two or three values it shows nothing but in db the students are present
A:
the thing is that you don't have that data for all search filters because Django filter work with AND operator and in your image you said give me a result that happened in 2019 AND 2020 and this is not possible.
the filter is working you just need to store the right data.
|
search data with multiple values in django
|
Want to filter data with multiple values in django.Currently i can only take two value from html but only one value filtering
This is my views code
p = request.GET.getlist('passout',[])
c = request.GET.getlist('course',[])
s = request.GET.getlist('skill',[])
search_variables = {}
if p:
for l in p:
search_variables['passout__yearofpassing__contains'] = l
print("@@@@@",p)
if s:
for j in s:
search_variables['skill__skill_name__contains'] = j
if c:
for k in c:
search_variables['course__course_name__contains'] = k
print("@@kk",k)
datas_list = Student.objects.filter(
**search_variables, status="Active").order_by('id')
This is html code
<div class="col col-sm-3" style="margin-right:-80px;">
<select class="selectpicker" id="passout" name="passout" placeholder="Select YOP" multiple >
{% for j in p %}<option value="{{ j }}" selected>{{i.yearofpassing}}</option> {% endfor %}
{% for i in yr %}
<option value="{{i.yearofpassing}}">{{i.yearofpassing}}</option>
{% endfor %}
</select>
</div>
<div class="col col-sm-3" style="margin-right:-80px;" >
<select class="selectpicker" name="course" id="course" placeholder="Select Course" multiple >
{% for j in c %}<option value="{{ j }}" selected >{{i.course_name}}</option> {% endfor %}
{% for i in cr %}
<option value="{{i.course_name}}">{{i.course_name}}</option>
{% endfor %}
</select>
</div>
<div class="col col-sm-3" style="margin-right: -350px;">
<select class="selectpicker" id="skill" name="skill" placeholder="Select Skills" multiple >
{% for j in s %}<option value="{{ j }}" selected >{{i.skill_name}}</option>{% endfor %}
{% for i in sl %}
<option value="{{i.skill_name}}" >{{i.skill_name}}</option>
{% endfor %}
</select>
</div>
<button id="search4" style="margin-left: 320px; " class="au-btn btn-info btn-sm" >Search </button>
<button id="search" style="margin-left: 1px; " class="au-btn btn-info " > <a href=" {% url 'publicpage' %}" style="margin-left: 8px; height: 40px; color: white;" title="Reset"> <i style="font-size:medium; margin-bottom: 1px; " class='fas fa-sync'></i></a></button>
in this image i search student with year of passout 2019 it shows a result
if i search with two or three values it shows nothing but in db the students are present
|
[
"the thing is that you don't have that data for all search filters because Django filter work with AND operator and in your image you said give me a result that happened in 2019 AND 2020 and this is not possible.\nthe filter is working you just need to store the right data.\n"
] |
[
0
] |
[] |
[] |
[
"django",
"filter",
"python",
"search"
] |
stackoverflow_0074501030_django_filter_python_search.txt
|
Q:
Why i am having a maximum recursion depth exceeded error
I am trying to apply the Binary Search algorithm (the recursive way) and I'm having this error
def BinarySearchRec(tab, x):
mid = len(tab) // 2
if len(tab) == 0:
return False
if tab[mid] > x:
return BinarySearchRec(tab[:mid], x)
elif tab[mid] < x:
return BinarySearchRec(tab[mid:], x)
else:
return mid
I tried to 1 and retrive one when i call the function back but didn't work on all cases
A:
When mid=0 and tab[mid] < x, the code gets stuck because BinarySearchRec(tab[mid:], x) will loop forever with the same inputs: (tab[mid:],x) -> (tab[0:],x) -> (tab,x) .
As a proof, you can try the following example:
tab = [1]
x = 2
BinarySearchRec(tab, x)
# recursion error raised
The easiest solution is to make sure that the array tab decreases in size every time you perform recursion:
def BinarySearchRec(tab, x):
mid = len(tab) // 2
if len(tab) == 0:
return False
if tab[mid] > x:
return BinarySearchRec(tab[:mid-1], x)
elif tab[mid] < x:
return BinarySearchRec(tab[mid+1:], x)
else:
return mid
tab = [1]
x = 2
BinarySearchRec(tab, x)
# now it works
In the new code, the tab array is trimmed using either mid+1 or mid-1, since we can discard mid as a solution when tab[mid] != x. This makes sure that tab always decreases at least one element in size, and hence the code does not crash. Cheers,
|
Why i am having a maximum recursion depth exceeded error
|
I am trying to apply the Binary Search algorithm (the recursive way) and I'm having this error
def BinarySearchRec(tab, x):
mid = len(tab) // 2
if len(tab) == 0:
return False
if tab[mid] > x:
return BinarySearchRec(tab[:mid], x)
elif tab[mid] < x:
return BinarySearchRec(tab[mid:], x)
else:
return mid
I tried to 1 and retrive one when i call the function back but didn't work on all cases
|
[
"When mid=0 and tab[mid] < x, the code gets stuck because BinarySearchRec(tab[mid:], x) will loop forever with the same inputs: (tab[mid:],x) -> (tab[0:],x) -> (tab,x) .\nAs a proof, you can try the following example:\ntab = [1]\nx = 2\nBinarySearchRec(tab, x)\n# recursion error raised\n\nThe easiest solution is to make sure that the array tab decreases in size every time you perform recursion:\ndef BinarySearchRec(tab, x):\n mid = len(tab) // 2\n if len(tab) == 0:\n return False\n if tab[mid] > x:\n return BinarySearchRec(tab[:mid-1], x)\n elif tab[mid] < x:\n return BinarySearchRec(tab[mid+1:], x)\n else:\n return mid\n\ntab = [1]\nx = 2\nBinarySearchRec(tab, x)\n# now it works\n\nIn the new code, the tab array is trimmed using either mid+1 or mid-1, since we can discard mid as a solution when tab[mid] != x. This makes sure that tab always decreases at least one element in size, and hence the code does not crash. Cheers,\n"
] |
[
1
] |
[] |
[] |
[
"arrays",
"binary_search",
"list",
"python",
"sorting"
] |
stackoverflow_0074500935_arrays_binary_search_list_python_sorting.txt
|
Q:
Better way of printing ascii art at given framerate
I am trying to optimize printing ascii art at given framerate. Now i am using time.sleep() but this is inconsistent because it doesnt add time when the frames are opening. I am asking is there a library which can handle this for me ?
This is my curent code:
def play_ascii():
maxcount = len(os.listdir('temp/ascii'))
count = 1
interval = input("Sleep between frames (recommended value: 0.03)")
winsound.PlaySound("temp/audio.wav",winsound.SND_ASYNC or winsound.SND_ALIAS)
while count != maxcount:
print(open("temp/ascii/frame{:05d}.txt".format(count)).read())
time.sleep(float(interval))
count+=1
winsound.PlaySound(None,winsound.SND_ASYNC)
A:
fpstimer might help
It can maintain certain a FPS in runtime
here is its PYPI link:
https://pypi.org/project/fpstimer
|
Better way of printing ascii art at given framerate
|
I am trying to optimize printing ascii art at given framerate. Now i am using time.sleep() but this is inconsistent because it doesnt add time when the frames are opening. I am asking is there a library which can handle this for me ?
This is my curent code:
def play_ascii():
maxcount = len(os.listdir('temp/ascii'))
count = 1
interval = input("Sleep between frames (recommended value: 0.03)")
winsound.PlaySound("temp/audio.wav",winsound.SND_ASYNC or winsound.SND_ALIAS)
while count != maxcount:
print(open("temp/ascii/frame{:05d}.txt".format(count)).read())
time.sleep(float(interval))
count+=1
winsound.PlaySound(None,winsound.SND_ASYNC)
|
[
"fpstimer might help\nIt can maintain certain a FPS in runtime\nhere is its PYPI link:\nhttps://pypi.org/project/fpstimer\n"
] |
[
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0074501059_python.txt
|
Q:
How to split data frame into x and y
I am splitting the data into training data and testing data like so:
train, test = train_test_split(dataFrame(), test_size=0.2)
Which works wonders, my training data frame looks like this:
PassengerId Survived SibSp Parch
77 78 0 0 0
748 749 0 1 0
444 445 1 0 0
361 362 0 1 0
576 577 1 0 0
27 28 0 3 2
232 233 0 0 0
424 425 0 1 1
785 786 0 0 0
… … … … …
I am now attempting to get the X and Y columns, X being my SibSp column and Y being my Parch column. After following many tutorials on Regression and training my AI, every person "split" the columns into x and y like so:
x = train[:, 0:2]
However, after many variations and googling, I cannot solve this error this line is giving me nor understand it:
TypeError: unhashable type: 'slice'
How can I split the SibSp column into an array of x and the Parch column into an array of y within my training data frame?
A:
The correct way to slice is x = train.iloc[:, 0:2].
A:
If your target class is the last column, the most generic solution is:
X = df.iloc[:, 0:-1]
y = df.iloc[:, -1]
|
How to split data frame into x and y
|
I am splitting the data into training data and testing data like so:
train, test = train_test_split(dataFrame(), test_size=0.2)
Which works wonders, my training data frame looks like this:
PassengerId Survived SibSp Parch
77 78 0 0 0
748 749 0 1 0
444 445 1 0 0
361 362 0 1 0
576 577 1 0 0
27 28 0 3 2
232 233 0 0 0
424 425 0 1 1
785 786 0 0 0
… … … … …
I am now attempting to get the X and Y columns, X being my SibSp column and Y being my Parch column. After following many tutorials on Regression and training my AI, every person "split" the columns into x and y like so:
x = train[:, 0:2]
However, after many variations and googling, I cannot solve this error this line is giving me nor understand it:
TypeError: unhashable type: 'slice'
How can I split the SibSp column into an array of x and the Parch column into an array of y within my training data frame?
|
[
"The correct way to slice is x = train.iloc[:, 0:2].\n",
"If your target class is the last column, the most generic solution is:\nX = df.iloc[:, 0:-1]\ny = df.iloc[:, -1]\n\n"
] |
[
14,
0
] |
[] |
[] |
[
"numpy",
"python"
] |
stackoverflow_0053991131_numpy_python.txt
|
Q:
Pycharm Referenced Error With Import Selenium Webdriver
Am using Python 3.6.5rcs , pip version 9.0.1 , selenium 3.11.0. The Python is installed in C:\Python and selenium is in C:\Python\Lib\site-packages\selenium. The environment variables have been set.
But the code
from selenium import webdriver
gives an unresolved reference error.
Any suggestion on how to fix the problem.
A:
Pycharm > Preferences > Project Interpreter
Then hit the '+' to install the package to your project path.
Or you can add that path to your PYTHONPATH environment variable in your project.
A:
I found this worked for me. I'm using PyCharm Community 2018.1.4 on Windows.
Navigate to: File->Settings->Project: [project name] -> Project Interpreter
On this page click the configuration wheel at the top which should provide a drop down menu. Click "Add" and a window should appear called "Add Python Interpreter"
You will be defaulted onto "Virtualenv Environment" tab.
There should be a checkbox called "Inherit global site-packages". Check this.
Click OK.
All your installed packages should be added.
A:
I used this command to resolve my error.
pip install webdriver_manager
A:
Install selenium and webdriver-manager from the option "python package" directly in the pycharm solve my problem
|
Pycharm Referenced Error With Import Selenium Webdriver
|
Am using Python 3.6.5rcs , pip version 9.0.1 , selenium 3.11.0. The Python is installed in C:\Python and selenium is in C:\Python\Lib\site-packages\selenium. The environment variables have been set.
But the code
from selenium import webdriver
gives an unresolved reference error.
Any suggestion on how to fix the problem.
|
[
"Pycharm > Preferences > Project Interpreter\nThen hit the '+' to install the package to your project path.\nOr you can add that path to your PYTHONPATH environment variable in your project.\n",
"I found this worked for me. I'm using PyCharm Community 2018.1.4 on Windows.\nNavigate to: File->Settings->Project: [project name] -> Project Interpreter\nOn this page click the configuration wheel at the top which should provide a drop down menu. Click \"Add\" and a window should appear called \"Add Python Interpreter\"\nYou will be defaulted onto \"Virtualenv Environment\" tab.\nThere should be a checkbox called \"Inherit global site-packages\". Check this.\nClick OK.\nAll your installed packages should be added.\n",
"I used this command to resolve my error.\npip install webdriver_manager\n",
"Install selenium and webdriver-manager from the option \"python package\" directly in the pycharm solve my problem\n"
] |
[
4,
2,
1,
0
] |
[] |
[] |
[
"pycharm",
"python",
"selenium"
] |
stackoverflow_0049482586_pycharm_python_selenium.txt
|
Q:
How to select only a link while web scrapping a HTML which the attribute has also text?
As a part of a a bigger webscrapping project, I want to extract the html link from a html. It is not all html link on the page, but only the in the second column of the big table.
An example of how the html these links appear look like:
<a href="exibir?proc=18955/989/20&offset=0">18955/989/20</a>
I would like to have a list the "exibir?proc=18955/989/20&offset=0" and NOT the "18955/989/20".
So far, i could only get them both together (code bellow). How can I get rid of it? Is there another solution? At the end I would like to have only a list of the links in the order they already appear.
from requests_html import HTMLSession
import csv
s = HTMLSession()
def get_product_links(page):
url = f"https://www.tce.sp.gov.br/jurisprudencia/pesquisar?txtTdPalvs=munic%C3%ADpio+pessoal+37&txtExp=temporari&txtQqUma=admiss%C3%A3o+contrata%C3%A7%C3%A3o&txtNenhPalvs=&txtNumIni=&txtNumFim=&tipoBuscaTxt=Documento&_tipoBuscaTxt=on&quantTrechos=1&processo=&exercicio=&dataAutuacaoInicio=&dataAutuacaoFim=&dataPubInicio=01%2F01%2F2021&dataPubFim=31%2F12%2F2021&_relator=1&_auditor=1&_materia=1&tipoDocumento=2&_tipoDocumento=1&acao=Executa&offset={page}"
links = []
r = s.get(url)
products = r.html.find('td.small a')
for item in products:
links.append(item.find('a', first=True).attrs['href'])
return links
page1 = get_product_links(0)
print(page1)
A:
Here is one way to get those links from the second column. You're welcome to functionalize it if you want.
from bs4 import BeautifulSoup as bs
import requests
from tqdm import tqdm ## if using Jupyter: from tqdm.notebook import tqdm
import pandas as pd
pd.set_option('display.max_columns', None)
pd.set_option('display.max_colwidth', None)
headers = {
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.5112.79 Safari/537.36'
}
s = requests.Session()
s.headers.update(headers)
big_list = []
for x in tqdm(range(0, 410, 10)):
url = f'https://www.tce.sp.gov.br/jurisprudencia/pesquisar?txtTdPalvs=munic%C3%ADpio+pessoal+37&txtExp=temporari&txtQqUma=admiss%C3%A3o+contrata%C3%A7%C3%A3o&txtNenhPalvs=&txtNumIni=&txtNumFim=&tipoBuscaTxt=Documento&_tipoBuscaTxt=on&quantTrechos=1&processo=&exercicio=&dataAutuacaoInicio=&dataAutuacaoFim=&dataPubInicio=01%2F01%2F2021&dataPubFim=31%2F12%2F2021&_relator=1&_auditor=1&_materia=1&tipoDocumento=2&_tipoDocumento=1&acao=Executa&offset={x}'
r = s.get(url)
urls = bs(r.text, 'html.parser').select('tr[class="borda-superior"] td:nth-of-type(2) a')
big_list.extend([(x.text.strip(), 'https://www.tce.sp.gov.br/jurisprudencia/' + x.get('href')) for x in urls])
df = pd.DataFrame(big_list, columns = ['title', 'url'])
print(df)
Result in terminal:
100%
41/41 [00:30<00:00, 1.42it/s]
title url
0 18955/989/20 https://www.tce.sp.gov.br/jurisprudencia/exibir?proc=18955/989/20&offset=0
1 13614/989/18 https://www.tce.sp.gov.br/jurisprudencia/exibir?proc=13614/989/18&offset=0
2 6269/989/19 https://www.tce.sp.gov.br/jurisprudencia/exibir?proc=6269/989/19&offset=0
3 14011/989/19 https://www.tce.sp.gov.br/jurisprudencia/exibir?proc=14011/989/19&offset=0
4 14082/989/19 https://www.tce.sp.gov.br/jurisprudencia/exibir?proc=14082/989/19&offset=0
... ... ...
399 4023/989/18 https://www.tce.sp.gov.br/jurisprudencia/exibir?proc=4023/989/18&offset=390
400 4024/989/18 https://www.tce.sp.gov.br/jurisprudencia/exibir?proc=4024/989/18&offset=400
401 4025/989/18 https://www.tce.sp.gov.br/jurisprudencia/exibir?proc=4025/989/18&offset=400
402 4026/989/18 https://www.tce.sp.gov.br/jurisprudencia/exibir?proc=4026/989/18&offset=400
403 4027/989/18 https://www.tce.sp.gov.br/jurisprudencia/exibir?proc=4027/989/18&offset=400
404 rows × 2 columns
Edit: If you want only the (partial) url as a list, all you have to do is:
from bs4 import BeautifulSoup as bs
import requests
from tqdm import tqdm ## if Jupyter: from tqdm.notebook import tqdm
import pandas as pd
pd.set_option('display.max_columns', None)
pd.set_option('display.max_colwidth', None)
s = requests.Session()
s.headers.update(headers)
big_list = []
for x in tqdm(range(0, 410, 10)):
url = f'https://www.tce.sp.gov.br/jurisprudencia/pesquisar?txtTdPalvs=munic%C3%ADpio+pessoal+37&txtExp=temporari&txtQqUma=admiss%C3%A3o+contrata%C3%A7%C3%A3o&txtNenhPalvs=&txtNumIni=&txtNumFim=&tipoBuscaTxt=Documento&_tipoBuscaTxt=on&quantTrechos=1&processo=&exercicio=&dataAutuacaoInicio=&dataAutuacaoFim=&dataPubInicio=01%2F01%2F2021&dataPubFim=31%2F12%2F2021&_relator=1&_auditor=1&_materia=1&tipoDocumento=2&_tipoDocumento=1&acao=Executa&offset={x}'
r = s.get(url)
urls = bs(r.text, 'html.parser').select('tr[class="borda-superior"] td:nth-of-type(2) a')
big_list.extend([x.get('href') for x in urls])
print(big_list)
Result in terminal:
100%
41/41 [00:29<00:00, 1.83it/s]
['exibir?proc=18955/989/20&offset=0',
'exibir?proc=13614/989/18&offset=0',
'exibir?proc=6269/989/19&offset=0',
'exibir?proc=14011/989/19&offset=0',
'exibir?proc=14082/989/19&offset=0',
'exibir?proc=14238/989/19&offset=0',
'exibir?proc=14141/989/20&offset=0',
'exibir?proc=15371/989/19&offset=0',
'exibir?proc=15388/989/20&offset=0',
'exibir?proc=12911/989/16&offset=0',
'exibir?proc=1735/002/11&offset=10',
'exibir?proc=23494/989/18&offset=10',
'exibir?proc=24496/989/19&offset=10',
'exibir?proc=17110/989/18&offset=10',
'exibir?proc=24043/989/19&offset=10',
'exibir?proc=2515/989/20&offset=10',
'exibir?proc=1891/989/20&offset=10',
'exibir?proc=15026/989/20&offset=10',
'exibir?proc=9070/989/20&offset=10',
'exibir?proc=21543/989/20&offset=10',
'exibir?proc=19654/989/20&offset=20',
'exibir?proc=19678/989/20&offset=20',
'exibir?proc=5714/989/19&offset=20',
'exibir?proc=20493/989/20&offset=20',
'exibir?proc=4671/989/19&offset=20',
'exibir?proc=14200/989/20&offset=20',
'exibir?proc=15277/989/20&offset=20',
'exibir?proc=1363/007/12&offset=20',
'exibir?proc=4908/989/19&offset=20',
'exibir?proc=15164/989/20&offset=20',
'exibir?proc=4418/989/19&offset=30',
'exibir?proc=4890/989/19&offset=30',
'exibir?proc=17924/989/20&offset=30',
'exibir?proc=4742/989/19&offset=30',
'exibir?proc=800226/465/09&offset=30',
'exibir?proc=23880/989/20&offset=30',
'exibir?proc=4561/989/19&offset=30',
'exibir?proc=4540/989/19&offset=30',
'exibir?proc=4471/989/19&offset=30',
'exibir?proc=4982/989/19&offset=30',
'exibir?proc=4519/989/19&offset=40',
'exibir?proc=4632/989/19&offset=40',
'exibir?proc=4536/989/19&offset=40',
'exibir?proc=4622/989/19&offset=40',
'exibir?proc=14734/989/16&offset=40',
'exibir?proc=4678/989/19&offset=40',
'exibir?proc=5501/989/16&offset=40',
'exibir?proc=13988/989/17&offset=40',
'exibir?proc=4854/989/19&offset=40',
'exibir?proc=4609/989/19&offset=40',
'exibir?proc=4717/989/19&offset=50',
'exibir?proc=4673/989/19&offset=50',
'exibir?proc=20988/989/20&offset=50',
'exibir?proc=4481/989/19&offset=50',
'exibir?proc=4675/989/19&offset=50',
'exibir?proc=4451/989/19&offset=50',
'exibir?proc=12943/989/19&offset=50',
'exibir?proc=23644/989/18&offset=50',
'exibir?proc=23875/989/18&offset=50',
'exibir?proc=4679/989/19&offset=50',
'exibir?proc=4425/989/19&offset=60',
'exibir?proc=2726/989/18&offset=60',
'exibir?proc=17172/989/20&offset=60',
'exibir?proc=2901/989/18&offset=60',
'exibir?proc=4469/989/19&offset=60',
'exibir?proc=299/012/13&offset=60',
'exibir?proc=4915/989/19&offset=60',
'exibir?proc=22649/989/20&offset=60',
'exibir?proc=22887/989/20&offset=60',
'exibir?proc=4721/989/19&offset=60',
'exibir?proc=4378/989/19&offset=70',
'exibir?proc=4935/989/19&offset=70',
'exibir?proc=4714/989/19&offset=70',
'exibir?proc=1230/989/21&offset=70',
'exibir?proc=1847/989/21&offset=70',
'exibir?proc=15606/989/21&offset=70',
'exibir?proc=11267/989/18&offset=70',
'exibir?proc=1232/004/12&offset=70',
'exibir?proc=4421/989/19&offset=70',
'exibir?proc=4931/989/19&offset=70',
'exibir?proc=4885/989/19&offset=80',
'exibir?proc=5002/989/19&offset=80',
'exibir?proc=21592/989/20&offset=80',
'exibir?proc=4839/989/19&offset=80',
'exibir?proc=4783/989/19&offset=80',
'exibir?proc=4599/989/19&offset=80',
'exibir?proc=4702/989/19&offset=80',
'exibir?proc=4617/989/19&offset=80',
'exibir?proc=4970/989/16&offset=80',
'exibir?proc=4492/989/19&offset=80',
'exibir?proc=2582/989/17&offset=90',
'exibir?proc=4993/989/19&offset=90',
'exibir?proc=4658/989/19&offset=90',
'exibir?proc=4606/989/19&offset=90',
'exibir?proc=4387/989/19&offset=90',
'exibir?proc=14549/989/19&offset=90',
'exibir?proc=4525/989/18&offset=90',
'exibir?proc=4713/989/19&offset=90',
'exibir?proc=838/001/14&offset=90',
'exibir?proc=4971/989/19&offset=90',
'exibir?proc=17505/989/18&offset=100',
'exibir?proc=5096/989/18&offset=100',
'exibir?proc=4413/989/19&offset=100',
'exibir?proc=4392/989/19&offset=100',
'exibir?proc=15132/989/20&offset=100',
'exibir?proc=4517/989/19&offset=100',
'exibir?proc=4760/989/19&offset=100',
'exibir?proc=18509/989/19&offset=100',
'exibir?proc=4952/989/19&offset=100',
'exibir?proc=5013/989/19&offset=100',
'exibir?proc=12922/989/19&offset=110',
'exibir?proc=6194/989/16&offset=110',
'exibir?proc=19323/989/20&offset=110',
'exibir?proc=4732/989/19&offset=110',
...]
|
How to select only a link while web scrapping a HTML which the attribute has also text?
|
As a part of a a bigger webscrapping project, I want to extract the html link from a html. It is not all html link on the page, but only the in the second column of the big table.
An example of how the html these links appear look like:
<a href="exibir?proc=18955/989/20&offset=0">18955/989/20</a>
I would like to have a list the "exibir?proc=18955/989/20&offset=0" and NOT the "18955/989/20".
So far, i could only get them both together (code bellow). How can I get rid of it? Is there another solution? At the end I would like to have only a list of the links in the order they already appear.
from requests_html import HTMLSession
import csv
s = HTMLSession()
def get_product_links(page):
url = f"https://www.tce.sp.gov.br/jurisprudencia/pesquisar?txtTdPalvs=munic%C3%ADpio+pessoal+37&txtExp=temporari&txtQqUma=admiss%C3%A3o+contrata%C3%A7%C3%A3o&txtNenhPalvs=&txtNumIni=&txtNumFim=&tipoBuscaTxt=Documento&_tipoBuscaTxt=on&quantTrechos=1&processo=&exercicio=&dataAutuacaoInicio=&dataAutuacaoFim=&dataPubInicio=01%2F01%2F2021&dataPubFim=31%2F12%2F2021&_relator=1&_auditor=1&_materia=1&tipoDocumento=2&_tipoDocumento=1&acao=Executa&offset={page}"
links = []
r = s.get(url)
products = r.html.find('td.small a')
for item in products:
links.append(item.find('a', first=True).attrs['href'])
return links
page1 = get_product_links(0)
print(page1)
|
[
"Here is one way to get those links from the second column. You're welcome to functionalize it if you want.\nfrom bs4 import BeautifulSoup as bs\nimport requests\nfrom tqdm import tqdm ## if using Jupyter: from tqdm.notebook import tqdm\nimport pandas as pd\n\npd.set_option('display.max_columns', None)\npd.set_option('display.max_colwidth', None)\n\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.5112.79 Safari/537.36'\n}\ns = requests.Session()\ns.headers.update(headers)\n\nbig_list = []\nfor x in tqdm(range(0, 410, 10)):\n url = f'https://www.tce.sp.gov.br/jurisprudencia/pesquisar?txtTdPalvs=munic%C3%ADpio+pessoal+37&txtExp=temporari&txtQqUma=admiss%C3%A3o+contrata%C3%A7%C3%A3o&txtNenhPalvs=&txtNumIni=&txtNumFim=&tipoBuscaTxt=Documento&_tipoBuscaTxt=on&quantTrechos=1&processo=&exercicio=&dataAutuacaoInicio=&dataAutuacaoFim=&dataPubInicio=01%2F01%2F2021&dataPubFim=31%2F12%2F2021&_relator=1&_auditor=1&_materia=1&tipoDocumento=2&_tipoDocumento=1&acao=Executa&offset={x}'\n r = s.get(url)\n urls = bs(r.text, 'html.parser').select('tr[class=\"borda-superior\"] td:nth-of-type(2) a')\n big_list.extend([(x.text.strip(), 'https://www.tce.sp.gov.br/jurisprudencia/' + x.get('href')) for x in urls])\ndf = pd.DataFrame(big_list, columns = ['title', 'url']) \nprint(df)\n\nResult in terminal:\n100%\n41/41 [00:30<00:00, 1.42it/s]\ntitle url\n0 18955/989/20 https://www.tce.sp.gov.br/jurisprudencia/exibir?proc=18955/989/20&offset=0\n1 13614/989/18 https://www.tce.sp.gov.br/jurisprudencia/exibir?proc=13614/989/18&offset=0\n2 6269/989/19 https://www.tce.sp.gov.br/jurisprudencia/exibir?proc=6269/989/19&offset=0\n3 14011/989/19 https://www.tce.sp.gov.br/jurisprudencia/exibir?proc=14011/989/19&offset=0\n4 14082/989/19 https://www.tce.sp.gov.br/jurisprudencia/exibir?proc=14082/989/19&offset=0\n... ... ...\n399 4023/989/18 https://www.tce.sp.gov.br/jurisprudencia/exibir?proc=4023/989/18&offset=390\n400 4024/989/18 https://www.tce.sp.gov.br/jurisprudencia/exibir?proc=4024/989/18&offset=400\n401 4025/989/18 https://www.tce.sp.gov.br/jurisprudencia/exibir?proc=4025/989/18&offset=400\n402 4026/989/18 https://www.tce.sp.gov.br/jurisprudencia/exibir?proc=4026/989/18&offset=400\n403 4027/989/18 https://www.tce.sp.gov.br/jurisprudencia/exibir?proc=4027/989/18&offset=400\n404 rows × 2 columns\n\nEdit: If you want only the (partial) url as a list, all you have to do is:\nfrom bs4 import BeautifulSoup as bs\nimport requests\nfrom tqdm import tqdm ## if Jupyter: from tqdm.notebook import tqdm\nimport pandas as pd\n\npd.set_option('display.max_columns', None)\npd.set_option('display.max_colwidth', None)\n\ns = requests.Session()\ns.headers.update(headers)\n\nbig_list = []\nfor x in tqdm(range(0, 410, 10)):\n url = f'https://www.tce.sp.gov.br/jurisprudencia/pesquisar?txtTdPalvs=munic%C3%ADpio+pessoal+37&txtExp=temporari&txtQqUma=admiss%C3%A3o+contrata%C3%A7%C3%A3o&txtNenhPalvs=&txtNumIni=&txtNumFim=&tipoBuscaTxt=Documento&_tipoBuscaTxt=on&quantTrechos=1&processo=&exercicio=&dataAutuacaoInicio=&dataAutuacaoFim=&dataPubInicio=01%2F01%2F2021&dataPubFim=31%2F12%2F2021&_relator=1&_auditor=1&_materia=1&tipoDocumento=2&_tipoDocumento=1&acao=Executa&offset={x}'\n r = s.get(url)\n urls = bs(r.text, 'html.parser').select('tr[class=\"borda-superior\"] td:nth-of-type(2) a')\n big_list.extend([x.get('href') for x in urls])\nprint(big_list)\n\nResult in terminal:\n100%\n41/41 [00:29<00:00, 1.83it/s]\n['exibir?proc=18955/989/20&offset=0',\n 'exibir?proc=13614/989/18&offset=0',\n 'exibir?proc=6269/989/19&offset=0',\n 'exibir?proc=14011/989/19&offset=0',\n 'exibir?proc=14082/989/19&offset=0',\n 'exibir?proc=14238/989/19&offset=0',\n 'exibir?proc=14141/989/20&offset=0',\n 'exibir?proc=15371/989/19&offset=0',\n 'exibir?proc=15388/989/20&offset=0',\n 'exibir?proc=12911/989/16&offset=0',\n 'exibir?proc=1735/002/11&offset=10',\n 'exibir?proc=23494/989/18&offset=10',\n 'exibir?proc=24496/989/19&offset=10',\n 'exibir?proc=17110/989/18&offset=10',\n 'exibir?proc=24043/989/19&offset=10',\n 'exibir?proc=2515/989/20&offset=10',\n 'exibir?proc=1891/989/20&offset=10',\n 'exibir?proc=15026/989/20&offset=10',\n 'exibir?proc=9070/989/20&offset=10',\n 'exibir?proc=21543/989/20&offset=10',\n 'exibir?proc=19654/989/20&offset=20',\n 'exibir?proc=19678/989/20&offset=20',\n 'exibir?proc=5714/989/19&offset=20',\n 'exibir?proc=20493/989/20&offset=20',\n 'exibir?proc=4671/989/19&offset=20',\n 'exibir?proc=14200/989/20&offset=20',\n 'exibir?proc=15277/989/20&offset=20',\n 'exibir?proc=1363/007/12&offset=20',\n 'exibir?proc=4908/989/19&offset=20',\n 'exibir?proc=15164/989/20&offset=20',\n 'exibir?proc=4418/989/19&offset=30',\n 'exibir?proc=4890/989/19&offset=30',\n 'exibir?proc=17924/989/20&offset=30',\n 'exibir?proc=4742/989/19&offset=30',\n 'exibir?proc=800226/465/09&offset=30',\n 'exibir?proc=23880/989/20&offset=30',\n 'exibir?proc=4561/989/19&offset=30',\n 'exibir?proc=4540/989/19&offset=30',\n 'exibir?proc=4471/989/19&offset=30',\n 'exibir?proc=4982/989/19&offset=30',\n 'exibir?proc=4519/989/19&offset=40',\n 'exibir?proc=4632/989/19&offset=40',\n 'exibir?proc=4536/989/19&offset=40',\n 'exibir?proc=4622/989/19&offset=40',\n 'exibir?proc=14734/989/16&offset=40',\n 'exibir?proc=4678/989/19&offset=40',\n 'exibir?proc=5501/989/16&offset=40',\n 'exibir?proc=13988/989/17&offset=40',\n 'exibir?proc=4854/989/19&offset=40',\n 'exibir?proc=4609/989/19&offset=40',\n 'exibir?proc=4717/989/19&offset=50',\n 'exibir?proc=4673/989/19&offset=50',\n 'exibir?proc=20988/989/20&offset=50',\n 'exibir?proc=4481/989/19&offset=50',\n 'exibir?proc=4675/989/19&offset=50',\n 'exibir?proc=4451/989/19&offset=50',\n 'exibir?proc=12943/989/19&offset=50',\n 'exibir?proc=23644/989/18&offset=50',\n 'exibir?proc=23875/989/18&offset=50',\n 'exibir?proc=4679/989/19&offset=50',\n 'exibir?proc=4425/989/19&offset=60',\n 'exibir?proc=2726/989/18&offset=60',\n 'exibir?proc=17172/989/20&offset=60',\n 'exibir?proc=2901/989/18&offset=60',\n 'exibir?proc=4469/989/19&offset=60',\n 'exibir?proc=299/012/13&offset=60',\n 'exibir?proc=4915/989/19&offset=60',\n 'exibir?proc=22649/989/20&offset=60',\n 'exibir?proc=22887/989/20&offset=60',\n 'exibir?proc=4721/989/19&offset=60',\n 'exibir?proc=4378/989/19&offset=70',\n 'exibir?proc=4935/989/19&offset=70',\n 'exibir?proc=4714/989/19&offset=70',\n 'exibir?proc=1230/989/21&offset=70',\n 'exibir?proc=1847/989/21&offset=70',\n 'exibir?proc=15606/989/21&offset=70',\n 'exibir?proc=11267/989/18&offset=70',\n 'exibir?proc=1232/004/12&offset=70',\n 'exibir?proc=4421/989/19&offset=70',\n 'exibir?proc=4931/989/19&offset=70',\n 'exibir?proc=4885/989/19&offset=80',\n 'exibir?proc=5002/989/19&offset=80',\n 'exibir?proc=21592/989/20&offset=80',\n 'exibir?proc=4839/989/19&offset=80',\n 'exibir?proc=4783/989/19&offset=80',\n 'exibir?proc=4599/989/19&offset=80',\n 'exibir?proc=4702/989/19&offset=80',\n 'exibir?proc=4617/989/19&offset=80',\n 'exibir?proc=4970/989/16&offset=80',\n 'exibir?proc=4492/989/19&offset=80',\n 'exibir?proc=2582/989/17&offset=90',\n 'exibir?proc=4993/989/19&offset=90',\n 'exibir?proc=4658/989/19&offset=90',\n 'exibir?proc=4606/989/19&offset=90',\n 'exibir?proc=4387/989/19&offset=90',\n 'exibir?proc=14549/989/19&offset=90',\n 'exibir?proc=4525/989/18&offset=90',\n 'exibir?proc=4713/989/19&offset=90',\n 'exibir?proc=838/001/14&offset=90',\n 'exibir?proc=4971/989/19&offset=90',\n 'exibir?proc=17505/989/18&offset=100',\n 'exibir?proc=5096/989/18&offset=100',\n 'exibir?proc=4413/989/19&offset=100',\n 'exibir?proc=4392/989/19&offset=100',\n 'exibir?proc=15132/989/20&offset=100',\n 'exibir?proc=4517/989/19&offset=100',\n 'exibir?proc=4760/989/19&offset=100',\n 'exibir?proc=18509/989/19&offset=100',\n 'exibir?proc=4952/989/19&offset=100',\n 'exibir?proc=5013/989/19&offset=100',\n 'exibir?proc=12922/989/19&offset=110',\n 'exibir?proc=6194/989/16&offset=110',\n 'exibir?proc=19323/989/20&offset=110',\n 'exibir?proc=4732/989/19&offset=110',\n...]\n\n"
] |
[
0
] |
[] |
[] |
[
"html",
"hyperlink",
"loops",
"python",
"web_scraping"
] |
stackoverflow_0074497612_html_hyperlink_loops_python_web_scraping.txt
|
Q:
TypeError: btn_add() missing 1 required positional argument: 'first_number'
I'm making a calculator in Python using Tkinter, and I'm getting an error im not sure as to why im running into this error but ive legit tried retyping the whole code and cant find anything about it on yt:
`
from tkinter import *
w = Tk()
w.title("Simple Calculator")
ent = Entry()
ent.grid(row=0,column=0,columnspan=3,padx=10,pady=10 )
def button_click(number):
current = ent.get()
ent.delete(0,END)
ent.insert(0,str(current)+str(number))
def button_clear():
ent.delete(0, END)
def button_add(first_number):
first_number = ent.get()
global f_num
f_num = int(first_number)
ent.delete(END)
# Defining Button
button_1 = Button(w,text="1",padx=40,pady=20,command=lambda:button_click(1))
button_2 = Button(w,text="2",padx = 40,pady = 20,command=lambda:button_click(2))
button_3 = Button(w,text="3",padx = 40,pady = 20,command=lambda:button_click(3))
button_4 = Button(w,text="4",padx = 40,pady = 20,command=lambda:button_click(4))
button_5 = Button(w,text="5",padx = 40,pady = 20,command=lambda:button_click(5))
button_6 = Button(w,text="6",padx = 40,pady = 20,command=lambda:button_click(6))
button_7 = Button(w,text="7",padx = 40,pady = 20,command=lambda:button_click(7))
button_8 = Button(w,text="8",padx = 40,pady = 20,command=lambda:button_click(8))
button_9 = Button(w,text="9",padx = 40,pady = 20,command=lambda:button_click(9))
button_0 = Button(w,text="0",padx = 40,pady = 20,command=lambda:button_click(0))
button_add = Button(w,text="+",padx=39,pady=20,command=button_add)
button_equal = Button(w,text="=",padx = 91,pady = 20,command=button_click)
button_clear = Button(w,text="CLEAR",padx = 79,pady = 20,command=button_clear)
# Putting button on screen
button_1.grid(row=3,column=0 )
button_2.grid(row=3,column= 1)
button_3.grid(row=3,column= 2)
button_4.grid(row=2,column= 0)
button_5.grid(row=2,column= 1)
button_6.grid(row=2,column= 2)
button_7.grid(row=1,column= 0)
button_8.grid(row=1,column= 1)
button_9.grid(row=1,column= 2)
button_0.grid(row=4,column= 0)
button_clear.grid(row=4,column=1,columnspan=2)
button_add.grid(row=5,column=0)
button_equal.grid(row=5,column=1,columnspan=2)
w.mainloop()
`
i tried everything to fix this error
P.S. I don't actually know which line the error is on, because it's saying that the error is on line 1705, even though the code is only 101 lines
A:
The error is where you inherit the Button class to button_add
specifically in command=button_add
You have to add in 'first_number' parameter to the command parameter
A:
def button_add():
first_number = ent.get()
global f_num
f_num = int(first_number)
ent.delete(END)
|
TypeError: btn_add() missing 1 required positional argument: 'first_number'
|
I'm making a calculator in Python using Tkinter, and I'm getting an error im not sure as to why im running into this error but ive legit tried retyping the whole code and cant find anything about it on yt:
`
from tkinter import *
w = Tk()
w.title("Simple Calculator")
ent = Entry()
ent.grid(row=0,column=0,columnspan=3,padx=10,pady=10 )
def button_click(number):
current = ent.get()
ent.delete(0,END)
ent.insert(0,str(current)+str(number))
def button_clear():
ent.delete(0, END)
def button_add(first_number):
first_number = ent.get()
global f_num
f_num = int(first_number)
ent.delete(END)
# Defining Button
button_1 = Button(w,text="1",padx=40,pady=20,command=lambda:button_click(1))
button_2 = Button(w,text="2",padx = 40,pady = 20,command=lambda:button_click(2))
button_3 = Button(w,text="3",padx = 40,pady = 20,command=lambda:button_click(3))
button_4 = Button(w,text="4",padx = 40,pady = 20,command=lambda:button_click(4))
button_5 = Button(w,text="5",padx = 40,pady = 20,command=lambda:button_click(5))
button_6 = Button(w,text="6",padx = 40,pady = 20,command=lambda:button_click(6))
button_7 = Button(w,text="7",padx = 40,pady = 20,command=lambda:button_click(7))
button_8 = Button(w,text="8",padx = 40,pady = 20,command=lambda:button_click(8))
button_9 = Button(w,text="9",padx = 40,pady = 20,command=lambda:button_click(9))
button_0 = Button(w,text="0",padx = 40,pady = 20,command=lambda:button_click(0))
button_add = Button(w,text="+",padx=39,pady=20,command=button_add)
button_equal = Button(w,text="=",padx = 91,pady = 20,command=button_click)
button_clear = Button(w,text="CLEAR",padx = 79,pady = 20,command=button_clear)
# Putting button on screen
button_1.grid(row=3,column=0 )
button_2.grid(row=3,column= 1)
button_3.grid(row=3,column= 2)
button_4.grid(row=2,column= 0)
button_5.grid(row=2,column= 1)
button_6.grid(row=2,column= 2)
button_7.grid(row=1,column= 0)
button_8.grid(row=1,column= 1)
button_9.grid(row=1,column= 2)
button_0.grid(row=4,column= 0)
button_clear.grid(row=4,column=1,columnspan=2)
button_add.grid(row=5,column=0)
button_equal.grid(row=5,column=1,columnspan=2)
w.mainloop()
`
i tried everything to fix this error
P.S. I don't actually know which line the error is on, because it's saying that the error is on line 1705, even though the code is only 101 lines
|
[
"The error is where you inherit the Button class to button_add\nspecifically in command=button_add\nYou have to add in 'first_number' parameter to the command parameter\n",
"def button_add():\nfirst_number = ent.get()\nglobal f_num\nf_num = int(first_number)\nent.delete(END)\n\n"
] |
[
0,
-1
] |
[] |
[] |
[
"calculator",
"function",
"python",
"tkinter"
] |
stackoverflow_0074501029_calculator_function_python_tkinter.txt
|
Q:
Nextcord: sending a message from a .txt
I want to send a random line from a .txt from my discord bot, I am using nextcord but if discord.py works better I can use that to. Let me know if anyone can help.
I haven't tried much as I am fairly new to python but thought I would give it a try. I tried using random and .json but it went horribly lol.
A:
I'm not sure how nextcord works but there is a way you can get a random line from a .txt file in any python file.
Firstly, make sure your .txt file is in the same folder as your python file. Secondly we should import random as we will use random.choice in this method. Then, you can create a function which chooses a random line from a text file which looks like this:
def random_line(fname):
lines = open(fname).read().splitlines()
return random.choice(lines)
We can just call this function whenever we want to get a random line from a .txt file.
Now that we have a way to get a random line from a .txt file, we can implement this into discord.py.This is how you would create this command in discord.py
import random
import discord
from discord.ext import commands
FILE_NAME = ""
YOUR_TOKEN = ""
intents = discord.Intents.all()
bot = commands.Bot(command_prefix=">", intents=intents)
#The function that gets the random line
def random_line(fname):
lines = open(fname).read().splitlines()
return random.choice(lines)
#Making the comand
@bot.command()
async def randomline(ctx):
await ctx.send(random_line(FILE_NAME))
bot.run(YOUR_TOKEN)
And remember to enable intents in the Developer Portal
If you would like to use nextcord just try to use the function that I gave you to make this command. I hope this helps and if there were any problems just let me kow.
|
Nextcord: sending a message from a .txt
|
I want to send a random line from a .txt from my discord bot, I am using nextcord but if discord.py works better I can use that to. Let me know if anyone can help.
I haven't tried much as I am fairly new to python but thought I would give it a try. I tried using random and .json but it went horribly lol.
|
[
"I'm not sure how nextcord works but there is a way you can get a random line from a .txt file in any python file.\nFirstly, make sure your .txt file is in the same folder as your python file. Secondly we should import random as we will use random.choice in this method. Then, you can create a function which chooses a random line from a text file which looks like this:\ndef random_line(fname):\n lines = open(fname).read().splitlines()\n return random.choice(lines)\n\nWe can just call this function whenever we want to get a random line from a .txt file.\nNow that we have a way to get a random line from a .txt file, we can implement this into discord.py.This is how you would create this command in discord.py\nimport random\nimport discord\nfrom discord.ext import commands\n\nFILE_NAME = \"\"\nYOUR_TOKEN = \"\"\nintents = discord.Intents.all()\nbot = commands.Bot(command_prefix=\">\", intents=intents)\n\n#The function that gets the random line\ndef random_line(fname):\n lines = open(fname).read().splitlines()\n return random.choice(lines)\n\n#Making the comand\n@bot.command()\nasync def randomline(ctx):\n await ctx.send(random_line(FILE_NAME))\n\nbot.run(YOUR_TOKEN)\n\nAnd remember to enable intents in the Developer Portal\nIf you would like to use nextcord just try to use the function that I gave you to make this command. I hope this helps and if there were any problems just let me kow.\n"
] |
[
0
] |
[] |
[] |
[
"discord.py",
"nextcord",
"python"
] |
stackoverflow_0074496961_discord.py_nextcord_python.txt
|
Q:
I cannot use opencv2 and received ImportError: libgl.so.1 cannot open shared object file no such file or directory
**env:**ubuntu16.04 anaconda3 python3.7.8 cuda10.0 gcc5.5
command:
conda activate myenv
python
import cv2
error:
Traceback (most recent call last):
File "", line 1, in
File "/home/.conda/envs/myenv/lib/python3.7/site-packages/cv2/__init__.py", line 5, in
from .cv2 import *
ImportError: libGL.so.1: cannot open shared object file: No such file or directory
I tried:
RUN apt install libgl1-mesa-glx -y
RUN apt-get install 'ffmpeg'\
'libsm6'\
'libxext6' -y
but this is already installed and the latest version(libgl1-mesa-glx18.0.5-0ubuntu0~16.04.1).
then i tried:
sudo apt-get install --reinstall libgl1-mesa-glx
it doesn't work.
finally,I tried to remove the package:
sudo apt-get --purge remove libgl1-mesa-glx
another error occurred:
Reading package list... Done
Analyzing the dependency tree of the package
Reading status information... Done
Some packages cannot be installed. If you are using an unstable distribution, this may be
Because the system cannot reach the state you requested. There may be some software you need in this version
The packages have not been created yet or they have been moved out of the Incoming directory.
The following information may be helpful in solving the problem:
The following packages have unmet dependencies:
libqt5multimedia5-plugins: Dependency: libqgsttools-p1 (>= 5.5.1) but it will not be installed
E: Error, pkgProblemResolver::Resolve failed. This may be due to a software package being required to maintain the status quo.
Any help would be really helpful.Thanks in advance.
conda list:
# packages in environment at /home/lwy/.conda/envs/mmdet1:
#
# Name Version Build Channel
_libgcc_mutex 0.1 conda_forge https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge
_openmp_mutex 4.5 1_gnu https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge
addict 2.3.0 <pip>
albumentations 0.5.1 <pip>
appdirs 1.4.4 <pip>
asynctest 0.13.0 <pip>
attrs 20.2.0 <pip>
ca-certificates 2020.6.20 hecda079_0 https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge
certifi 2020.6.20 py37he5f6b98_2 https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge
chardet 3.0.4 <pip>
cityscapesScripts 2.1.7 <pip>
codecov 2.1.10 <pip>
coloredlogs 14.0 <pip>
coverage 5.3 <pip>
cycler 0.10.0 <pip>
Cython 0.29.21 <pip>
decorator 4.4.2 <pip>
flake8 3.8.4 <pip>
future 0.18.2 <pip>
humanfriendly 8.2 <pip>
idna 2.10 <pip>
imagecorruptions 1.1.0 <pip>
imageio 2.9.0 <pip>
imgaug 0.4.0 <pip>
importlib-metadata 2.0.0 <pip>
iniconfig 1.1.1 <pip>
isort 5.6.4 <pip>
kiwisolver 1.3.1 <pip>
kwarray 0.5.10 <pip>
ld_impl_linux-64 2.35 h769bd43_9 https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge
libffi 3.2.1 1 https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free
libgcc-ng 9.3.0 h5dbcf3e_17 https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge
libgomp 9.3.0 h5dbcf3e_17 https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge
libstdcxx-ng 9.3.0 h2ae2ef3_17 https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge
matplotlib 3.3.2 <pip>
mccabe 0.6.1 <pip>
mmcv 1.1.6 <pip>
mmdet 1.2.0+unknown <pip>
ncurses 6.2 he1b5a44_2 https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge
networkx 2.5 <pip>
numpy 1.19.4 <pip>
opencv-python 4.4.0.46 <pip>
openssl 1.1.1h h516909a_0 https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge
ordered-set 4.0.2 <pip>
packaging 20.4 <pip>
Pillow 6.2.2 <pip>
pip 20.2.4 py_0 https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge
pluggy 0.13.1 <pip>
py 1.9.0 <pip>
pycocotools 2.0 <pip>
pycodestyle 2.6.0 <pip>
pyflakes 2.2.0 <pip>
pyparsing 2.4.7 <pip>
pyquaternion 0.9.9 <pip>
pytest 6.1.2 <pip>
pytest-cov 2.10.1 <pip>
pytest-runner 5.2 <pip>
python 3.7.8 h6f2ec95_1_cpython https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge
python-dateutil 2.8.1 <pip>
python_abi 3.7 1_cp37m https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge
PyWavelets 1.1.1 <pip>
PyYAML 5.3.1 <pip>
readline 8.0 he28a2e2_2 https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge
requests 2.24.0 <pip>
scikit-image 0.17.2 <pip>
scipy 1.5.3 <pip>
setuptools 49.6.0 py37he5f6b98_2 https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge
Shapely 1.7.1 <pip>
six 1.15.0 <pip>
sqlite 3.33.0 h4cf870e_1 https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge
tifffile 2020.10.1 <pip>
tk 8.6.10 hed695b0_1 https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge
toml 0.10.2 <pip>
torch 1.5.0+cu92 <pip>
torchvision 0.6.0+cu92 <pip>
tqdm 4.51.0 <pip>
typing 3.7.4.3 <pip>
ubelt 0.9.3 <pip>
urllib3 1.25.11 <pip>
wheel 0.35.1 pyh9f0ad1d_0 https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge
xdoctest 0.15.0 <pip>
xz 5.2.5 h516909a_1 https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge
yapf 0.30.0 <pip>
zipp 3.4.0 <pip>
zlib 1.2.11 0 https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free
A:
Usually these Pacakges are meant to be installed as System Packages and Not only Python packages. Therefore many times even after successfull installation of such packages like opencv, cmake, dlib they don't work.
The Best way is to Install them is using.
sudo apt-get install python3-opencv
This is the Preferred Method for the Successfull Installation of opencv on Ubuntu as per the Official Opencv Docs.
A:
I have solved this problem!
Firstly, find the file:
find /usr -name libGL.so.1
I found /usr/lib/x86_64-linux-gnu/mesa/libGL.so.1.
Then, I created a soft link:
ln -s /usr/lib/x86_64-linux-gnu/mesa/libGL.so.1 /usr/lib/libGL.so.1
Finally, I verified that it is valid:
# python
import cv2
A:
I was able to solve the issue by
apt-get install libgl1
|
I cannot use opencv2 and received ImportError: libgl.so.1 cannot open shared object file no such file or directory
|
**env:**ubuntu16.04 anaconda3 python3.7.8 cuda10.0 gcc5.5
command:
conda activate myenv
python
import cv2
error:
Traceback (most recent call last):
File "", line 1, in
File "/home/.conda/envs/myenv/lib/python3.7/site-packages/cv2/__init__.py", line 5, in
from .cv2 import *
ImportError: libGL.so.1: cannot open shared object file: No such file or directory
I tried:
RUN apt install libgl1-mesa-glx -y
RUN apt-get install 'ffmpeg'\
'libsm6'\
'libxext6' -y
but this is already installed and the latest version(libgl1-mesa-glx18.0.5-0ubuntu0~16.04.1).
then i tried:
sudo apt-get install --reinstall libgl1-mesa-glx
it doesn't work.
finally,I tried to remove the package:
sudo apt-get --purge remove libgl1-mesa-glx
another error occurred:
Reading package list... Done
Analyzing the dependency tree of the package
Reading status information... Done
Some packages cannot be installed. If you are using an unstable distribution, this may be
Because the system cannot reach the state you requested. There may be some software you need in this version
The packages have not been created yet or they have been moved out of the Incoming directory.
The following information may be helpful in solving the problem:
The following packages have unmet dependencies:
libqt5multimedia5-plugins: Dependency: libqgsttools-p1 (>= 5.5.1) but it will not be installed
E: Error, pkgProblemResolver::Resolve failed. This may be due to a software package being required to maintain the status quo.
Any help would be really helpful.Thanks in advance.
conda list:
# packages in environment at /home/lwy/.conda/envs/mmdet1:
#
# Name Version Build Channel
_libgcc_mutex 0.1 conda_forge https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge
_openmp_mutex 4.5 1_gnu https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge
addict 2.3.0 <pip>
albumentations 0.5.1 <pip>
appdirs 1.4.4 <pip>
asynctest 0.13.0 <pip>
attrs 20.2.0 <pip>
ca-certificates 2020.6.20 hecda079_0 https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge
certifi 2020.6.20 py37he5f6b98_2 https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge
chardet 3.0.4 <pip>
cityscapesScripts 2.1.7 <pip>
codecov 2.1.10 <pip>
coloredlogs 14.0 <pip>
coverage 5.3 <pip>
cycler 0.10.0 <pip>
Cython 0.29.21 <pip>
decorator 4.4.2 <pip>
flake8 3.8.4 <pip>
future 0.18.2 <pip>
humanfriendly 8.2 <pip>
idna 2.10 <pip>
imagecorruptions 1.1.0 <pip>
imageio 2.9.0 <pip>
imgaug 0.4.0 <pip>
importlib-metadata 2.0.0 <pip>
iniconfig 1.1.1 <pip>
isort 5.6.4 <pip>
kiwisolver 1.3.1 <pip>
kwarray 0.5.10 <pip>
ld_impl_linux-64 2.35 h769bd43_9 https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge
libffi 3.2.1 1 https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free
libgcc-ng 9.3.0 h5dbcf3e_17 https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge
libgomp 9.3.0 h5dbcf3e_17 https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge
libstdcxx-ng 9.3.0 h2ae2ef3_17 https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge
matplotlib 3.3.2 <pip>
mccabe 0.6.1 <pip>
mmcv 1.1.6 <pip>
mmdet 1.2.0+unknown <pip>
ncurses 6.2 he1b5a44_2 https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge
networkx 2.5 <pip>
numpy 1.19.4 <pip>
opencv-python 4.4.0.46 <pip>
openssl 1.1.1h h516909a_0 https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge
ordered-set 4.0.2 <pip>
packaging 20.4 <pip>
Pillow 6.2.2 <pip>
pip 20.2.4 py_0 https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge
pluggy 0.13.1 <pip>
py 1.9.0 <pip>
pycocotools 2.0 <pip>
pycodestyle 2.6.0 <pip>
pyflakes 2.2.0 <pip>
pyparsing 2.4.7 <pip>
pyquaternion 0.9.9 <pip>
pytest 6.1.2 <pip>
pytest-cov 2.10.1 <pip>
pytest-runner 5.2 <pip>
python 3.7.8 h6f2ec95_1_cpython https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge
python-dateutil 2.8.1 <pip>
python_abi 3.7 1_cp37m https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge
PyWavelets 1.1.1 <pip>
PyYAML 5.3.1 <pip>
readline 8.0 he28a2e2_2 https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge
requests 2.24.0 <pip>
scikit-image 0.17.2 <pip>
scipy 1.5.3 <pip>
setuptools 49.6.0 py37he5f6b98_2 https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge
Shapely 1.7.1 <pip>
six 1.15.0 <pip>
sqlite 3.33.0 h4cf870e_1 https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge
tifffile 2020.10.1 <pip>
tk 8.6.10 hed695b0_1 https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge
toml 0.10.2 <pip>
torch 1.5.0+cu92 <pip>
torchvision 0.6.0+cu92 <pip>
tqdm 4.51.0 <pip>
typing 3.7.4.3 <pip>
ubelt 0.9.3 <pip>
urllib3 1.25.11 <pip>
wheel 0.35.1 pyh9f0ad1d_0 https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge
xdoctest 0.15.0 <pip>
xz 5.2.5 h516909a_1 https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge
yapf 0.30.0 <pip>
zipp 3.4.0 <pip>
zlib 1.2.11 0 https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free
|
[
"Usually these Pacakges are meant to be installed as System Packages and Not only Python packages. Therefore many times even after successfull installation of such packages like opencv, cmake, dlib they don't work.\nThe Best way is to Install them is using.\nsudo apt-get install python3-opencv\n\nThis is the Preferred Method for the Successfull Installation of opencv on Ubuntu as per the Official Opencv Docs.\n",
"I have solved this problem!\nFirstly, find the file:\nfind /usr -name libGL.so.1\n\nI found /usr/lib/x86_64-linux-gnu/mesa/libGL.so.1.\nThen, I created a soft link:\nln -s /usr/lib/x86_64-linux-gnu/mesa/libGL.so.1 /usr/lib/libGL.so.1\n\nFinally, I verified that it is valid:\n# python\nimport cv2\n\n",
"I was able to solve the issue by\napt-get install libgl1 \n\n"
] |
[
5,
1,
0
] |
[] |
[] |
[
"anaconda3",
"importerror",
"opencv",
"python",
"ubuntu_16.04"
] |
stackoverflow_0064664094_anaconda3_importerror_opencv_python_ubuntu_16.04.txt
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.