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:
Why is this blitting two times?
I am trying to make a microsoft paint like program using pygame, however im running into an issue while trying to create "stickers".
my sticker code looks like:
if canvasRect.collidepoint(mx,my) and mb[0]:
for j in range(12,len(tools)):
screen.set_clip(canvasRect)
if tool==tools[j]:
for i in range(len(stampNames)):
stickers=image.load(stampNames[i])
wid=stickers.get_width()
hei=stickers.get_height()
if mb[0]:
screen.blit(stickers,(mx-wid//2,my-hei//2))
and i have two lists related to the code above being:
tools=["brush","eraser","pencil","line","load","save","spraypaint","bucket","clear","ellipse","fillellipse","box","fillbox","Lewy","Neuer"]
and:
stampNames=["icons/lewy.png","icons/neuer.png"]
how could i make stop it from "blitting" two times and prevent it from blitting multiple times when i update the list with more.
A:
It's pretty difficult to determine what it is you want from the small snippet of code, but I'm guessing the desire is:
If the mouse-button-1 is clicked mb[0], draw a "stamp" (AKA "sticker") at the mouse-cordinates mx,my.
It looks like your code is drawing the image as the click is made. As I said in a comment, this is not a good approach. PyGame is an "event driven" system, and generally this means the code needs to react to user-input events to update an internal model, and then render that model to the window.
So in terms of clicking the mouse to place a "stamp", it would be better to simply remember the stamp-type and the position clicked. These can then be painted later in the update loop.
But first we need a list of stickers to stamp. Here's a snippet of code that will iterate over a list of sticker-names, creating a python dictionary of images. So later stickers[ "sticker1" ] gets an Image:
stickers = {} # dictionary of stickers, by name
for sticker_name in [ "sticker1", "sticker2", "sticker3" ]:
filename += sticker_name + ".png"
try:
sticker_image = pygame.image.load( filename ).convert_alpha()
stickers[ sticker_name ] = sticker_image
except:
print( "Failed to load sticker [" + sticker_name + "]" )
Probably you have some method of remembering the user's selected sticker-name. I'm going to assume this is the variable current_sticker.
current_sticker = stickers.keys()[0] # default to first sticker
Now handle the mouse-click by remembering the sticker name, and the mouse-position into the list placed_stickers:
placed_stickers = [] # initially empty
# ...
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.MOUSEBUTTONUP: # mouse button released
if event.button == 1:
mx, my = pygame.mouse.get_pos()
sticker_position = stickers[current_sticker].get_rect( topleft=(mx,my) )
placed_stickers.append( [ sticker_position, current_sticker ] )
So in this manner, when mouse-button-1 is released, the placed_stickers list will get a new list-entry like [ [100, 122, 64, 64], "sticker1" ]. (So placed_stickers is a list of lists).
Then when painting the window, iterate through placed_stickers, blitting each one:
# paint screen
window.fill( background_colour )
for placement in placed_stickers:
position, sticker_name = placement
sticker_image = stickers[ sticker_name ]
window.blit( sticker_image, position ) # <<== paint each sticker
If there's an option to erase a sticker, it should be pretty easy to iterate through the same list, finding which rectangle was clicked in by testing collision against the mouse point.
|
Why is this blitting two times?
|
I am trying to make a microsoft paint like program using pygame, however im running into an issue while trying to create "stickers".
my sticker code looks like:
if canvasRect.collidepoint(mx,my) and mb[0]:
for j in range(12,len(tools)):
screen.set_clip(canvasRect)
if tool==tools[j]:
for i in range(len(stampNames)):
stickers=image.load(stampNames[i])
wid=stickers.get_width()
hei=stickers.get_height()
if mb[0]:
screen.blit(stickers,(mx-wid//2,my-hei//2))
and i have two lists related to the code above being:
tools=["brush","eraser","pencil","line","load","save","spraypaint","bucket","clear","ellipse","fillellipse","box","fillbox","Lewy","Neuer"]
and:
stampNames=["icons/lewy.png","icons/neuer.png"]
how could i make stop it from "blitting" two times and prevent it from blitting multiple times when i update the list with more.
|
[
"It's pretty difficult to determine what it is you want from the small snippet of code, but I'm guessing the desire is:\n\nIf the mouse-button-1 is clicked mb[0], draw a \"stamp\" (AKA \"sticker\") at the mouse-cordinates mx,my.\n\nIt looks like your code is drawing the image as the click is made. As I said in a comment, this is not a good approach. PyGame is an \"event driven\" system, and generally this means the code needs to react to user-input events to update an internal model, and then render that model to the window.\nSo in terms of clicking the mouse to place a \"stamp\", it would be better to simply remember the stamp-type and the position clicked. These can then be painted later in the update loop.\nBut first we need a list of stickers to stamp. Here's a snippet of code that will iterate over a list of sticker-names, creating a python dictionary of images. So later stickers[ \"sticker1\" ] gets an Image:\nstickers = {} # dictionary of stickers, by name\nfor sticker_name in [ \"sticker1\", \"sticker2\", \"sticker3\" ]:\n filename += sticker_name + \".png\"\n try:\n sticker_image = pygame.image.load( filename ).convert_alpha()\n stickers[ sticker_name ] = sticker_image\n except:\n print( \"Failed to load sticker [\" + sticker_name + \"]\" )\n\nProbably you have some method of remembering the user's selected sticker-name. I'm going to assume this is the variable current_sticker.\ncurrent_sticker = stickers.keys()[0] # default to first sticker\n\nNow handle the mouse-click by remembering the sticker name, and the mouse-position into the list placed_stickers:\nplaced_stickers = [] # initially empty\n\n# ...\n\nwhile running:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False \n elif event.type == pygame.MOUSEBUTTONUP: # mouse button released\n if event.button == 1:\n mx, my = pygame.mouse.get_pos()\n sticker_position = stickers[current_sticker].get_rect( topleft=(mx,my) )\n placed_stickers.append( [ sticker_position, current_sticker ] )\n\nSo in this manner, when mouse-button-1 is released, the placed_stickers list will get a new list-entry like [ [100, 122, 64, 64], \"sticker1\" ]. (So placed_stickers is a list of lists).\nThen when painting the window, iterate through placed_stickers, blitting each one:\n# paint screen\nwindow.fill( background_colour )\nfor placement in placed_stickers:\n position, sticker_name = placement\n sticker_image = stickers[ sticker_name ]\n window.blit( sticker_image, position ) # <<== paint each sticker\n\nIf there's an option to erase a sticker, it should be pretty easy to iterate through the same list, finding which rectangle was clicked in by testing collision against the mouse point.\n"
] |
[
0
] |
[] |
[] |
[
"pygame",
"python"
] |
stackoverflow_0074503479_pygame_python.txt
|
Q:
Labeling year on time series
I am working on a timeseries plot from data that looks like the following:
import pandas as pd
data = {'index': [1, 34, 78, 900, 1200, 5000, 9001, 12000, 15234, 23432],
'rating': [90, 85, 89, 82, 78, 65, 54, 32, 39, 45],
'Year': [2005, 2005, 2005, 2006, 2006, 2006, 2007, 2008, 2009, 2009]}
df = pd.DataFrame(data)
The main issue is the lack of actual dates. I have plotted the data using the index order - the data is sorted in index-ascending order, the value of the index is meaningless.
I have plotted the data using
import plotly.express as px
fig = px.line(df, x='index', y='rating')
fig.show()
but would like to shade or label each year on the plot (could just be vertical dotted lines separating years, or alternated grey shades beneath the line but above the axis per year).
A:
I am assuming that you have already sorted the DataFrame using the index column.
Here's a solution using bar (column) chart using matplotlib.
import matplotlib.pyplot as plt
import numpy as np
# [optional] create a dictionary of colors with year as keys. It is better if this is dynamically generated if you have a lot of years.
color_cycle = {'2005': 'red', '2006': 'blue', '2007': 'green', '2008': 'orange', '2009': 'purple'}
# I am assuming that the rating data is sorted by index already
# plot rating as a column chart using equal spacing on the x-axis
plt.bar(x=np.arange(len(df)), height=df['rating'], width=0.8, color=[color_cycle[str(year)] for year in df['Year']])
# add Year as x-axis labels
plt.xticks(np.arange(len(df)), df['Year'])
# add labels to the axes
plt.xlabel('Year')
plt.ylabel('Rating')
# display the plot
plt.show()
Outputs
|
Labeling year on time series
|
I am working on a timeseries plot from data that looks like the following:
import pandas as pd
data = {'index': [1, 34, 78, 900, 1200, 5000, 9001, 12000, 15234, 23432],
'rating': [90, 85, 89, 82, 78, 65, 54, 32, 39, 45],
'Year': [2005, 2005, 2005, 2006, 2006, 2006, 2007, 2008, 2009, 2009]}
df = pd.DataFrame(data)
The main issue is the lack of actual dates. I have plotted the data using the index order - the data is sorted in index-ascending order, the value of the index is meaningless.
I have plotted the data using
import plotly.express as px
fig = px.line(df, x='index', y='rating')
fig.show()
but would like to shade or label each year on the plot (could just be vertical dotted lines separating years, or alternated grey shades beneath the line but above the axis per year).
|
[
"I am assuming that you have already sorted the DataFrame using the index column.\nHere's a solution using bar (column) chart using matplotlib.\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# [optional] create a dictionary of colors with year as keys. It is better if this is dynamically generated if you have a lot of years.\ncolor_cycle = {'2005': 'red', '2006': 'blue', '2007': 'green', '2008': 'orange', '2009': 'purple'}\n\n# I am assuming that the rating data is sorted by index already\n\n# plot rating as a column chart using equal spacing on the x-axis\nplt.bar(x=np.arange(len(df)), height=df['rating'], width=0.8, color=[color_cycle[str(year)] for year in df['Year']])\n\n# add Year as x-axis labels\nplt.xticks(np.arange(len(df)), df['Year'])\n# add labels to the axes\nplt.xlabel('Year')\nplt.ylabel('Rating')\n\n# display the plot\nplt.show()\n\nOutputs\n\n"
] |
[
1
] |
[] |
[] |
[
"data_analysis",
"numpy",
"plotly",
"python",
"time_series"
] |
stackoverflow_0074525913_data_analysis_numpy_plotly_python_time_series.txt
|
Q:
Websites using scrapy-playwright and only playwright work differently
I am trying to log into a webpage using scrapy-playwright, as I want the nice integration with scrapy. I can't log in using scrapy-playwright, as it redirects to a page that does not exist. I have also tried doing a post request instead of clicking, that doesn't work either.
However, if I try the same thing using only Playwright, it works perfectly... Is there a difference between websites opened with scrapy-playwright compared to only Playwright? And does anyone know how to solve this using scrapy-playwright?
scrapy-playwright code:
def start_requests(self):
yield scrapy.Request(
url = self.url,
meta = dict(
playwright = True,
playwright_include_page = True,
playwright_page_methods = [PageMethod('wait_for_selector', 'a[data-toggle=dropdown]')],
),
callback = self.sign_in,
)
async def sign_in(self, response):
page = response.meta['playwright_page']
while await page.is_visible("button[class='close close-news']"):
await page.click("button[class='close close-news']")
await page.click('button#declineAllConsentSummary')
await page.click('div.my-account-sub > a[data-toggle=dropdown]', timeout=10000)
await page.fill('input#j_username_header', os.getenv(self.usernameKey), timeout=10000)
await page.fill('input#j_password_header', os.getenv(self.passwordKey), timeout=10000)
await page.click('button#responsiveMyAccLoginGA')
Playwright code:
async def test_async_playwright(self):
async with async_playwright() as playwright:
browser = await playwright.chromium.launch(headless=False)
context = await browser.new_context(base_url=self.url)
page = await context.new_page()
await page.goto(self.url, wait_until='commit')
while await page.is_visible("button[class='close close-news']"):
await page.click("button[class='close close-news']")
await page.click('button#declineAllConsentSummary')
await page.wait_for_selector('a[data-toggle=dropdown]')
await page.click('div.my-account-sub > a[data-toggle=dropdown]', timeout=5000)
await page.fill('input#j_username_header', os.getenv(self.usernameKey), timeout=5000)
await page.fill('input#j_password_header', os.getenv(self.passwordKey), timeout=5000)
await page.click('button#responsiveMyAccLoginGA')
A:
As a possible workaround, if you are redirected(to the broken page) after the token/cookie is granted, you can as well navigate to a normal site url, and you should be logged in
|
Websites using scrapy-playwright and only playwright work differently
|
I am trying to log into a webpage using scrapy-playwright, as I want the nice integration with scrapy. I can't log in using scrapy-playwright, as it redirects to a page that does not exist. I have also tried doing a post request instead of clicking, that doesn't work either.
However, if I try the same thing using only Playwright, it works perfectly... Is there a difference between websites opened with scrapy-playwright compared to only Playwright? And does anyone know how to solve this using scrapy-playwright?
scrapy-playwright code:
def start_requests(self):
yield scrapy.Request(
url = self.url,
meta = dict(
playwright = True,
playwright_include_page = True,
playwright_page_methods = [PageMethod('wait_for_selector', 'a[data-toggle=dropdown]')],
),
callback = self.sign_in,
)
async def sign_in(self, response):
page = response.meta['playwright_page']
while await page.is_visible("button[class='close close-news']"):
await page.click("button[class='close close-news']")
await page.click('button#declineAllConsentSummary')
await page.click('div.my-account-sub > a[data-toggle=dropdown]', timeout=10000)
await page.fill('input#j_username_header', os.getenv(self.usernameKey), timeout=10000)
await page.fill('input#j_password_header', os.getenv(self.passwordKey), timeout=10000)
await page.click('button#responsiveMyAccLoginGA')
Playwright code:
async def test_async_playwright(self):
async with async_playwright() as playwright:
browser = await playwright.chromium.launch(headless=False)
context = await browser.new_context(base_url=self.url)
page = await context.new_page()
await page.goto(self.url, wait_until='commit')
while await page.is_visible("button[class='close close-news']"):
await page.click("button[class='close close-news']")
await page.click('button#declineAllConsentSummary')
await page.wait_for_selector('a[data-toggle=dropdown]')
await page.click('div.my-account-sub > a[data-toggle=dropdown]', timeout=5000)
await page.fill('input#j_username_header', os.getenv(self.usernameKey), timeout=5000)
await page.fill('input#j_password_header', os.getenv(self.passwordKey), timeout=5000)
await page.click('button#responsiveMyAccLoginGA')
|
[
"As a possible workaround, if you are redirected(to the broken page) after the token/cookie is granted, you can as well navigate to a normal site url, and you should be logged in\n"
] |
[
0
] |
[] |
[] |
[
"playwright",
"playwright_python",
"python",
"scrapy",
"web_scraping"
] |
stackoverflow_0072375388_playwright_playwright_python_python_scrapy_web_scraping.txt
|
Q:
Railway.app: Is Procfile Successfully Loading a Worker?
Migrating from Heroku to Railway.app: Python Flask app with Redis and Postgres. Using Redis as an asynchronous job queue, with the RQ Redis queue python library.
Procfile, which works in dev, looks like this:
web: gunicorn app:app
worker: rq worker --with-scheduler
The last line of the Deploy log looks as if the worker is loading:
[2022-10-07 22:33:46 +0000] [1] [INFO] Starting gunicorn 20.0.4
[2022-10-07 22:33:46 +0000] [1] [INFO] Listening at: http://0.0.0.0:6040/ (1)
[2022-10-07 22:33:46 +0000] [1] [INFO] Using worker: sync
[2022-10-07 22:33:46 +0000] [11] [INFO] Booting worker with pid: 11
However, none of my Redis-enqueued jobs are starting. It's as if the worker process does not exist. Railway's documentation says little except that Procfiles are supported.
Because there is no SSH, I cannot look at the live processes to see if the worker is running. Other than in the deploy log, I don't see any evidence of a worker process. Redis queue works successfully in the dev environment, and the staging/production environments are successfully addressing the correct Redis URLs.
How can I check to see if the Procfile-started worker process on a railway service is indeed live? Has anyone else had trouble starting workers from the Procfile on Railway.app? What might I be missing?
A:
You can use docker deployment.
|
Railway.app: Is Procfile Successfully Loading a Worker?
|
Migrating from Heroku to Railway.app: Python Flask app with Redis and Postgres. Using Redis as an asynchronous job queue, with the RQ Redis queue python library.
Procfile, which works in dev, looks like this:
web: gunicorn app:app
worker: rq worker --with-scheduler
The last line of the Deploy log looks as if the worker is loading:
[2022-10-07 22:33:46 +0000] [1] [INFO] Starting gunicorn 20.0.4
[2022-10-07 22:33:46 +0000] [1] [INFO] Listening at: http://0.0.0.0:6040/ (1)
[2022-10-07 22:33:46 +0000] [1] [INFO] Using worker: sync
[2022-10-07 22:33:46 +0000] [11] [INFO] Booting worker with pid: 11
However, none of my Redis-enqueued jobs are starting. It's as if the worker process does not exist. Railway's documentation says little except that Procfiles are supported.
Because there is no SSH, I cannot look at the live processes to see if the worker is running. Other than in the deploy log, I don't see any evidence of a worker process. Redis queue works successfully in the dev environment, and the staging/production environments are successfully addressing the correct Redis URLs.
How can I check to see if the Procfile-started worker process on a railway service is indeed live? Has anyone else had trouble starting workers from the Procfile on Railway.app? What might I be missing?
|
[
"You can use docker deployment.\n"
] |
[
0
] |
[] |
[] |
[
"flask",
"python",
"python_3.x",
"redis",
"rq"
] |
stackoverflow_0073998727_flask_python_python_3.x_redis_rq.txt
|
Q:
PuLP not printing output on IPython cell
I am using PuLP and IPython/Jupyter Notebook for a project.
I have the following cell of code:
import pulp
model = pulp.LpProblem('Example', pulp.LpMinimize)
x1 = pulp.LpVariable('x1', lowBound=0, cat='Integer')
x2 = pulp.LpVariable('x2', lowBound=0, cat='Integer')
model += -2*x1 - 3*x2
model += x1 + 2*x2 <= 7
model += 2*x1 + x2 <= 7
model.solve(pulp.solvers.COIN(msg=True))
When I execute the cell, the output is simply:
1
When I look at the terminal running the Notebook server, I can see the output of the solver (in this case: COIN). The same happens if a change the model.solve argument to
model.solve(pulp.solvers.PULP_CBC_CMD(msg=True))
or
model.solve(pulp.solvers.PYGLPK(msg=True))
However, when I use the Gurobi Solver, with the line
model.solve(pulp.solvers.GUROBI(msg=True))
the output of the solver is displayed on the Notebook cell, which is the behavior I want. In fact, I would be happy with any free solver printing its output directly on the Notebook cell.
I could not find directions on how to approach this issue in PuLP documentation. Any help would be appreciated. I am also curious to know if someone else gets this behavior.
I am using Linux Mint, 64 Bits, IPython 4.0.0 and PuLP 1.6.0.
A:
Use %%python cell magic to print terminal's output.
%%python
import pulp
model = pulp.LpProblem('Example', pulp.LpMinimize)
x1 = pulp.LpVariable('x1', lowBound=0, cat='Integer')
x2 = pulp.LpVariable('x2', lowBound=0, cat='Integer')
model += -2*x1 - 3*x2
model += x1 + 2*x2 <= 7
model += 2*x1 + x2 <= 7
model.solve(pulp.solvers.COIN(msg=True))
A:
Late to the party, but for anyone still looking for a solution...
Create a file called monkeypatch.py and put it in the same directory as your notebooks
Paste the following into it, and save
from pulp import PULP_CBC_CMD, LpProblem
original_solve_method = LpProblem.solve
def solve(prob):
solver = PULP_CBC_CMD(logPath=r'log.txt', msg=False)
original_solve_method(prob, solver=solver)
with open('log.txt', 'r') as f:
print(f.read())
LpProblem.solve = solve
Then in your notebook insert the line
import monkeypatch
near the top.
It will overwrite the solve method, so that it writes the logfile to "log.txt" and then reads in this file and displays it inside the notebook.
|
PuLP not printing output on IPython cell
|
I am using PuLP and IPython/Jupyter Notebook for a project.
I have the following cell of code:
import pulp
model = pulp.LpProblem('Example', pulp.LpMinimize)
x1 = pulp.LpVariable('x1', lowBound=0, cat='Integer')
x2 = pulp.LpVariable('x2', lowBound=0, cat='Integer')
model += -2*x1 - 3*x2
model += x1 + 2*x2 <= 7
model += 2*x1 + x2 <= 7
model.solve(pulp.solvers.COIN(msg=True))
When I execute the cell, the output is simply:
1
When I look at the terminal running the Notebook server, I can see the output of the solver (in this case: COIN). The same happens if a change the model.solve argument to
model.solve(pulp.solvers.PULP_CBC_CMD(msg=True))
or
model.solve(pulp.solvers.PYGLPK(msg=True))
However, when I use the Gurobi Solver, with the line
model.solve(pulp.solvers.GUROBI(msg=True))
the output of the solver is displayed on the Notebook cell, which is the behavior I want. In fact, I would be happy with any free solver printing its output directly on the Notebook cell.
I could not find directions on how to approach this issue in PuLP documentation. Any help would be appreciated. I am also curious to know if someone else gets this behavior.
I am using Linux Mint, 64 Bits, IPython 4.0.0 and PuLP 1.6.0.
|
[
"Use %%python cell magic to print terminal's output.\n%%python\nimport pulp\nmodel = pulp.LpProblem('Example', pulp.LpMinimize)\nx1 = pulp.LpVariable('x1', lowBound=0, cat='Integer')\nx2 = pulp.LpVariable('x2', lowBound=0, cat='Integer')\n\nmodel += -2*x1 - 3*x2 \nmodel += x1 + 2*x2 <= 7\nmodel += 2*x1 + x2 <= 7\n\nmodel.solve(pulp.solvers.COIN(msg=True))\n\n",
"Late to the party, but for anyone still looking for a solution...\nCreate a file called monkeypatch.py and put it in the same directory as your notebooks\nPaste the following into it, and save\nfrom pulp import PULP_CBC_CMD, LpProblem\n\noriginal_solve_method = LpProblem.solve\n\ndef solve(prob):\n solver = PULP_CBC_CMD(logPath=r'log.txt', msg=False)\n original_solve_method(prob, solver=solver)\n with open('log.txt', 'r') as f:\n print(f.read())\n\nLpProblem.solve = solve\n\nThen in your notebook insert the line\nimport monkeypatch\n\nnear the top.\nIt will overwrite the solve method, so that it writes the logfile to \"log.txt\" and then reads in this file and displays it inside the notebook.\n"
] |
[
1,
0
] |
[] |
[] |
[
"ipython_notebook",
"mathematical_optimization",
"pulp",
"python"
] |
stackoverflow_0034475510_ipython_notebook_mathematical_optimization_pulp_python.txt
|
Q:
Split Polygons by Overlap in Python
I have the Json data that I want to Split by overlap polygons
data_01 = {
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "Polygon",
"coordinates": [
[[2, 2], [2, 22], [22, 22], [22, 2], [2, 2]]
]
},
"properties": {"z": 1412.5, "la": "ba"}
},
{
"type": "Feature",
"geometry": {
"type": "Polygon",
"coordinates": [
[[12, 16], [7, 10], [17, 10], [12, 16]]
]
},
"properties": {"z": 1412.5, "la": "ba"}
},
{
"type": "Feature",
"geometry": {
"type": "Polygon",
"coordinates": [
[[27, 15], [24, 12], [29, 12], [27, 15]]
]
},
"properties": {"z": 1412.5, "la": "ba"}
}
]
}
I would like to get the data where data from Poly_1 and 2 should be joined like data_final:
I try to read data
import json
with open("data_01.json", 'r', encoding='utf-8-sig') as fh:
d = fh.read()
f = json.loads(d)
j = f['features'][0:]
for i in j:
poly_coord = i['geometry']['coordinates'][0:]
poly_coord = poly_coord[0]
print(poly_coord )
data_final = {
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "Polygon",
"coordinates": [
[[27, 15], [24, 12], [29, 12], [27, 15]]
]
},
"properties": {"z": 1412.5, "la": "ba"}
},
{
"type": "Feature",
"geometry": {
"type": "Polygon",
"coordinates": [
[[2, 2], [2, 22], [22, 22], [22, 2], [2, 2]],
[[12, 16], [7, 10], [17, 10], [12, 16]]
]
},
"properties": {"z": 1412.5, "la": "ba"}
}
]
}
A:
You can read/write GeoJSON objects and do spatial set operations like this with geopandas:
In [8]: df = gpd.read_file("data_01.json", engine="GeoJSON")
In [9]: df
Out[9]:
z la geometry
0 1412.5 ba POLYGON ((2.00000 2.00000, 2.00000 22.00000, 2...
1 1412.5 ba POLYGON ((12.00000 16.00000, 7.00000 10.00000,...
2 1412.5 ba POLYGON ((27.00000 15.00000, 24.00000 12.00000...
In [10]: df.loc[0, "geometry"] = (df.loc[0, "geometry"] - df.loc[1, "geometry"])
In [11]: df = df.drop(1)
In [12]:
Out[12]:
z la geometry
0 1412.5 ba POLYGON ((2.00000 22.00000, 22.00000 22.00000,...
2 1412.5 ba POLYGON ((27.00000 15.00000, 24.00000 12.00000...
You can then export back to json with to_json:
In [13]: print(df.to_json())
Out[13]:
{
"type": "FeatureCollection",
"features": [
{
"id": "0",
"type": "Feature",
"properties": {"la": "ba", "z": 1412.5},
"geometry": {
"type": "Polygon",
"coordinates": [
[[2.0, 22.0], [22.0, 22.0], [22.0, 2.0], [2.0, 2.0], [2.0, 22.0]],
[[7.0, 10.0], [17.0, 10.0], [12.0, 16.0], [7.0, 10.0]]
]
}
},
{
"id": "2",
"type": "Feature",
"properties": {"la": "ba", "z": 1412.5},
"geometry": {
"type": "Polygon",
"coordinates": [
[[27.0, 15.0], [24.0, 12.0], [29.0, 12.0], [27.0, 15.0]]
]
}
}
]
}
|
Split Polygons by Overlap in Python
|
I have the Json data that I want to Split by overlap polygons
data_01 = {
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "Polygon",
"coordinates": [
[[2, 2], [2, 22], [22, 22], [22, 2], [2, 2]]
]
},
"properties": {"z": 1412.5, "la": "ba"}
},
{
"type": "Feature",
"geometry": {
"type": "Polygon",
"coordinates": [
[[12, 16], [7, 10], [17, 10], [12, 16]]
]
},
"properties": {"z": 1412.5, "la": "ba"}
},
{
"type": "Feature",
"geometry": {
"type": "Polygon",
"coordinates": [
[[27, 15], [24, 12], [29, 12], [27, 15]]
]
},
"properties": {"z": 1412.5, "la": "ba"}
}
]
}
I would like to get the data where data from Poly_1 and 2 should be joined like data_final:
I try to read data
import json
with open("data_01.json", 'r', encoding='utf-8-sig') as fh:
d = fh.read()
f = json.loads(d)
j = f['features'][0:]
for i in j:
poly_coord = i['geometry']['coordinates'][0:]
poly_coord = poly_coord[0]
print(poly_coord )
data_final = {
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "Polygon",
"coordinates": [
[[27, 15], [24, 12], [29, 12], [27, 15]]
]
},
"properties": {"z": 1412.5, "la": "ba"}
},
{
"type": "Feature",
"geometry": {
"type": "Polygon",
"coordinates": [
[[2, 2], [2, 22], [22, 22], [22, 2], [2, 2]],
[[12, 16], [7, 10], [17, 10], [12, 16]]
]
},
"properties": {"z": 1412.5, "la": "ba"}
}
]
}
|
[
"You can read/write GeoJSON objects and do spatial set operations like this with geopandas:\nIn [8]: df = gpd.read_file(\"data_01.json\", engine=\"GeoJSON\")\n\nIn [9]: df\nOut[9]:\n z la geometry\n0 1412.5 ba POLYGON ((2.00000 2.00000, 2.00000 22.00000, 2...\n1 1412.5 ba POLYGON ((12.00000 16.00000, 7.00000 10.00000,...\n2 1412.5 ba POLYGON ((27.00000 15.00000, 24.00000 12.00000...\n\nIn [10]: df.loc[0, \"geometry\"] = (df.loc[0, \"geometry\"] - df.loc[1, \"geometry\"])\n\nIn [11]: df = df.drop(1)\n\nIn [12]:\nOut[12]:\n z la geometry\n0 1412.5 ba POLYGON ((2.00000 22.00000, 22.00000 22.00000,...\n2 1412.5 ba POLYGON ((27.00000 15.00000, 24.00000 12.00000...\n\nYou can then export back to json with to_json:\nIn [13]: print(df.to_json())\nOut[13]: \n{\n \"type\": \"FeatureCollection\",\n \"features\": [\n {\n \"id\": \"0\",\n \"type\": \"Feature\",\n \"properties\": {\"la\": \"ba\", \"z\": 1412.5},\n \"geometry\": {\n \"type\": \"Polygon\",\n \"coordinates\": [\n [[2.0, 22.0], [22.0, 22.0], [22.0, 2.0], [2.0, 2.0], [2.0, 22.0]],\n [[7.0, 10.0], [17.0, 10.0], [12.0, 16.0], [7.0, 10.0]]\n ]\n }\n },\n {\n \"id\": \"2\",\n \"type\": \"Feature\",\n \"properties\": {\"la\": \"ba\", \"z\": 1412.5},\n \"geometry\": {\n \"type\": \"Polygon\",\n \"coordinates\": [\n [[27.0, 15.0], [24.0, 12.0], [29.0, 12.0], [27.0, 15.0]]\n ]\n }\n }\n ]\n}\n\n"
] |
[
0
] |
[] |
[] |
[
"json",
"polygon",
"python"
] |
stackoverflow_0074526297_json_polygon_python.txt
|
Q:
seeming memory leak in numpy for Mac?
I used the following process the generate a numpy array with size = (720, 720, 3). In principle, it should cost 720 * 720 * 3 * 8Byte = 12.3MB. However, in the ans = memory_benchmark(), it costs 188 MB. Why does it cost much more memory than expected? I think it should have same cost as the line m1 = np.ones((720, 720, 3)).
I have following two Environments. Both have same problem.
Environment1: numpy=1.23.4, memory_profiler=0.61.0, python=3.10.6, MacOS 12.6.1(Intel not M1)
Environment2: numpy=1.19.5, memory_profiler=0.61.0, python=3.8.15, MacOS 12.6.1(Intel not M1)
I did memory profile in the following
import numpy as np
from memory_profiler import profile
@profile
def memory_benchmark():
m1 = np.ones((720, 720, 3))
m2 = np.random.randint(128, size=(720, 720, 77, 3))
a = m2[:, :, :, 0].astype(np.uint16)
b = m2[:, :, :, 1].astype(np.uint16)
ans = np.array(m1[b, a].sum(axis=2))
m2 = None
a = None
b = None
m1 = None
return ans
@profile
def f():
ans = memory_benchmark()
print(ans.shape)
print("finished")
if __name__ == '__main__':
f()
(720, 720, 3)
finished
Line # Mem usage Increment Occurrences Line Contents
=============================================================
5 59.3 MiB 59.3 MiB 1 @profile
6 def memory_benchmark():
7 71.2 MiB 11.9 MiB 1 m1 = np.ones((720, 720, 3))
8 984.8 MiB 913.7 MiB 1 m2 = np.random.randint(128, size=(720, 720, 77, 3))
9 1061.0 MiB 76.1 MiB 1 a = m2[:, :, :, 0].astype(np.uint16)
10 1137.1 MiB 76.1 MiB 1 b = m2[:, :, :, 1].astype(np.uint16)
11 1160.9 MiB 23.8 MiB 1 ans = np.array(m1[b, a].sum(axis=2))
12 247.3 MiB -913.6 MiB 1 m2 = None
13 247.3 MiB 0.0 MiB 1 a = None
14 247.3 MiB 0.0 MiB 1 b = None
15 247.3 MiB 0.0 MiB 1 m1 = None
16 247.3 MiB 0.0 MiB 1 return ans
Line # Mem usage Increment Occurrences Line Contents
=============================================================
19 59.3 MiB 59.3 MiB 1 @profile
20 def f():
21 247.3 MiB 188.0 MiB 1 ans = memory_benchmark()
22 247.3 MiB 0.0 MiB 1 print(ans.shape)
23 247.3 MiB 0.0 MiB 1 print("finished")
If I print(type(m1[0, 0, 0])) yields <class 'numpy.float64'>, print(type(m2[0, 0, 0, 0])) yields <class 'numpy.int64'>, print(type(ans[0, 0, 0])) yields <class 'numpy.float64'>
However, in my Ubuntu VM, I don't have above problem.
A:
I can't reproduce the results you're getting. In python 3.7.3, numpy 1.21.4, and memory_profiler 0.61.0, I'm getting the following results
Line # Mem usage Increment Occurrences Line Contents
=============================================================
23 57.6 MiB 57.6 MiB 1 @profile
24 def memory_benchmark():
25 69.5 MiB 11.9 MiB 1 m1 = np.ones((720, 720, 3))
26 527.4 MiB 457.8 MiB 1 m2 = np.random.randint(128, size=(720, 720, 77, 3))
27 603.6 MiB 76.3 MiB 1 a = m2[:, :, :, 0].astype(np.uint16)
28 679.9 MiB 76.3 MiB 1 b = m2[:, :, :, 1].astype(np.uint16)
29 692.0 MiB 12.1 MiB 1 ans = np.array(m1[b, a].sum(axis=2))
30 234.3 MiB -457.7 MiB 1 m2 = None
31 158.0 MiB -76.3 MiB 1 a = None
32 81.7 MiB -76.3 MiB 1 b = None
33 69.8 MiB -11.9 MiB 1 m1 = None
34 69.8 MiB 0.0 MiB 1 return ans
(720, 720, 3)
finished
Line # Mem usage Increment Occurrences Line Contents
=============================================================
37 57.6 MiB 57.6 MiB 1 @profile
38 def f():
39 69.8 MiB 12.2 MiB 1 ans = memory_benchmark()
40 69.8 MiB 0.0 MiB 1 print(ans.shape)
41 69.8 MiB 0.0 MiB 1 print("finished")
Printing type(m1[0,0,0,0]) yields <class 'numpy.int32'>, so the 457.8 MiB makes sense. On the other hand, your output seems weird, given that assigning m1 to None reports no difference in memory. Which python & library versions are you using?
Update: In a different machine, with python 3.10.6, numpy 1.23.5, and memory_profiler 0.61.0, I still cannot reproduce the OP output.
Line # Mem usage Increment Occurrences Line Contents
=============================================================
5 35.6 MiB 35.6 MiB 1 @profile
6 def memory_benchmark():
7 47.4 MiB 11.8 MiB 1 m1 = np.ones((720, 720, 3))
8 961.2 MiB 913.8 MiB 1 m2 = np.random.randint(128, size=(720, 720, 77, 3))
9 1037.4 MiB 76.2 MiB 1 a = m2[:, :, :, 0].astype(np.uint16)
10 1113.6 MiB 76.2 MiB 1 b = m2[:, :, :, 1].astype(np.uint16)
11 1125.8 MiB 12.2 MiB 1 ans = np.array(m1[b, a].sum(axis=2))
12 212.1 MiB -913.6 MiB 1 m2 = None
13 136.0 MiB -76.1 MiB 1 a = None
14 59.9 MiB -76.1 MiB 1 b = None
15 48.0 MiB -11.9 MiB 1 m1 = None
16 48.0 MiB 0.0 MiB 1 return ans
(720, 720, 3)
finished
Line # Mem usage Increment Occurrences Line Contents
=============================================================
19 35.6 MiB 35.6 MiB 1 @profile
20 def f():
21 48.0 MiB 12.3 MiB 1 ans = memory_benchmark()
22 48.0 MiB 0.0 MiB 1 print(ans.shape)
23 48.0 MiB 0.0 MiB 1 print("finished")
A:
Those numbers look fine to me:
In [772]: 720*720*3*8/1e6
Out[772]: 12.4416
In [773]: 720*720*3*8/1e6 * 77
Out[773]: 958.0032
In [775]: 720*720*77*2/1e6
Out[775]: 79.8336
Evidently once you drop it to 247.3 MiB, the interpreter/numpy decides to "hang on" to that memory, rather than return it to the OS. When tracking memory you are dealing the "choices" of several layers - OS, python interpreter, and numpy's own memory management. One or more of those layers can maintain a "free space" from which it can allocated new objects or arrays.
|
seeming memory leak in numpy for Mac?
|
I used the following process the generate a numpy array with size = (720, 720, 3). In principle, it should cost 720 * 720 * 3 * 8Byte = 12.3MB. However, in the ans = memory_benchmark(), it costs 188 MB. Why does it cost much more memory than expected? I think it should have same cost as the line m1 = np.ones((720, 720, 3)).
I have following two Environments. Both have same problem.
Environment1: numpy=1.23.4, memory_profiler=0.61.0, python=3.10.6, MacOS 12.6.1(Intel not M1)
Environment2: numpy=1.19.5, memory_profiler=0.61.0, python=3.8.15, MacOS 12.6.1(Intel not M1)
I did memory profile in the following
import numpy as np
from memory_profiler import profile
@profile
def memory_benchmark():
m1 = np.ones((720, 720, 3))
m2 = np.random.randint(128, size=(720, 720, 77, 3))
a = m2[:, :, :, 0].astype(np.uint16)
b = m2[:, :, :, 1].astype(np.uint16)
ans = np.array(m1[b, a].sum(axis=2))
m2 = None
a = None
b = None
m1 = None
return ans
@profile
def f():
ans = memory_benchmark()
print(ans.shape)
print("finished")
if __name__ == '__main__':
f()
(720, 720, 3)
finished
Line # Mem usage Increment Occurrences Line Contents
=============================================================
5 59.3 MiB 59.3 MiB 1 @profile
6 def memory_benchmark():
7 71.2 MiB 11.9 MiB 1 m1 = np.ones((720, 720, 3))
8 984.8 MiB 913.7 MiB 1 m2 = np.random.randint(128, size=(720, 720, 77, 3))
9 1061.0 MiB 76.1 MiB 1 a = m2[:, :, :, 0].astype(np.uint16)
10 1137.1 MiB 76.1 MiB 1 b = m2[:, :, :, 1].astype(np.uint16)
11 1160.9 MiB 23.8 MiB 1 ans = np.array(m1[b, a].sum(axis=2))
12 247.3 MiB -913.6 MiB 1 m2 = None
13 247.3 MiB 0.0 MiB 1 a = None
14 247.3 MiB 0.0 MiB 1 b = None
15 247.3 MiB 0.0 MiB 1 m1 = None
16 247.3 MiB 0.0 MiB 1 return ans
Line # Mem usage Increment Occurrences Line Contents
=============================================================
19 59.3 MiB 59.3 MiB 1 @profile
20 def f():
21 247.3 MiB 188.0 MiB 1 ans = memory_benchmark()
22 247.3 MiB 0.0 MiB 1 print(ans.shape)
23 247.3 MiB 0.0 MiB 1 print("finished")
If I print(type(m1[0, 0, 0])) yields <class 'numpy.float64'>, print(type(m2[0, 0, 0, 0])) yields <class 'numpy.int64'>, print(type(ans[0, 0, 0])) yields <class 'numpy.float64'>
However, in my Ubuntu VM, I don't have above problem.
|
[
"I can't reproduce the results you're getting. In python 3.7.3, numpy 1.21.4, and memory_profiler 0.61.0, I'm getting the following results\n\nLine # Mem usage Increment Occurrences Line Contents\n=============================================================\n 23 57.6 MiB 57.6 MiB 1 @profile\n 24 def memory_benchmark():\n 25 69.5 MiB 11.9 MiB 1 m1 = np.ones((720, 720, 3))\n 26 527.4 MiB 457.8 MiB 1 m2 = np.random.randint(128, size=(720, 720, 77, 3))\n 27 603.6 MiB 76.3 MiB 1 a = m2[:, :, :, 0].astype(np.uint16)\n 28 679.9 MiB 76.3 MiB 1 b = m2[:, :, :, 1].astype(np.uint16)\n 29 692.0 MiB 12.1 MiB 1 ans = np.array(m1[b, a].sum(axis=2))\n 30 234.3 MiB -457.7 MiB 1 m2 = None\n 31 158.0 MiB -76.3 MiB 1 a = None\n 32 81.7 MiB -76.3 MiB 1 b = None\n 33 69.8 MiB -11.9 MiB 1 m1 = None\n 34 69.8 MiB 0.0 MiB 1 return ans\n\n\n(720, 720, 3)\nfinished\n\nLine # Mem usage Increment Occurrences Line Contents\n=============================================================\n 37 57.6 MiB 57.6 MiB 1 @profile\n 38 def f():\n 39 69.8 MiB 12.2 MiB 1 ans = memory_benchmark()\n 40 69.8 MiB 0.0 MiB 1 print(ans.shape)\n 41 69.8 MiB 0.0 MiB 1 print(\"finished\")\n\nPrinting type(m1[0,0,0,0]) yields <class 'numpy.int32'>, so the 457.8 MiB makes sense. On the other hand, your output seems weird, given that assigning m1 to None reports no difference in memory. Which python & library versions are you using?\n\nUpdate: In a different machine, with python 3.10.6, numpy 1.23.5, and memory_profiler 0.61.0, I still cannot reproduce the OP output.\nLine # Mem usage Increment Occurrences Line Contents\n=============================================================\n 5 35.6 MiB 35.6 MiB 1 @profile\n 6 def memory_benchmark():\n 7 47.4 MiB 11.8 MiB 1 m1 = np.ones((720, 720, 3))\n 8 961.2 MiB 913.8 MiB 1 m2 = np.random.randint(128, size=(720, 720, 77, 3))\n 9 1037.4 MiB 76.2 MiB 1 a = m2[:, :, :, 0].astype(np.uint16)\n 10 1113.6 MiB 76.2 MiB 1 b = m2[:, :, :, 1].astype(np.uint16)\n 11 1125.8 MiB 12.2 MiB 1 ans = np.array(m1[b, a].sum(axis=2))\n 12 212.1 MiB -913.6 MiB 1 m2 = None\n 13 136.0 MiB -76.1 MiB 1 a = None\n 14 59.9 MiB -76.1 MiB 1 b = None\n 15 48.0 MiB -11.9 MiB 1 m1 = None\n 16 48.0 MiB 0.0 MiB 1 return ans\n\n\n(720, 720, 3)\nfinished\n\nLine # Mem usage Increment Occurrences Line Contents\n=============================================================\n 19 35.6 MiB 35.6 MiB 1 @profile\n 20 def f():\n 21 48.0 MiB 12.3 MiB 1 ans = memory_benchmark()\n 22 48.0 MiB 0.0 MiB 1 print(ans.shape)\n 23 48.0 MiB 0.0 MiB 1 print(\"finished\")\n\n",
"Those numbers look fine to me:\nIn [772]: 720*720*3*8/1e6\nOut[772]: 12.4416\n\nIn [773]: 720*720*3*8/1e6 * 77\nOut[773]: 958.0032\n\nIn [775]: 720*720*77*2/1e6\nOut[775]: 79.8336\n\nEvidently once you drop it to 247.3 MiB, the interpreter/numpy decides to \"hang on\" to that memory, rather than return it to the OS. When tracking memory you are dealing the \"choices\" of several layers - OS, python interpreter, and numpy's own memory management. One or more of those layers can maintain a \"free space\" from which it can allocated new objects or arrays.\n"
] |
[
0,
0
] |
[] |
[] |
[
"macos",
"memory_leaks",
"numpy",
"python"
] |
stackoverflow_0074526223_macos_memory_leaks_numpy_python.txt
|
Q:
Selenium AttributeError: 'WebDriver' object has no attribute 'find_element_by_css_selector'
I am following this build of a scraper for LinkedIn job data.
Here is my code:
from selenium import webdriver
import time
import pandas as pd
url = 'https://www.linkedin.com/jobs/search?keywords=&location=San%20Francisco%2C%20California%2C%20United%20States&locationId=&geoId=102277331&f_TPR=&distance=100&position=1&pageNum=0'
wd = webdriver.Chrome(executable_path=r'/Users/voi/chromedriver')
wd.get(url)
no_of_jobs = int(wd.driver.find_element_by_css_selector('h1>span').get_attribute('innerText'))
I have seen this, and attempted the solution, but received a similar error, except with regards to the WebDriver object not having a driver attribute.
Here is the full error message:
cd /Users/voi ; /usr/bin/env /usr/local/bin/python3 /Users/voi/.vscode/extensions/ms-python.python-2
022.8.1/pythonFiles/lib/python/debugpy/launcher 59402 -- /Users/voi/jobscrape.py
/Users/voi/jobscrape.py:7: DeprecationWarning: executable_path has been deprecated, please pass in a Service object
wd = webdriver.Chrome(executable_path=r'/Users/voi/chromedriver')
Traceback (most recent call last):
File "/Users/voi/jobscrape.py", line 10, in <module>
no_of_jobs = int(wd.find_element_by_css_selector('h1>span').get_attribute('innerText'))
AttributeError: 'WebDriver' object has no attribute 'find_element_by_css_selector'
A:
Okay, I answered my own question. The individual methods find_element_by_* have been replaced by find_element, e.g.
no_of_jobs = int(wd.find_element(By.CSS_SELECTOR, 'h1>span'))
More info is here
A:
Selenium just removed that method in version 4.3.0. See the CHANGES: https://github.com/SeleniumHQ/selenium/blob/a4995e2c096239b42c373f26498a6c9bb4f2b3e7/py/CHANGES
Selenium 4.3.0
* Deprecated find_element_by_* and find_elements_by_* are now removed (#10712)
* Deprecated Opera support has been removed (#10630)
* Fully upgraded from python 2x to 3.7 syntax and features (#10647)
* Added a devtools version fallback mechanism to look for an older version when mismatch occurs (#10749)
* Better support for co-operative multi inheritance by utilising super() throughout
* Improved type hints throughout
You now need to use:
driver.find_element("css selector", SELECTOR)
In your example, you would use:
no_of_jobs = int(wd.find_element("css selector", "h1 > span").get_attribute("innerText"))
For improved reliability, you should consider using WebDriverWait in combination with visibility_of_element_located.
Here's how that might look:
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
# ...
element = WebDriverWait(wd, 10).until(
EC.visibility_of_element_located(("css selector", "h1 > span"))
)
no_of_jobs = int(element.get_attribute("innerText"))
A:
Selenium recently removed the 16 deprecated find_element(s)_by_x functions in favor of a general find_element and find_elements function that take the "by" part as their first argument.
To update your code, you can use your IDE's find-and-replace-all feature to replace these 16 search terms:
.find_element_by_class_name(
.find_element(By.CLASS_NAME,
.find_element_by_css_selector(
.find_element(By.CSS_SELECTOR,
.find_element_by_id(
.find_element(By.ID,
.find_element_by_link_text(
.find_element(By.LINK_TEXT,
.find_element_by_name(
.find_element(By.NAME,
.find_element_by_partial_link_text(
.find_element(By.PARTIAL_LINK_TEXT,
.find_element_by_tag_name(
.find_element(By.TAG_NAME,
.find_element_by_xpath(
.find_element(By.XPATH,
.find_elements_by_class_name(
.find_elements(By.CLASS_NAME,
.find_elements_by_css_selector(
.find_elements(By.CSS_SELECTOR,
.find_elements_by_id(
.find_elements(By.ID,
.find_elements_by_link_text(
.find_elements(By.LINK_TEXT,
.find_elements_by_name(
.find_elements(By.NAME,
.find_elements_by_partial_link_text(
.find_elements(By.PARTIAL_LINK_TEXT,
.find_elements_by_tag_name(
.find_elements(By.TAG_NAME,
.find_elements_by_xpath(
.find_elements(By.XPATH,
You'll also need to import By if you haven't already done so:
from selenium.webdriver.common.by import By
A:
To add on to the answer from @m.lekk ( https://stackoverflow.com/a/72854301/7733418 ), I also tried to use dir() to get all the attributes from the object and find the text attribute that contains the information that I need.
|
Selenium AttributeError: 'WebDriver' object has no attribute 'find_element_by_css_selector'
|
I am following this build of a scraper for LinkedIn job data.
Here is my code:
from selenium import webdriver
import time
import pandas as pd
url = 'https://www.linkedin.com/jobs/search?keywords=&location=San%20Francisco%2C%20California%2C%20United%20States&locationId=&geoId=102277331&f_TPR=&distance=100&position=1&pageNum=0'
wd = webdriver.Chrome(executable_path=r'/Users/voi/chromedriver')
wd.get(url)
no_of_jobs = int(wd.driver.find_element_by_css_selector('h1>span').get_attribute('innerText'))
I have seen this, and attempted the solution, but received a similar error, except with regards to the WebDriver object not having a driver attribute.
Here is the full error message:
cd /Users/voi ; /usr/bin/env /usr/local/bin/python3 /Users/voi/.vscode/extensions/ms-python.python-2
022.8.1/pythonFiles/lib/python/debugpy/launcher 59402 -- /Users/voi/jobscrape.py
/Users/voi/jobscrape.py:7: DeprecationWarning: executable_path has been deprecated, please pass in a Service object
wd = webdriver.Chrome(executable_path=r'/Users/voi/chromedriver')
Traceback (most recent call last):
File "/Users/voi/jobscrape.py", line 10, in <module>
no_of_jobs = int(wd.find_element_by_css_selector('h1>span').get_attribute('innerText'))
AttributeError: 'WebDriver' object has no attribute 'find_element_by_css_selector'
|
[
"Okay, I answered my own question. The individual methods find_element_by_* have been replaced by find_element, e.g.\nno_of_jobs = int(wd.find_element(By.CSS_SELECTOR, 'h1>span'))\n\nMore info is here\n",
"Selenium just removed that method in version 4.3.0. See the CHANGES: https://github.com/SeleniumHQ/selenium/blob/a4995e2c096239b42c373f26498a6c9bb4f2b3e7/py/CHANGES\nSelenium 4.3.0\n* Deprecated find_element_by_* and find_elements_by_* are now removed (#10712)\n* Deprecated Opera support has been removed (#10630)\n* Fully upgraded from python 2x to 3.7 syntax and features (#10647)\n* Added a devtools version fallback mechanism to look for an older version when mismatch occurs (#10749)\n* Better support for co-operative multi inheritance by utilising super() throughout\n* Improved type hints throughout\n\nYou now need to use:\ndriver.find_element(\"css selector\", SELECTOR)\n\nIn your example, you would use:\nno_of_jobs = int(wd.find_element(\"css selector\", \"h1 > span\").get_attribute(\"innerText\"))\n\nFor improved reliability, you should consider using WebDriverWait in combination with visibility_of_element_located.\nHere's how that might look:\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.ui import WebDriverWait\n\n# ...\n\nelement = WebDriverWait(wd, 10).until(\n EC.visibility_of_element_located((\"css selector\", \"h1 > span\"))\n)\nno_of_jobs = int(element.get_attribute(\"innerText\"))\n\n",
"Selenium recently removed the 16 deprecated find_element(s)_by_x functions in favor of a general find_element and find_elements function that take the \"by\" part as their first argument.\nTo update your code, you can use your IDE's find-and-replace-all feature to replace these 16 search terms:\n.find_element_by_class_name(\n.find_element(By.CLASS_NAME, \n\n.find_element_by_css_selector(\n.find_element(By.CSS_SELECTOR, \n\n.find_element_by_id(\n.find_element(By.ID, \n\n.find_element_by_link_text(\n.find_element(By.LINK_TEXT, \n\n.find_element_by_name(\n.find_element(By.NAME, \n\n.find_element_by_partial_link_text(\n.find_element(By.PARTIAL_LINK_TEXT, \n\n.find_element_by_tag_name(\n.find_element(By.TAG_NAME, \n\n.find_element_by_xpath(\n.find_element(By.XPATH, \n\n.find_elements_by_class_name(\n.find_elements(By.CLASS_NAME, \n\n.find_elements_by_css_selector(\n.find_elements(By.CSS_SELECTOR, \n\n.find_elements_by_id(\n.find_elements(By.ID, \n\n.find_elements_by_link_text(\n.find_elements(By.LINK_TEXT, \n\n.find_elements_by_name(\n.find_elements(By.NAME, \n\n.find_elements_by_partial_link_text(\n.find_elements(By.PARTIAL_LINK_TEXT, \n\n.find_elements_by_tag_name(\n.find_elements(By.TAG_NAME, \n\n.find_elements_by_xpath(\n.find_elements(By.XPATH, \n\nYou'll also need to import By if you haven't already done so:\nfrom selenium.webdriver.common.by import By\n\n",
"To add on to the answer from @m.lekk ( https://stackoverflow.com/a/72854301/7733418 ), I also tried to use dir() to get all the attributes from the object and find the text attribute that contains the information that I need.\n"
] |
[
15,
4,
3,
0
] |
[] |
[] |
[
"python",
"selenium",
"selenium_webdriver"
] |
stackoverflow_0072854116_python_selenium_selenium_webdriver.txt
|
Q:
Python regular expression split by multiple delimiters
Given the sentence "I want to eat fish and I want to buy a car. Therefore, I have to make money."
I want to split the sentene by
['I want to eat fish', 'I want to buy a car", Therefore, 'I have to make money']
I am trying to split the sentence
re.split('.|and', sentence)
However, it splits the sentence by '.', 'a', 'n', and 'd'.
How can I split the sentence by '.' and 'and'?
A:
In addition to escaping the dot (.), which matches any non-newline character in regex, you should also match any leading or trailing spaces in order for the delimiter of the split to consume undesired leading and trailing spaces from the results. Use a positive lookahead pattern to assert a following non-whitespace character in the end to avoid splitting by the trailing dot:
re.split('\s*(?:\.|and)\s*(?=\S)', sentence)
This returns:
['I want to eat fish', 'I want to buy a car', 'Therefore, I have to make money.']
Demo: https://replit.com/@blhsing/LimitedVastCookies
A:
You need to escape the . in the regex.
import re
s = "I want to eat fish and I want to buy a car. Therefore, I have to make money."
re.split('\.|and', s)
Result:
['I want to eat fish ',
' I want to buy a car',
' Therefore, I have to make money',
'']
|
Python regular expression split by multiple delimiters
|
Given the sentence "I want to eat fish and I want to buy a car. Therefore, I have to make money."
I want to split the sentene by
['I want to eat fish', 'I want to buy a car", Therefore, 'I have to make money']
I am trying to split the sentence
re.split('.|and', sentence)
However, it splits the sentence by '.', 'a', 'n', and 'd'.
How can I split the sentence by '.' and 'and'?
|
[
"In addition to escaping the dot (.), which matches any non-newline character in regex, you should also match any leading or trailing spaces in order for the delimiter of the split to consume undesired leading and trailing spaces from the results. Use a positive lookahead pattern to assert a following non-whitespace character in the end to avoid splitting by the trailing dot:\nre.split('\\s*(?:\\.|and)\\s*(?=\\S)', sentence)\n\nThis returns:\n['I want to eat fish', 'I want to buy a car', 'Therefore, I have to make money.']\n\nDemo: https://replit.com/@blhsing/LimitedVastCookies\n",
"You need to escape the . in the regex.\nimport re\n\ns = \"I want to eat fish and I want to buy a car. Therefore, I have to make money.\"\n\nre.split('\\.|and', s)\n\nResult:\n['I want to eat fish ',\n ' I want to buy a car',\n ' Therefore, I have to make money',\n '']\n\n"
] |
[
2,
1
] |
[] |
[] |
[
"python",
"regex"
] |
stackoverflow_0074526464_python_regex.txt
|
Q:
Is it possible to Average only certain sections of a spreadsheet with python by specifying the sections you want based on another factor?
I am trying to average the sea temperature for the fall and spring of each year in my data set. Imagine three columns (year/season/temp) which list things such as: 1963, FALL, 75 and continues with various years and the spring/fall season. How could I code to find the average of the temperatures that are in the fall of 1963 then the spring of 1963 then the fall of 1964 and so on all the way until 2021? My goal is to be able to show the temperature changes over time from those averages
I only have the temperature vs time scatter plot as of now and wasn't expected to have any issues but i think having multiple temperatures for each year that contradict each other (by not separating the fall/spring) is really hurting my r2 value
A:
With pandas you can perform a groupby on the data frame. Assuming the column names are year, season and Temp something like the following should work:
import numpy as np
import pandas as pd
avg_df = df.groupby(['year','season']).agg({'Temp':[np.mean, np.std]})
avg_df.columns = ['Mean', 'STD']
|
Is it possible to Average only certain sections of a spreadsheet with python by specifying the sections you want based on another factor?
|
I am trying to average the sea temperature for the fall and spring of each year in my data set. Imagine three columns (year/season/temp) which list things such as: 1963, FALL, 75 and continues with various years and the spring/fall season. How could I code to find the average of the temperatures that are in the fall of 1963 then the spring of 1963 then the fall of 1964 and so on all the way until 2021? My goal is to be able to show the temperature changes over time from those averages
I only have the temperature vs time scatter plot as of now and wasn't expected to have any issues but i think having multiple temperatures for each year that contradict each other (by not separating the fall/spring) is really hurting my r2 value
|
[
"With pandas you can perform a groupby on the data frame. Assuming the column names are year, season and Temp something like the following should work:\nimport numpy as np\nimport pandas as pd\n\navg_df = df.groupby(['year','season']).agg({'Temp':[np.mean, np.std]})\navg_df.columns = ['Mean', 'STD']\n\n"
] |
[
0
] |
[] |
[] |
[
"average",
"pandas",
"python",
"sorting",
"spreadsheet"
] |
stackoverflow_0074526459_average_pandas_python_sorting_spreadsheet.txt
|
Q:
Using an extra python package index url with setup.py
Is there a way to use an extra Python package index (ala pip --extra-index-url pypi.example.org mypackage) with setup.py so that running python setup.py install can find the packages hosted on pypi.example.org?
A:
If you're the package maintainer, and you want to host one or more dependencies for your package somewhere other than PyPi, you can use the dependency_links option of setuptools in your distribution's setup.py file. This allows you to provide an explicit location where your package can be located.
For example:
from setuptools import setup
setup(
name='somepackage',
install_requires=[
'somedep'
],
dependency_links=[
'https://pypi.example.org/pypi/somedep/'
]
# ...
)
If you host your own index server, you'll need to provide links to the pages containing the actual download links for each egg, not the page listing all of the packages (e.g. https://pypi.example.org/pypi/somedep/, not https://pypi.example.org/)
A:
setuptools uses easy_install under the hood.
It relies on either setup.cfg or ~/.pydistutils.cfg as documented here.
Extra paths to packages can be defined in either of these files with the find_links. You can override the registry url with index_url but cannot supply an extra-index-url. Example below inspired by the docs:
[easy_install]
find_links = http://mypackages.example.com/somedir/
http://turbogears.org/download/
http://peak.telecommunity.com/dist/
index-url = https://mypi.example.com
A:
I wanted to post a latest answer to this since both the top answers are obsolete; use of easy_install has been deprecated by setuptools.
https://setuptools.pypa.io/en/latest/deprecated/easy_install.html
Easy Install is deprecated. Do not use it. Instead use pip. If you think you need Easy Install, please reach out to the PyPA team (a ticket to pip or setuptools is fine), describing your use-case.
Please use pip moving forward. You can do one of the following:
provide --index-url flag to pip command
define index-url in pip.conf file
define PIP_INDEX_URL environment variable
https://pip.pypa.io/en/stable/topics/configuration/
A:
The following worked for me (develop, not install):
$ python setup.py develop --index-url https://x.com/n/r/pypi-proxy/simple
Where https://x.com/n/r/pypi-proxy/simple is a local PyPI repository.
A:
Found solution when using Dockerfile:
RUN cd flask-mongoengine-0.9.5 && \
/bin/echo -e [easy_install]\\nindex-url = https://pypi.tuna.tsinghua.edu.cn/simple >> setup.cfg && \
python setup.py install
Which /bin/echo -e [easy_install]\\nindex-url = https://pypi.tuna.tsinghua.edu.cn/simple will exists in file setup.cfg:
[easy_install]
index-url = https://pypi.tuna.tsinghua.edu.cn/simple
A:
this worked for me
PIP_INDEX_URL=<MY CUSTOM PIP INDEX URL> pip install -e .
I use setup.py and setup.cfg
|
Using an extra python package index url with setup.py
|
Is there a way to use an extra Python package index (ala pip --extra-index-url pypi.example.org mypackage) with setup.py so that running python setup.py install can find the packages hosted on pypi.example.org?
|
[
"If you're the package maintainer, and you want to host one or more dependencies for your package somewhere other than PyPi, you can use the dependency_links option of setuptools in your distribution's setup.py file. This allows you to provide an explicit location where your package can be located.\nFor example:\nfrom setuptools import setup\n\nsetup(\n name='somepackage',\n install_requires=[\n 'somedep'\n ],\n dependency_links=[\n 'https://pypi.example.org/pypi/somedep/'\n ]\n # ...\n)\n\nIf you host your own index server, you'll need to provide links to the pages containing the actual download links for each egg, not the page listing all of the packages (e.g. https://pypi.example.org/pypi/somedep/, not https://pypi.example.org/)\n",
"setuptools uses easy_install under the hood.\nIt relies on either setup.cfg or ~/.pydistutils.cfg as documented here.\nExtra paths to packages can be defined in either of these files with the find_links. You can override the registry url with index_url but cannot supply an extra-index-url. Example below inspired by the docs:\n[easy_install]\nfind_links = http://mypackages.example.com/somedir/\n http://turbogears.org/download/\n http://peak.telecommunity.com/dist/\nindex-url = https://mypi.example.com\n\n",
"I wanted to post a latest answer to this since both the top answers are obsolete; use of easy_install has been deprecated by setuptools.\nhttps://setuptools.pypa.io/en/latest/deprecated/easy_install.html\n\nEasy Install is deprecated. Do not use it. Instead use pip. If you think you need Easy Install, please reach out to the PyPA team (a ticket to pip or setuptools is fine), describing your use-case.\n\nPlease use pip moving forward. You can do one of the following:\n\nprovide --index-url flag to pip command\ndefine index-url in pip.conf file\ndefine PIP_INDEX_URL environment variable\n\nhttps://pip.pypa.io/en/stable/topics/configuration/\n",
"The following worked for me (develop, not install):\n$ python setup.py develop --index-url https://x.com/n/r/pypi-proxy/simple\n\nWhere https://x.com/n/r/pypi-proxy/simple is a local PyPI repository.\n",
"Found solution when using Dockerfile:\nRUN cd flask-mongoengine-0.9.5 && \\\n /bin/echo -e [easy_install]\\\\nindex-url = https://pypi.tuna.tsinghua.edu.cn/simple >> setup.cfg && \\\n python setup.py install\n\nWhich /bin/echo -e [easy_install]\\\\nindex-url = https://pypi.tuna.tsinghua.edu.cn/simple will exists in file setup.cfg:\n[easy_install]\nindex-url = https://pypi.tuna.tsinghua.edu.cn/simple\n\n",
"this worked for me\nPIP_INDEX_URL=<MY CUSTOM PIP INDEX URL> pip install -e .\n\nI use setup.py and setup.cfg\n"
] |
[
49,
17,
5,
4,
2,
0
] |
[
"As far as I know, you cant do that.\nYou need to tell pip this, or by passing a parameter like you mentioned, or by setting this on the user environment.\nCheck my ~/.pip/pip.conf:\n[global]\ndownload_cache = ~/.cache/pip\nindex-url = http://user:pass@localpypiserver.com:80/simple\ntimeout = 300\n\nIn this case, my local pypiserver also proxies all packages from pypi.python.org, so I dont need to add a 2nd entry.\n",
"You can include --extra-index-urls in a requirements.txt file. See: http://pip.readthedocs.org/en/0.8.3/requirement-format.html\n"
] |
[
-2,
-6
] |
[
"packaging",
"pip",
"pypi",
"python",
"setup.py"
] |
stackoverflow_0024443583_packaging_pip_pypi_python_setup.py.txt
|
Q:
Make parent class do something "once" in Python
class TaskInput:
def __init__(self):
self.cfg = my_config #### Question: How do I do this only once?
class TaskA(TaskInput):
def __init__(self):
pass
class TaskB (TaskInput):
def __init__(self):
pass
There are many tasks like TaskA, TaskB etc, they all are inherited from TaskInput.
Tasks also depend on something, let's say, a configuration which I only want to set ONCE.
The code has multiple Tasks classes, like TaskA, TaskB etc. They all depend on this common configuration.
One natural way would be to make this configuration a class member of TaskInput, ie, TaskInput.cfg = my_config, something that's initialized in __init__() of TaskInput.
However, if it's a member of TaskInput, it'll get executed multiple times, every time a new object of type TaskX is created as all those Tasks are inherited from TaskInput.
What's the best practice and best way to accomplish this in Python?
A:
Make the configuration a class attribute by defining it on the class rather than in __init__.
class TaskInput:
cfg = my_config
It is now accessible as self.cfg on any instance of TaskInput or its children.
A:
I will not try to guess your need so I will assume you mean exactly what you said below, namely that you want a single initialization of a class member, but done through the creation of an instance.
a class member of TaskInput, ie, TaskInput.cfg = my_config, something
that's initialized in init() of TaskInput.
This can work, but not the way you did it. in your code you never created a class attribute, anything created with self is an instance attribute belonging to a single specific task instance so that:
from copy import deepcopy
class TaskInput:
_cfg = None # prefix with '_' to indicate it should be considered private
def __init__(self, my_config=None):
_cfg = _cfg or my_config
@property
def cfg(self):
""" If you want to privatize it a bit more,
make yourself a getter that returns a deep copy."""
return deepcopy(cfg)
Now, there basically is no such thing as true privatization in python and you will never be able to entirely prevent manipulation. In the example above, any child has direct read-write access to _cfg, so it would fall on us not to use it directly and pass by its accessors (__init__() and cfg()).
There's always a way to make things more difficult, like the following, using modules.
Project
├─ __init__.py
├─ settings.py
├─ module1.py
└─ module2.py
settings.py
cfg = None
module1.py
from copy import deepcopy
import settings
class A:
def __init__(self, cfg_=None):
settings.cfg = settings.cfg or cfg_
@property
def cfg(self):
return deepcopy(settings.cfg)
module2.py
""" The following classes won't be able to
overwrite the config without importing
from settings.py.
"""
from module1 import A
class B(A):
pass
class C(A):
def __init__(self):
super().__init__("foobar")
Giving these results:
b0 = B()
b0.cfg
# > None
b1 = B({"foo1": "bar1"})
b1.cfg
# > {'foo1': 'bar1'}
b2 = B({"foo1": "bar2", "foo3": "bar3"})
b2.cfg
# > {'foo1': 'bar1'}
try:
b2.cfg = 1234
except Exception as e:
print(type(e), e)
# > <class 'AttributeError'> can't set attribute
b2.cfg
# > {'foo1': 'bar1'}
c = C("asdf")
c.cfg
# > {'foo1': 'bar1'}
Which can be overkill of course and removes the actual ownership of the configuration from the class
|
Make parent class do something "once" in Python
|
class TaskInput:
def __init__(self):
self.cfg = my_config #### Question: How do I do this only once?
class TaskA(TaskInput):
def __init__(self):
pass
class TaskB (TaskInput):
def __init__(self):
pass
There are many tasks like TaskA, TaskB etc, they all are inherited from TaskInput.
Tasks also depend on something, let's say, a configuration which I only want to set ONCE.
The code has multiple Tasks classes, like TaskA, TaskB etc. They all depend on this common configuration.
One natural way would be to make this configuration a class member of TaskInput, ie, TaskInput.cfg = my_config, something that's initialized in __init__() of TaskInput.
However, if it's a member of TaskInput, it'll get executed multiple times, every time a new object of type TaskX is created as all those Tasks are inherited from TaskInput.
What's the best practice and best way to accomplish this in Python?
|
[
"Make the configuration a class attribute by defining it on the class rather than in __init__.\nclass TaskInput:\n cfg = my_config\n\nIt is now accessible as self.cfg on any instance of TaskInput or its children.\n",
"I will not try to guess your need so I will assume you mean exactly what you said below, namely that you want a single initialization of a class member, but done through the creation of an instance.\n\na class member of TaskInput, ie, TaskInput.cfg = my_config, something\nthat's initialized in init() of TaskInput.\n\nThis can work, but not the way you did it. in your code you never created a class attribute, anything created with self is an instance attribute belonging to a single specific task instance so that:\nfrom copy import deepcopy\n\nclass TaskInput:\n _cfg = None # prefix with '_' to indicate it should be considered private\n \n def __init__(self, my_config=None):\n _cfg = _cfg or my_config\n \n @property\n def cfg(self):\n \"\"\" If you want to privatize it a bit more,\n make yourself a getter that returns a deep copy.\"\"\"\n return deepcopy(cfg)\n\nNow, there basically is no such thing as true privatization in python and you will never be able to entirely prevent manipulation. In the example above, any child has direct read-write access to _cfg, so it would fall on us not to use it directly and pass by its accessors (__init__() and cfg()).\nThere's always a way to make things more difficult, like the following, using modules.\n Project\n ├─ __init__.py\n ├─ settings.py\n ├─ module1.py\n └─ module2.py\n\nsettings.py\ncfg = None\n\nmodule1.py\nfrom copy import deepcopy\nimport settings\n\nclass A:\n def __init__(self, cfg_=None):\n settings.cfg = settings.cfg or cfg_\n\n @property\n def cfg(self):\n return deepcopy(settings.cfg)\n\nmodule2.py\n\"\"\" The following classes won't be able to\noverwrite the config without importing\nfrom settings.py.\n\"\"\"\n\nfrom module1 import A\n\nclass B(A):\n pass\n\nclass C(A):\n def __init__(self):\n super().__init__(\"foobar\")\n\nGiving these results:\nb0 = B()\nb0.cfg\n# > None\n\nb1 = B({\"foo1\": \"bar1\"})\nb1.cfg\n# > {'foo1': 'bar1'}\n\nb2 = B({\"foo1\": \"bar2\", \"foo3\": \"bar3\"})\nb2.cfg\n# > {'foo1': 'bar1'}\n\ntry:\n b2.cfg = 1234\nexcept Exception as e:\n print(type(e), e)\n# > <class 'AttributeError'> can't set attribute\n\nb2.cfg\n# > {'foo1': 'bar1'}\n\nc = C(\"asdf\")\nc.cfg\n# > {'foo1': 'bar1'}\n\nWhich can be overkill of course and removes the actual ownership of the configuration from the class\n"
] |
[
2,
0
] |
[] |
[] |
[
"inheritance",
"python"
] |
stackoverflow_0074524574_inheritance_python.txt
|
Q:
How to upload a dataset folder to an already existing folder in vs code (connected to remote ssh)
I kind of have a structure of my vs repository as follow:
* shh remote host
* workspace
* main folder
* folder where I want to upload a 20 GB file of dataset
Please note that I can't locate the folder in the computer system. How can I upload a zip file or a direct folder in the 'folder where I want to upload a 20 GB file of dataset'
I tried push command and also tried to copy paste the stuff there.
A:
The comments have given a reasonable solution. Of course, if you must use SSH, you can use rsync to transfer files.
An alternative to using SSHFS to access remote files is to use rsync to copy the entire contents of a folder on remote host to your local machine. The rsync command will determine which files need to be updated each time it is run, which is far more efficient and convenient than using something like scp or sftp.
YOU can read docs for more details.
|
How to upload a dataset folder to an already existing folder in vs code (connected to remote ssh)
|
I kind of have a structure of my vs repository as follow:
* shh remote host
* workspace
* main folder
* folder where I want to upload a 20 GB file of dataset
Please note that I can't locate the folder in the computer system. How can I upload a zip file or a direct folder in the 'folder where I want to upload a 20 GB file of dataset'
I tried push command and also tried to copy paste the stuff there.
|
[
"The comments have given a reasonable solution. Of course, if you must use SSH, you can use rsync to transfer files.\nAn alternative to using SSHFS to access remote files is to use rsync to copy the entire contents of a folder on remote host to your local machine. The rsync command will determine which files need to be updated each time it is run, which is far more efficient and convenient than using something like scp or sftp.\nYOU can read docs for more details.\n"
] |
[
0
] |
[] |
[] |
[
"python",
"visual_studio_code"
] |
stackoverflow_0074519802_python_visual_studio_code.txt
|
Q:
Selenium's version of seleniumwire's requests
So, originally my code was something like this:
from seleniumwire import webdriver
driver = webdriver.Firefox(options=self.web_options
driver.get(user_site)
ret = list(driver.requests)
verify = extract_verify(ret)
driver.requests.clear()
driver.get(self.root + '?verify={}'.format(urllib.parse.quote(verify)))
resp = self.driver.page_source
The api has changed so that driver.get needs to be replaced with driver.request('POST', root, data={"verify": urllib.parse.quote(verify)}) which requires me to install seleniumrequests, but seleniumrequests is built on the selenium webdriver, not the seleniumwire webdriver and if I try to switch out the webdriver, then the driver.requests line doesn't work because selenium doesn't have that field.
As for versions, I have:
selenium=4.6.0
selenium-wire=5.1.0
selenium-requests=2.0.1
Python=3.8.10
What do you guys think I should try?
A:
I was able to fix this with from seleniumrequests.request import RequestsSessionMixin. It was still helpful to get my thoughts on paper like this.
|
Selenium's version of seleniumwire's requests
|
So, originally my code was something like this:
from seleniumwire import webdriver
driver = webdriver.Firefox(options=self.web_options
driver.get(user_site)
ret = list(driver.requests)
verify = extract_verify(ret)
driver.requests.clear()
driver.get(self.root + '?verify={}'.format(urllib.parse.quote(verify)))
resp = self.driver.page_source
The api has changed so that driver.get needs to be replaced with driver.request('POST', root, data={"verify": urllib.parse.quote(verify)}) which requires me to install seleniumrequests, but seleniumrequests is built on the selenium webdriver, not the seleniumwire webdriver and if I try to switch out the webdriver, then the driver.requests line doesn't work because selenium doesn't have that field.
As for versions, I have:
selenium=4.6.0
selenium-wire=5.1.0
selenium-requests=2.0.1
Python=3.8.10
What do you guys think I should try?
|
[
"I was able to fix this with from seleniumrequests.request import RequestsSessionMixin. It was still helpful to get my thoughts on paper like this.\n"
] |
[
0
] |
[] |
[] |
[
"dependencies",
"python",
"selenium",
"selenium_webdriver"
] |
stackoverflow_0074526370_dependencies_python_selenium_selenium_webdriver.txt
|
Q:
Blob.generate_signed_url() failing to AttributeError
So I'm trying to produce temporary globally readable URLs for my Google Cloud Storage objects using the google-cloud-storage Python library (https://googlecloudplatform.github.io/google-cloud-python/latest/storage/blobs.html) - more specifically the Blob.generate_signed_url() method. I doing this from within a Compute Engine instance in a command line Python script. And I keep getting the following error:
AttributeError: you need a private key to sign credentials.the credentials you are currently using <class 'oauth2cl
ient.service_account.ServiceAccountCredentials'> just contains a token. see https://google-cloud-python.readthedocs
.io/en/latest/core/auth.html?highlight=authentication#setting-up-a-service-account for more details.
I am aware that there are issues with doing this from within GCE (https://github.com/GoogleCloudPlatform/google-auth-library-python/issues/50) but I have created a new Service Account credentials following the instructions here: https://cloud.google.com/storage/docs/access-control/create-signed-urls-program and my key.json file most certainly includes a private key. Still I am seeing that error.
This is my code:
keyfile = "/path/to/my/key.json"
credentials = ServiceAccountCredentials.from_json_keyfile_name(keyfile)
expiration = timedelta(3) # valid for 3 days
url = blob.generate_signed_url(expiration, method="GET",
credentials=credentials)
I've read through the issue tracker here https://github.com/GoogleCloudPlatform/google-cloud-python/issues?page=2&q=is%3Aissue+is%3Aopen and nothing related jumps out so I am assuming this should work. Cannot see what's going wrong here.
A:
I was having the same issue. Ended up fixing it by starting the storage client directly from the service account json.
storage_client = storage.Client.from_service_account_json('path_to_service_account_key.json')
I know I'm late to the party but hopefully this helps!
A:
Currently, it's not possible to use blob.generate_signed_url without explicitly referencing credentials. (Source: Google-Cloud-Python documentation) However, you can do a workaround, as seen here, which consists of:
signing_credentials = compute_engine.IDTokenCredentials(
auth_request,
"",
service_account_email=credentials.service_account_email
)
signed_url = signed_blob_path.generate_signed_url(
expires_at_ms,
credentials=signing_credentials,
version="v4"
)
A:
A much complete snippet for those asking where other elements come from. cc @AlbertoVitoriano
from google.auth.transport import requests
from google.auth import default, compute_engine
credentials, _ = default()
# then within your abstraction
auth_request = requests.Request()
credentials.refresh(auth_request)
signing_credentials = compute_engine.IDTokenCredentials(
auth_request,
"",
service_account_email=credentials.service_account_email
)
signed_url = signed_blob_path.generate_signed_url(
expires_at_ms,
credentials=signing_credentials,
version="v4"
)
|
Blob.generate_signed_url() failing to AttributeError
|
So I'm trying to produce temporary globally readable URLs for my Google Cloud Storage objects using the google-cloud-storage Python library (https://googlecloudplatform.github.io/google-cloud-python/latest/storage/blobs.html) - more specifically the Blob.generate_signed_url() method. I doing this from within a Compute Engine instance in a command line Python script. And I keep getting the following error:
AttributeError: you need a private key to sign credentials.the credentials you are currently using <class 'oauth2cl
ient.service_account.ServiceAccountCredentials'> just contains a token. see https://google-cloud-python.readthedocs
.io/en/latest/core/auth.html?highlight=authentication#setting-up-a-service-account for more details.
I am aware that there are issues with doing this from within GCE (https://github.com/GoogleCloudPlatform/google-auth-library-python/issues/50) but I have created a new Service Account credentials following the instructions here: https://cloud.google.com/storage/docs/access-control/create-signed-urls-program and my key.json file most certainly includes a private key. Still I am seeing that error.
This is my code:
keyfile = "/path/to/my/key.json"
credentials = ServiceAccountCredentials.from_json_keyfile_name(keyfile)
expiration = timedelta(3) # valid for 3 days
url = blob.generate_signed_url(expiration, method="GET",
credentials=credentials)
I've read through the issue tracker here https://github.com/GoogleCloudPlatform/google-cloud-python/issues?page=2&q=is%3Aissue+is%3Aopen and nothing related jumps out so I am assuming this should work. Cannot see what's going wrong here.
|
[
"I was having the same issue. Ended up fixing it by starting the storage client directly from the service account json.\nstorage_client = storage.Client.from_service_account_json('path_to_service_account_key.json')\n\nI know I'm late to the party but hopefully this helps!\n",
"Currently, it's not possible to use blob.generate_signed_url without explicitly referencing credentials. (Source: Google-Cloud-Python documentation) However, you can do a workaround, as seen here, which consists of:\nsigning_credentials = compute_engine.IDTokenCredentials(\n auth_request,\n \"\",\n service_account_email=credentials.service_account_email\n)\nsigned_url = signed_blob_path.generate_signed_url(\n expires_at_ms,\n credentials=signing_credentials,\n version=\"v4\"\n)\n\n",
"A much complete snippet for those asking where other elements come from. cc @AlbertoVitoriano\n from google.auth.transport import requests\n from google.auth import default, compute_engine\n \n credentials, _ = default()\n \n # then within your abstraction\n auth_request = requests.Request()\n credentials.refresh(auth_request)\n \n signing_credentials = compute_engine.IDTokenCredentials(\n auth_request,\n \"\",\n service_account_email=credentials.service_account_email\n )\n signed_url = signed_blob_path.generate_signed_url(\n expires_at_ms,\n credentials=signing_credentials,\n version=\"v4\"\n )\n\n"
] |
[
15,
11,
0
] |
[] |
[] |
[
"google_cloud_python",
"google_cloud_storage",
"google_compute_engine",
"python"
] |
stackoverflow_0046540894_google_cloud_python_google_cloud_storage_google_compute_engine_python.txt
|
Q:
An output image file with red contours of all objects
I have the following code:
import cv2 as cv
import numpy as np
image = cv.imread("input1.jpg")
img_gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
img_denoised = cv.GaussianBlur(img_gray,(5,5),2)
ret, thresh = cv.threshold(img_denoised, 216, 255, cv.THRESH_BINARY)
kernel = np.ones((1,1),np.uint8)
opening = cv.dilate(thresh, kernel)
opening = cv.erode(opening, kernel)
# detect the contours on the binary image using cv.CHAIN_APPROX_NONE
contours, hierarchy = cv.findContours(image=opening, mode=cv.RETR_TREE, method=cv.CHAIN_APPROX_NONE)
for i in contours:
x, y, w, h = cv.boundingRect(i)
cv.drawContours(image, [i], -1, (0, 0, 255), 2)
cv.imshow("A.jpg", image)
cv.waitKey(0)
cv.destroyAllWindows()
Output:
enter image description here
It only shows the stars with a red contours but I want all the text to have a red contours, including the background. Here is the original file:
enter image description here
Many thanks in advance!
A:
I messed with this a bit and the best outcome I could get was the following, I think with some tweaking you could ignore the shading, as I'm converting it to grayscale it seems to be dropping the correct contour on the shapes, but the text is working as expected;
import cv2
import numpy as np
src = cv2.imread('c:\\input1.jpg')
gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
# blur
blur = cv2.GaussianBlur(gray, (3, 3), 0)
# canny edge
canny = cv2.Canny(blur, 100, 200)
# dilate
kernel = np.ones((5, 5))
dilate = cv2.dilate(canny, kernel, iterations=1)
# find contours
contours, hierarchy = cv2.findContours(
dilate, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
# draw contours
cv2.drawContours(src, contours, -1, (0, 255, 0), 3)
cv2.imshow("a.jpg", src)
cv2.waitKey()
|
An output image file with red contours of all objects
|
I have the following code:
import cv2 as cv
import numpy as np
image = cv.imread("input1.jpg")
img_gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
img_denoised = cv.GaussianBlur(img_gray,(5,5),2)
ret, thresh = cv.threshold(img_denoised, 216, 255, cv.THRESH_BINARY)
kernel = np.ones((1,1),np.uint8)
opening = cv.dilate(thresh, kernel)
opening = cv.erode(opening, kernel)
# detect the contours on the binary image using cv.CHAIN_APPROX_NONE
contours, hierarchy = cv.findContours(image=opening, mode=cv.RETR_TREE, method=cv.CHAIN_APPROX_NONE)
for i in contours:
x, y, w, h = cv.boundingRect(i)
cv.drawContours(image, [i], -1, (0, 0, 255), 2)
cv.imshow("A.jpg", image)
cv.waitKey(0)
cv.destroyAllWindows()
Output:
enter image description here
It only shows the stars with a red contours but I want all the text to have a red contours, including the background. Here is the original file:
enter image description here
Many thanks in advance!
|
[
"I messed with this a bit and the best outcome I could get was the following, I think with some tweaking you could ignore the shading, as I'm converting it to grayscale it seems to be dropping the correct contour on the shapes, but the text is working as expected;\nimport cv2\nimport numpy as np\n\nsrc = cv2.imread('c:\\\\input1.jpg')\n\ngray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)\n# blur\nblur = cv2.GaussianBlur(gray, (3, 3), 0)\n# canny edge\ncanny = cv2.Canny(blur, 100, 200)\n# dilate\nkernel = np.ones((5, 5))\ndilate = cv2.dilate(canny, kernel, iterations=1)\n# find contours\ncontours, hierarchy = cv2.findContours(\n dilate, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)\n# draw contours\ncv2.drawContours(src, contours, -1, (0, 255, 0), 3)\n\ncv2.imshow(\"a.jpg\", src)\ncv2.waitKey()\n\n\n"
] |
[
1
] |
[] |
[] |
[
"opencv",
"python"
] |
stackoverflow_0074526315_opencv_python.txt
|
Q:
UnboundLocalError - local variable 'emprendedores' referenced before assignment
I can't figure out why am I getting this error message: "UnboundLocalError - local variable 'emprendedores' referenced before assignment"
enter image description here
Hey fellows, i'm building an app in Django and almost is pretty well. However, I cannot find solution to a problem in my search view. The main idea is allowing the user to indicate the word and to select the desired fields to search into from an form, and returning the registered users that satisfy the criteria.
The html file looks like this:
enter image description here
This is the model:
enter image description here
and this is the view I'm working on:
enter image description here
But I can't figure out why am I getting this error message: "UnboundLocalError - local variable 'emprendedores' referenced before assignment"
enter image description here
I'll be glad if someone can help my out.
A:
This is the error:
UnboundLocalError at /consulta/
local variable 'emprendedores' referenced before assignment
Request Method: POST
Request URL: http://127.0.0.1:8000/consulta/
Django Version: 3.2.8
Exception Type: UnboundLocalError
Exception Value:
local variable 'emprendedores' referenced before assignment
Exception Location: C:\Users\Jobert Gutierrez\Documents\PROYECTOS\DESPRO\BARDEP\views.py, line 112, in Consulta
Python Executable: C:\ProgramData\Anaconda3\python.exe
Python Version: 3.9.7
This is the View:
def Consulta(request):
if request.method == "POST":
#fields = Emprendedores._meta.get_fields()
fields = request.POST.getlist('campos')
busqueda = request.POST['busqueda']
query = Q()
if (busqueda.isnumeric()):
emprendedores = Emprendedores.objects.filter(numerodocumento__contains=busqueda)
messages.success(request,("No existen coincidencias para su búsqueda"))
else:
for columna in fields:
if columna in Emprendedores._meta.get_fields():
condicion = {f'{columna}__icontains': busqueda }
query |= Q(**condicion)
query.connector = 'OR'
emprendedores = Emprendedores.objects.filter(query)
elif columna in SectorEconomico._meta.get_fields():
query1 = SectorEconomico.objects.filter(nombresector__icontains=busqueda)
emprendedores = Emprendedores.objects.filter(sectoreco__pk=F('query1__pk'))
return emprendedores
return emprendedores
return render(request,'buscados.html',{'emprendedores':emprendedores})
else:
return render(request,'consulta.html')
How can I send it to the view?
|
UnboundLocalError - local variable 'emprendedores' referenced before assignment
|
I can't figure out why am I getting this error message: "UnboundLocalError - local variable 'emprendedores' referenced before assignment"
enter image description here
Hey fellows, i'm building an app in Django and almost is pretty well. However, I cannot find solution to a problem in my search view. The main idea is allowing the user to indicate the word and to select the desired fields to search into from an form, and returning the registered users that satisfy the criteria.
The html file looks like this:
enter image description here
This is the model:
enter image description here
and this is the view I'm working on:
enter image description here
But I can't figure out why am I getting this error message: "UnboundLocalError - local variable 'emprendedores' referenced before assignment"
enter image description here
I'll be glad if someone can help my out.
|
[
"This is the error:\nUnboundLocalError at /consulta/\nlocal variable 'emprendedores' referenced before assignment\nRequest Method: POST\nRequest URL: http://127.0.0.1:8000/consulta/\nDjango Version: 3.2.8\nException Type: UnboundLocalError\nException Value: \nlocal variable 'emprendedores' referenced before assignment\nException Location: C:\\Users\\Jobert Gutierrez\\Documents\\PROYECTOS\\DESPRO\\BARDEP\\views.py, line 112, in Consulta\nPython Executable: C:\\ProgramData\\Anaconda3\\python.exe\nPython Version: 3.9.7\n\nThis is the View:\ndef Consulta(request):\n if request.method == \"POST\":\n #fields = Emprendedores._meta.get_fields()\n fields = request.POST.getlist('campos')\n busqueda = request.POST['busqueda']\n query = Q()\n if (busqueda.isnumeric()):\n emprendedores = Emprendedores.objects.filter(numerodocumento__contains=busqueda)\n messages.success(request,(\"No existen coincidencias para su búsqueda\"))\n else:\n for columna in fields:\n if columna in Emprendedores._meta.get_fields():\n condicion = {f'{columna}__icontains': busqueda }\n query |= Q(**condicion)\n query.connector = 'OR'\n emprendedores = Emprendedores.objects.filter(query) \n elif columna in SectorEconomico._meta.get_fields():\n query1 = SectorEconomico.objects.filter(nombresector__icontains=busqueda) \n emprendedores = Emprendedores.objects.filter(sectoreco__pk=F('query1__pk'))\n return emprendedores\n return emprendedores\n return render(request,'buscados.html',{'emprendedores':emprendedores})\n else:\n return render(request,'consulta.html')\n\nHow can I send it to the view?\n"
] |
[
0
] |
[] |
[] |
[
"django",
"django_errors",
"django_views",
"python"
] |
stackoverflow_0074525798_django_django_errors_django_views_python.txt
|
Q:
Adding a word after every particular word in a list in Python
I'm sorry if my Title seems kinda weird, English is not my first Language and I didn't know how to express myself correctly.
I have a list and I want to add a word every time after a particular word:
Example:
list = ['add', 'add', 'ball', 'cup', 'add']
Expected result:
list = ['add','Nice', 'add', 'Nice, 'ball', 'cup', 'add','Nice']
I tried including a:
for word in list:
if 'add' in word:
list.insert(((list.index(word))+1,'Nice')
But my loop keeps adding only on the first 'add', and go eternal.
I tried doing something like this:
for word in list:
if 'add' in word:
local = list.index(word) + 1
if list[local] == 'Nice':
pass
else:
list.insert(local,'Nice')
It stops the eternal loop, but the second 'add' doesn't get a 'Nice',
I get a: ['add', 'Nice', 'add', 'ball', 'cup', 'add']
It looks like my "for word in list" only sees a singular 'add'.
A:
Mutating the list you're iterating over easily leads to unexpected results since the internal iterator of the loop has no idea of your modification to the sequence.
Instead, you can create a new list to append output to:
lst = ['add', 'add', 'ball', 'cup', 'add']
output = []
for word in lst:
output.append(word)
if word == 'add':
output.append('Nice')
print(output)
This outputs:
['add', 'Nice', 'add', 'Nice', 'ball', 'cup', 'add', 'Nice']
A:
Here is a very shorthand way to do what you want using sum() (for short lists)...
https://docs.python.org/3/library/functions.html#sum
words = ['add', 'add', 'ball', 'cup', 'add']
sum(([v,'Nice'] if v == 'add' else [v] for v in words), [])
Output is:
['add', 'Nice', 'add', 'Nice', 'ball', 'cup', 'add', 'Nice']
Also see itertools.chain() for longer lists as it is more efficient.
|
Adding a word after every particular word in a list in Python
|
I'm sorry if my Title seems kinda weird, English is not my first Language and I didn't know how to express myself correctly.
I have a list and I want to add a word every time after a particular word:
Example:
list = ['add', 'add', 'ball', 'cup', 'add']
Expected result:
list = ['add','Nice', 'add', 'Nice, 'ball', 'cup', 'add','Nice']
I tried including a:
for word in list:
if 'add' in word:
list.insert(((list.index(word))+1,'Nice')
But my loop keeps adding only on the first 'add', and go eternal.
I tried doing something like this:
for word in list:
if 'add' in word:
local = list.index(word) + 1
if list[local] == 'Nice':
pass
else:
list.insert(local,'Nice')
It stops the eternal loop, but the second 'add' doesn't get a 'Nice',
I get a: ['add', 'Nice', 'add', 'ball', 'cup', 'add']
It looks like my "for word in list" only sees a singular 'add'.
|
[
"Mutating the list you're iterating over easily leads to unexpected results since the internal iterator of the loop has no idea of your modification to the sequence.\nInstead, you can create a new list to append output to:\nlst = ['add', 'add', 'ball', 'cup', 'add']\noutput = []\nfor word in lst:\n output.append(word)\n if word == 'add':\n output.append('Nice')\nprint(output)\n\nThis outputs:\n['add', 'Nice', 'add', 'Nice', 'ball', 'cup', 'add', 'Nice']\n\n",
"Here is a very shorthand way to do what you want using sum() (for short lists)...\nhttps://docs.python.org/3/library/functions.html#sum\nwords = ['add', 'add', 'ball', 'cup', 'add']\n\nsum(([v,'Nice'] if v == 'add' else [v] for v in words), [])\n\nOutput is:\n['add', 'Nice', 'add', 'Nice', 'ball', 'cup', 'add', 'Nice']\n\nAlso see itertools.chain() for longer lists as it is more efficient.\n"
] |
[
1,
0
] |
[] |
[] |
[
"for_loop",
"list",
"python"
] |
stackoverflow_0074526532_for_loop_list_python.txt
|
Q:
Error trying to make a discord selfbot in python
So I'm trying to make a discord selfbot in python and I got this error
Traceback (most recent call last):
File "C:\Users\tauga\Documents\luna.py", line 4, in <module>
client = commands.Bot(command_prefix="*", self_bot=True, help_command=False)
TypeError: __init__() missing 1 required keyword-only argument: 'intents'
I have tried rewriting the code many times and nothing has worked
My code
import discord
from discord.ext import commands
client = commands.Bot(command_prefix="*", self_bot=True, help_command=False)
token="my discord token that i'm not showing"
@client.event
async def on_ready():
print("Luna Online")
@client.command()
async def test(ctx):
await ctx.send("luna Test Command")
client.run(token, bot=False)
If anyone could help that would be great!
A:
Try this client= commands.Bot(command_prefix='!', intents=discord.Intents.all())
Your error was because discord api requires intents, which you never set.
To run the bot use client.run("token", bot=False)
And for the command, use ctx.channel.send("test message here")
Please note, self botting is a very bad idea, and will likely result in getting banned.
|
Error trying to make a discord selfbot in python
|
So I'm trying to make a discord selfbot in python and I got this error
Traceback (most recent call last):
File "C:\Users\tauga\Documents\luna.py", line 4, in <module>
client = commands.Bot(command_prefix="*", self_bot=True, help_command=False)
TypeError: __init__() missing 1 required keyword-only argument: 'intents'
I have tried rewriting the code many times and nothing has worked
My code
import discord
from discord.ext import commands
client = commands.Bot(command_prefix="*", self_bot=True, help_command=False)
token="my discord token that i'm not showing"
@client.event
async def on_ready():
print("Luna Online")
@client.command()
async def test(ctx):
await ctx.send("luna Test Command")
client.run(token, bot=False)
If anyone could help that would be great!
|
[
"Try this client= commands.Bot(command_prefix='!', intents=discord.Intents.all())\nYour error was because discord api requires intents, which you never set.\nTo run the bot use client.run(\"token\", bot=False)\nAnd for the command, use ctx.channel.send(\"test message here\")\nPlease note, self botting is a very bad idea, and will likely result in getting banned.\n"
] |
[
0
] |
[] |
[] |
[
"discord",
"discord.py",
"python",
"python_3.x"
] |
stackoverflow_0074524007_discord_discord.py_python_python_3.x.txt
|
Q:
Vs code doesn't regognize tkinter on pop os
I have a code, where i use tkinter to make a window and stuff. It's a brawler picker for brawl stars. Im using pop os-linux and vs code and i have tried so many ways, but anything doesn't work.
When i run the code, i get this:
(.venv) sh-5.1$ python -u "/home/"my_name"/Documents/Vs-code_projektit/Joku.py"
Traceback (most recent call last):
File "/home/"my_name"/Documents/Vs-code_projektit/Joku.py", line 2, in <module>
from tkinter import *
ModuleNotFoundError: No module named 'tkinter'
And in the vs code itself, it regognizes the tkinter and turns the text green, but after that nothing relating to tkinter doesn't work and i shows an error. Btw i have the full code already cause i copied from my dual boot windows and i wanted to try it here,
What should i do to make it work?
EDIT:
For everybody who has the same problem, it may be caused by the app version. I posted this on reddit cause i didn't get answer in time, and someone suggested that i download vs code with appimage, snap, or in my case pop!_os Installation.
MAIN POINT: Someone said that NEVER use FLATPACK with ides. It may work for other apps but never use it with ides. It can't handle system packages or modules.
A:
First of all, you need to know what interpreter is currently used by vscode, which is displayed in the lower right corner of the interface.
Clicking on the displayed python version will open a Select Interpreter panel where you can select the interpreter with the tkinter package installed to run the code
Or you can install the tkinter package for the currently used interpreter.
<path-to-current-python.exe> -m pip install tkinter
EDIT
From your terminal information it can be seen that you have activated the virtual environment, but you are running the code with Code Runner.
As a reminder, Code Runner doesn't change interpreters as you select another interpreter in the Select Interpreter panel. So please use the Run Pythonn File option provided by the official Python extension to run the code.
|
Vs code doesn't regognize tkinter on pop os
|
I have a code, where i use tkinter to make a window and stuff. It's a brawler picker for brawl stars. Im using pop os-linux and vs code and i have tried so many ways, but anything doesn't work.
When i run the code, i get this:
(.venv) sh-5.1$ python -u "/home/"my_name"/Documents/Vs-code_projektit/Joku.py"
Traceback (most recent call last):
File "/home/"my_name"/Documents/Vs-code_projektit/Joku.py", line 2, in <module>
from tkinter import *
ModuleNotFoundError: No module named 'tkinter'
And in the vs code itself, it regognizes the tkinter and turns the text green, but after that nothing relating to tkinter doesn't work and i shows an error. Btw i have the full code already cause i copied from my dual boot windows and i wanted to try it here,
What should i do to make it work?
EDIT:
For everybody who has the same problem, it may be caused by the app version. I posted this on reddit cause i didn't get answer in time, and someone suggested that i download vs code with appimage, snap, or in my case pop!_os Installation.
MAIN POINT: Someone said that NEVER use FLATPACK with ides. It may work for other apps but never use it with ides. It can't handle system packages or modules.
|
[
"First of all, you need to know what interpreter is currently used by vscode, which is displayed in the lower right corner of the interface.\n\nClicking on the displayed python version will open a Select Interpreter panel where you can select the interpreter with the tkinter package installed to run the code\n\nOr you can install the tkinter package for the currently used interpreter.\n<path-to-current-python.exe> -m pip install tkinter\n\n\nEDIT\nFrom your terminal information it can be seen that you have activated the virtual environment, but you are running the code with Code Runner.\n\nAs a reminder, Code Runner doesn't change interpreters as you select another interpreter in the Select Interpreter panel. So please use the Run Pythonn File option provided by the official Python extension to run the code.\n\n"
] |
[
0
] |
[] |
[] |
[
"linux",
"python",
"tkinter",
"visual_studio_code"
] |
stackoverflow_0074518489_linux_python_tkinter_visual_studio_code.txt
|
Q:
What does the Abstract Base Class register method actually do?
I am confused about the ABC register method.
Take the following code:
import io
from abc import ABCMeta, abstractmethod
class IStream(metaclass=ABCMeta):
@abstractmethod
def read(self, maxbytes=-1):
pass
@abstractmethod
def write(self, data):
pass
IStream.register(io.IOBase)
f = open('foo.txt')
isinstance(f, Istream) # returns true
When you register io.IOBase what exactly happens? Are you saying that IOBase class can only have methods defined by Istream ABC class going forward? What is the benefit of ABC registering other classes?
A:
It simply makes issubclass(io.IOBase, IStream) return True (which then implies that an instance of io.IOBase is an instance of IStream). It is up to the programmer registering the class to ensure that io.IOBase actually conforms to the API defined by IStream.
The reason is to let you define an interface in the form of IStream, and let you indicate that a class that may not have actually inherited from IStream satisfies the interface. Essentially, it is just formalized duck typing.
A:
For example, we can replace Cat class extending Animal class below:
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def sound(self):
pass
# ↓↓↓ Here ↓↓↓
class Cat(Animal):
def sound(self):
print("Meow!!")
# ↑↑↑ Here ↑↑↑
print(issubclass(Cat, Animal))
With this code having register() below:
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def sound(self):
pass
# ↓↓↓ Here ↓↓↓
class Cat:
def sound(self):
print("Meow!!")
Animal.register(Cat)
# ↑↑↑ Here ↑↑↑
print(issubclass(Cat, Animal))
Then, both of the code above outputs the same result below showing Cat class is the subclass of Animal class:
True
|
What does the Abstract Base Class register method actually do?
|
I am confused about the ABC register method.
Take the following code:
import io
from abc import ABCMeta, abstractmethod
class IStream(metaclass=ABCMeta):
@abstractmethod
def read(self, maxbytes=-1):
pass
@abstractmethod
def write(self, data):
pass
IStream.register(io.IOBase)
f = open('foo.txt')
isinstance(f, Istream) # returns true
When you register io.IOBase what exactly happens? Are you saying that IOBase class can only have methods defined by Istream ABC class going forward? What is the benefit of ABC registering other classes?
|
[
"It simply makes issubclass(io.IOBase, IStream) return True (which then implies that an instance of io.IOBase is an instance of IStream). It is up to the programmer registering the class to ensure that io.IOBase actually conforms to the API defined by IStream.\nThe reason is to let you define an interface in the form of IStream, and let you indicate that a class that may not have actually inherited from IStream satisfies the interface. Essentially, it is just formalized duck typing.\n",
"For example, we can replace Cat class extending Animal class below:\nfrom abc import ABC, abstractmethod\n\nclass Animal(ABC):\n @abstractmethod\n def sound(self):\n pass\n\n# ↓↓↓ Here ↓↓↓\n\nclass Cat(Animal):\n def sound(self):\n print(\"Meow!!\")\n\n# ↑↑↑ Here ↑↑↑\n\nprint(issubclass(Cat, Animal))\n\nWith this code having register() below:\nfrom abc import ABC, abstractmethod\n\nclass Animal(ABC):\n @abstractmethod\n def sound(self):\n pass\n\n# ↓↓↓ Here ↓↓↓\n\nclass Cat:\n def sound(self):\n print(\"Meow!!\")\n \nAnimal.register(Cat)\n\n# ↑↑↑ Here ↑↑↑\n\nprint(issubclass(Cat, Animal))\n\nThen, both of the code above outputs the same result below showing Cat class is the subclass of Animal class:\nTrue\n\n"
] |
[
2,
0
] |
[] |
[] |
[
"python",
"python_3.x"
] |
stackoverflow_0059740972_python_python_3.x.txt
|
Q:
Frozenset Intersection with Wildcards
I'm trying to intersect frozensets in Python, but not getting the desired result. My intersection array, LCC, has 100s of strings.
LCC = ['A','E...']
fs1 = frozenset('A')
fs2 = frozenset('E830')
fs1.intersection(LCC)
fs2.intersection(LCC)
The results are:
frozenset({'A'})
frozenset()
I would expect the second function to yield frozenset({'E830'})
Does anyone known how to get this to work with wildcards? Or is it impossible since the string being passed in to LCC is interpreting the wildcards literally?
A:
I assume your '...' is a wildcard pattern meaning any characters of length three.(Regular expression syntax)
You can use regular expressions like this.
import re
LCC = ['A', 'E...']
fs = frozenset({'A', 'E830', 'E2'})
re_patterns = [re.compile(pattern) for pattern in LCC]
intersection = {e for e in fs for pattern in re_patterns
if re.fullmatch(pattern, e)}
print(intersection)
This will output the following.
{'A', 'E830'}
|
Frozenset Intersection with Wildcards
|
I'm trying to intersect frozensets in Python, but not getting the desired result. My intersection array, LCC, has 100s of strings.
LCC = ['A','E...']
fs1 = frozenset('A')
fs2 = frozenset('E830')
fs1.intersection(LCC)
fs2.intersection(LCC)
The results are:
frozenset({'A'})
frozenset()
I would expect the second function to yield frozenset({'E830'})
Does anyone known how to get this to work with wildcards? Or is it impossible since the string being passed in to LCC is interpreting the wildcards literally?
|
[
"I assume your '...' is a wildcard pattern meaning any characters of length three.(Regular expression syntax)\nYou can use regular expressions like this.\nimport re\n\nLCC = ['A', 'E...']\nfs = frozenset({'A', 'E830', 'E2'})\n\nre_patterns = [re.compile(pattern) for pattern in LCC]\nintersection = {e for e in fs for pattern in re_patterns\n if re.fullmatch(pattern, e)}\nprint(intersection)\n\nThis will output the following.\n{'A', 'E830'}\n\n"
] |
[
0
] |
[] |
[] |
[
"frozenset",
"intersection",
"python",
"wildcard"
] |
stackoverflow_0074525886_frozenset_intersection_python_wildcard.txt
|
Q:
Show class docstring in VSCode
There are some classes written with the docstring at the class level, as opposed to under methods like the init method, for example PyTorch's CrossEntropy loss class.
How can I show the class docstring in VSCode with a shortcut, similar to this question?
A:
Set these three key-bindings in the picture.
Click or move the cursor to what you want to display the content
Use the shortcuts to get.
You can also use the methods in the comments, hover over an instance of that class with your mouse.
|
Show class docstring in VSCode
|
There are some classes written with the docstring at the class level, as opposed to under methods like the init method, for example PyTorch's CrossEntropy loss class.
How can I show the class docstring in VSCode with a shortcut, similar to this question?
|
[
"\n\nSet these three key-bindings in the picture.\nClick or move the cursor to what you want to display the content\nUse the shortcuts to get.\n\nYou can also use the methods in the comments, hover over an instance of that class with your mouse.\n"
] |
[
0
] |
[] |
[] |
[
"python",
"visual_studio_code"
] |
stackoverflow_0074523665_python_visual_studio_code.txt
|
Q:
How do I spell out each inputted digits in python
I need to make a program that takes an integer input and when you enter a number, it types out the spelling of each digit. For example, I inputted 12, the program will print out:
One
Two
I have a little problem with the code, how do I print out the results (or the spellings) vertically and in separate lines? The output should be:
Enter the number: 86
Eight
Six
But my output is:
Enter the number: 86
Eight Six
I just need it to print vertically and in different lines like I said. Thank you! You can alter the code itself too, This is my code:
arr = ['Zero','One','Two','Three','Four','Five','Six','Seven','Eight','Nine']
def number_2_word(num):
if(num==0):
return ""
else:
small_ans = arr[num%10]
ans = number_2_word(int(num/10)) + small_ans + " "
return ans
num = int(input("Enter the number: "))
print(end="")
print(number_2_word(num))
A:
In this line:
ans = number_2_word(int(num/10)) + small_ans + " "
Use line break rather than space
ans = number_2_word(int(num / 10)) + small_ans + "\n"
I did a few tests, seems work as you expected
|
How do I spell out each inputted digits in python
|
I need to make a program that takes an integer input and when you enter a number, it types out the spelling of each digit. For example, I inputted 12, the program will print out:
One
Two
I have a little problem with the code, how do I print out the results (or the spellings) vertically and in separate lines? The output should be:
Enter the number: 86
Eight
Six
But my output is:
Enter the number: 86
Eight Six
I just need it to print vertically and in different lines like I said. Thank you! You can alter the code itself too, This is my code:
arr = ['Zero','One','Two','Three','Four','Five','Six','Seven','Eight','Nine']
def number_2_word(num):
if(num==0):
return ""
else:
small_ans = arr[num%10]
ans = number_2_word(int(num/10)) + small_ans + " "
return ans
num = int(input("Enter the number: "))
print(end="")
print(number_2_word(num))
|
[
"In this line:\nans = number_2_word(int(num/10)) + small_ans + \" \"\n\nUse line break rather than space\nans = number_2_word(int(num / 10)) + small_ans + \"\\n\"\n\nI did a few tests, seems work as you expected\n"
] |
[
0
] |
[] |
[] |
[
"for_loop",
"loops",
"python",
"while_loop"
] |
stackoverflow_0074526674_for_loop_loops_python_while_loop.txt
|
Q:
Selenium_Datepicker (Calendar) Python
I am writing code with selenium to fulfill information in a websites. I am not able to instruct the code to select a specific date.
Here is the html code:
<div id="subview1:itemViewFragment1:itemForm1:texti0023_POPUP" name="subview1:itemViewFragment1:itemForm1:texti0023_POPUP_HXPOPUP" style="position: absolute; top: 482px; left: 425px; z-index: 1000000; padding: 0px; margin: 0px; vertical-align: top; overflow: visible; display: block; visibility: visible;" class="inputText_DatePicker">
<table id="subview1:itemViewFragment1:itemForm1:texti0023_POPUP_TABLE" border="0" cellspacing="0" cellpadding="0" class="inputText_DatePicker-Size">
<tbody><tr><td valign="top" align="left">
<table id="subview1:itemViewFragment1:itemForm1:texti0023_POPUP_HDR_TABLE" border="0" cellspacing="0" cellpadding="0" class="inputText_DatePicker-Header" width="100%">
<tbody><tr><td valign="middle" align="right" class="inputText_DatePicker-HeaderLine1">
<img id="subview1:itemViewFragment1:itemForm1:texti0023_POPUP_DAY_20221129O" class="inputText_DatePicker-CurrentMonth" tabindex="1" style="cursor: pointer;">
<span unselectable="on">29</span>
</td><td valign="middle" align="center" id="subview1:itemViewFragment1:itemForm1:texti0023_POPUP_DAY_20221130O" class="inputText_DatePicker-CurrentMonth" tabindex="1" style="cursor: pointer;">
<span unselectable="on">30</span>
</td><td valign="middle" align="center" id="subview1:itemViewFragment1:itemForm1:texti0023_POPUP_DAY_20221201X"
i've tried all the code in this website but did not find a solution.
|
Selenium_Datepicker (Calendar) Python
|
I am writing code with selenium to fulfill information in a websites. I am not able to instruct the code to select a specific date.
Here is the html code:
<div id="subview1:itemViewFragment1:itemForm1:texti0023_POPUP" name="subview1:itemViewFragment1:itemForm1:texti0023_POPUP_HXPOPUP" style="position: absolute; top: 482px; left: 425px; z-index: 1000000; padding: 0px; margin: 0px; vertical-align: top; overflow: visible; display: block; visibility: visible;" class="inputText_DatePicker">
<table id="subview1:itemViewFragment1:itemForm1:texti0023_POPUP_TABLE" border="0" cellspacing="0" cellpadding="0" class="inputText_DatePicker-Size">
<tbody><tr><td valign="top" align="left">
<table id="subview1:itemViewFragment1:itemForm1:texti0023_POPUP_HDR_TABLE" border="0" cellspacing="0" cellpadding="0" class="inputText_DatePicker-Header" width="100%">
<tbody><tr><td valign="middle" align="right" class="inputText_DatePicker-HeaderLine1">
<img id="subview1:itemViewFragment1:itemForm1:texti0023_POPUP_DAY_20221129O" class="inputText_DatePicker-CurrentMonth" tabindex="1" style="cursor: pointer;">
<span unselectable="on">29</span>
</td><td valign="middle" align="center" id="subview1:itemViewFragment1:itemForm1:texti0023_POPUP_DAY_20221130O" class="inputText_DatePicker-CurrentMonth" tabindex="1" style="cursor: pointer;">
<span unselectable="on">30</span>
</td><td valign="middle" align="center" id="subview1:itemViewFragment1:itemForm1:texti0023_POPUP_DAY_20221201X"
i've tried all the code in this website but did not find a solution.
|
[] |
[] |
[
"<div id=\"subview1:itemViewFragment1:itemForm1:texti0023_POPUP\" name=\"subview1:itemViewFragment1:itemForm1:texti0023_POPUP_HXPOPUP\" style=\"position: absolute; top: 482px; left: 425px; z-index: 1000000; padding: 0px; margin: 0px; vertical-align: top; overflow: visible; display: block; visibility: visible;\" class=\"inputText_DatePicker\"><table id=\"subview1:itemViewFragment1:itemForm1:texti0023_POPUP_TABLE\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"inputText_DatePicker-Size\"><tbody><tr><td valign=\"top\" align=\"left\"><table id=\"subview1:itemViewFragment1:itemForm1:texti0023_POPUP_HDR_TABLE\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"inputText_DatePicker-Header\" width=\"100%\"><tbody><tr><td valign=\"middle\" align=\"right\" class=\"inputText_DatePicker-HeaderLine1\"><img id=\"subview1:itemViewFragment1:itemForm1:texti0023_POPUP_HDRBTN1\" class=\"inputText_DatePicker-Button\" src=\"https://www.cdsservices.ca/solutions/isin/.ibmjsfres/img/1x1.gif\" title=\"Previous year\" alt=\"Previous year\" style=\"background-image: url("https://www.cdsservices.ca/solutions/isin/.ibmjsfres/img/hinkies_vlg_v3_0_12.gif"); background-position: 0px -12px; background-repeat: no-repeat; margin: 0px; cursor: pointer;\"></td><td valign=\"middle\" align=\"center\" class=\"inputText_DatePicker-HeaderYear\">2022</td><td valign=\"middle\" align=\"left\" class=\"inputText_DatePicker-HeaderLine1\"><img id=\"subview1:itemViewFragment1:itemForm1:texti0023_POPUP_HDRBTN2\" class=\"inputText_DatePicker-Button\" src=\"https://www.cdsservices.ca/solutions/isin/.ibmjsfres/img/1x1.gif\" title=\"Next year\" alt=\"Next year\" style=\"background-image: url("https://www.cdsservices.ca/solutions/isin/.ibmjsfres/img/hinkies_vlg_v3_0_12.gif"); background-position: 0px 0px; background-repeat: no-repeat; margin: 0px; cursor: pointer;\"></td></tr><tr><td valign=\"middle\" align=\"right\" class=\"inputText_DatePicker-HeaderLine2\"><img id=\"subview1:itemViewFragment1:itemForm1:texti0023_POPUP_HDRBTN3\" class=\"inputText_DatePicker-Button\" src=\"https://www.cdsservices.ca/solutions/isin/.ibmjsfres/img/1x1.gif\" title=\"Previous month\" alt=\"Previous month\" style=\"background-image: url("https://www.cdsservices.ca/solutions/isin/.ibmjsfres/img/hinkies_vlg_v3_0_12.gif"); background-position: 0px -12px; background-repeat: no-repeat; margin: 0px; cursor: pointer;\"></td><td valign=\"middle\" align=\"center\" class=\"inputText_DatePicker-HeaderMonth\">November</td><td valign=\"middle\" align=\"left\" class=\"inputText_DatePicker-HeaderLine2\"><img id=\"subview1:itemViewFragment1:itemForm1:texti0023_POPUP_HDRBTN4\" class=\"inputText_DatePicker-Button\" src=\"https://www.cdsservices.ca/solutions/isin/.ibmjsfres/img/1x1.gif\" title=\"Next month\" alt=\"Next month\" style=\"background-image: url("https://www.cdsservices.ca/solutions/isin/.ibmjsfres/img/hinkies_vlg_v3_0_12.gif"); background-position: 0px 0px; background-repeat: no-repeat; margin: 0px; cursor: pointer;\"></td></tr></tbody></table></td></tr><tr><td valign=\"top\" align=\"left\"><table id=\"subview1:itemViewFragment1:itemForm1:texti0023_POPUP_BODY_TABLE\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"inputText_DatePicker-Body\" width=\"100%\"><tbody><tr><td valign=\"middle\" align=\"center\" class=\"inputText_DatePicker-HeaderWeekday\" style=\"cursor: pointer;\"><span unselectable=\"on\">S</span></td><td valign=\"middle\" align=\"center\" class=\"inputText_DatePicker-HeaderWeekday\" style=\"cursor: pointer;\"><span unselectable=\"on\">M</span></td><td valign=\"middle\" align=\"center\" class=\"inputText_DatePicker-HeaderWeekday\" style=\"cursor: pointer;\"><span unselectable=\"on\">T</span></td><td valign=\"middle\" align=\"center\" class=\"inputText_DatePicker-HeaderWeekday\" style=\"cursor: pointer;\"><span unselectable=\"on\">W</span></td><td valign=\"middle\" align=\"center\" class=\"inputText_DatePicker-HeaderWeekday\" style=\"cursor: pointer;\"><span unselectable=\"on\">T</span></td><td valign=\"middle\" align=\"center\" class=\"inputText_DatePicker-HeaderWeekday\" style=\"cursor: pointer;\"><span unselectable=\"on\">F</span></td><td valign=\"middle\" align=\"center\" class=\"inputText_DatePicker-HeaderWeekday\" style=\"cursor: pointer;\"><span unselectable=\"on\">S</span></td></tr><tr><td valign=\"middle\" align=\"center\" id=\"subview1:itemViewFragment1:itemForm1:texti0023_POPUP_DAY_20221030X\" class=\"inputText_DatePicker-OtherMonth\" tabindex=\"1\" style=\"cursor: pointer;\"><span unselectable=\"on\">30</span></td><td valign=\"middle\" align=\"center\" id=\"subview1:itemViewFragment1:itemForm1:texti0023_POPUP_DAY_20221031X\" class=\"inputText_DatePicker-OtherMonth\" tabindex=\"1\" style=\"cursor: pointer;\"><span unselectable=\"on\">31</span></td><td valign=\"middle\" align=\"center\" id=\"subview1:itemViewFragment1:itemForm1:texti0023_POPUP_DAY_20221101O\" class=\"inputText_DatePicker-CurrentMonth\" tabindex=\"1\" style=\"cursor: pointer;\"><span unselectable=\"on\">1</span></td><td valign=\"middle\" align=\"center\" id=\"subview1:itemViewFragment1:itemForm1:texti0023_POPUP_DAY_20221102O\" class=\"inputText_DatePicker-CurrentMonth\" tabindex=\"1\" style=\"cursor: pointer;\"><span unselectable=\"on\">2</span></td><td valign=\"middle\" align=\"center\" id=\"subview1:itemViewFragment1:itemForm1:texti0023_POPUP_DAY_20221103O\" class=\"inputText_DatePicker-CurrentMonth\" tabindex=\"1\" style=\"cursor: pointer;\"><span unselectable=\"on\">3</span></td><td valign=\"middle\" align=\"center\" id=\"subview1:itemViewFragment1:itemForm1:texti0023_POPUP_DAY_20221104O\" class=\"inputText_DatePicker-CurrentMonth\" tabindex=\"1\" style=\"cursor: pointer;\"><span unselectable=\"on\">4</span></td><td valign=\"middle\" align=\"center\" id=\"subview1:itemViewFragment1:itemForm1:texti0023_POPUP_DAY_20221105O\" class=\"inputText_DatePicker-CurrentMonth\" tabindex=\"1\" style=\"cursor: pointer;\"><span unselectable=\"on\">5</span></td></tr><tr><td valign=\"middle\" align=\"center\" id=\"subview1:itemViewFragment1:itemForm1:texti0023_POPUP_DAY_20221106O\" class=\"inputText_DatePicker-CurrentMonth\" tabindex=\"1\" style=\"cursor: pointer;\"><span unselectable=\"on\">6</span></td><td valign=\"middle\" align=\"center\" id=\"subview1:itemViewFragment1:itemForm1:texti0023_POPUP_DAY_20221107O\" class=\"inputText_DatePicker-CurrentMonth\" tabindex=\"1\" style=\"cursor: pointer;\"><span unselectable=\"on\">7</span></td><td valign=\"middle\" align=\"center\" id=\"subview1:itemViewFragment1:itemForm1:texti0023_POPUP_DAY_20221108O\" class=\"inputText_DatePicker-CurrentMonth\" tabindex=\"1\" style=\"cursor: pointer;\"><span unselectable=\"on\">8</span></td><td valign=\"middle\" align=\"center\" id=\"subview1:itemViewFragment1:itemForm1:texti0023_POPUP_DAY_20221109O\" class=\"inputText_DatePicker-CurrentMonth\" tabindex=\"1\" style=\"cursor: pointer;\"><span unselectable=\"on\">9</span></td><td valign=\"middle\" align=\"center\" id=\"subview1:itemViewFragment1:itemForm1:texti0023_POPUP_DAY_20221110O\" class=\"inputText_DatePicker-CurrentMonth\" tabindex=\"1\" style=\"cursor: pointer;\"><span unselectable=\"on\">10</span></td><td valign=\"middle\" align=\"center\" id=\"subview1:itemViewFragment1:itemForm1:texti0023_POPUP_DAY_20221111O\" class=\"inputText_DatePicker-CurrentMonth\" tabindex=\"1\" style=\"cursor: pointer;\"><span unselectable=\"on\">11</span></td><td valign=\"middle\" align=\"center\" id=\"subview1:itemViewFragment1:itemForm1:texti0023_POPUP_DAY_20221112O\" class=\"inputText_DatePicker-CurrentMonth\" tabindex=\"1\" style=\"cursor: pointer;\"><span unselectable=\"on\">12</span></td></tr><tr><td valign=\"middle\" align=\"center\" id=\"subview1:itemViewFragment1:itemForm1:texti0023_POPUP_DAY_20221113O\" class=\"inputText_DatePicker-CurrentMonth\" tabindex=\"1\" style=\"cursor: pointer;\"><span unselectable=\"on\">13</span></td><td valign=\"middle\" align=\"center\" id=\"subview1:itemViewFragment1:itemForm1:texti0023_POPUP_DAY_20221114O\" class=\"inputText_DatePicker-CurrentMonth\" tabindex=\"1\" style=\"cursor: pointer;\"><span unselectable=\"on\">14</span></td><td valign=\"middle\" align=\"center\" id=\"subview1:itemViewFragment1:itemForm1:texti0023_POPUP_DAY_20221115O\" class=\"inputText_DatePicker-CurrentMonth\" tabindex=\"1\" style=\"cursor: pointer;\"><span unselectable=\"on\">15</span></td><td valign=\"middle\" align=\"center\" id=\"subview1:itemViewFragment1:itemForm1:texti0023_POPUP_DAY_20221116O\" class=\"inputText_DatePicker-CurrentMonth\" tabindex=\"1\" style=\"cursor: pointer;\"><span unselectable=\"on\">16</span></td><td valign=\"middle\" align=\"center\" id=\"subview1:itemViewFragment1:itemForm1:texti0023_POPUP_DAY_20221117O\" class=\"inputText_DatePicker-CurrentMonth\" tabindex=\"1\" style=\"cursor: pointer;\"><span unselectable=\"on\">17</span></td><td valign=\"middle\" align=\"center\" id=\"subview1:itemViewFragment1:itemForm1:texti0023_POPUP_DAY_20221118O\" class=\"inputText_DatePicker-CurrentMonth\" tabindex=\"1\" style=\"cursor: pointer;\"><span unselectable=\"on\">18</span></td><td valign=\"middle\" align=\"center\" id=\"subview1:itemViewFragment1:itemForm1:texti0023_POPUP_DAY_20221119O\" class=\"inputText_DatePicker-CurrentMonth\" tabindex=\"1\" style=\"cursor: pointer;\"><span unselectable=\"on\">19</span></td></tr><tr><td valign=\"middle\" align=\"center\" id=\"subview1:itemViewFragment1:itemForm1:texti0023_POPUP_DAY_20221120O\" class=\"inputText_DatePicker-CurrentMonth\" tabindex=\"1\" style=\"cursor: pointer;\"><span unselectable=\"on\">20</span></td><td valign=\"middle\" align=\"center\" id=\"subview1:itemViewFragment1:itemForm1:texti0023_POPUP_DAY_20221121O\" class=\"inputText_DatePicker-CurrentToday\" tabindex=\"1\" style=\"cursor: pointer;\"><span unselectable=\"on\">21</span></td><td valign=\"middle\" align=\"center\" id=\"subview1:itemViewFragment1:itemForm1:texti0023_POPUP_DAY_20221122O\" class=\"inputText_DatePicker-CurrentMonth\" tabindex=\"1\" style=\"cursor: pointer;\"><span unselectable=\"on\">22</span></td><td valign=\"middle\" align=\"center\" id=\"subview1:itemViewFragment1:itemForm1:texti0023_POPUP_DAY_20221123O\" class=\"inputText_DatePicker-CurrentMonth\" tabindex=\"1\" style=\"cursor: pointer;\"><span unselectable=\"on\">23</span></td><td valign=\"middle\" align=\"center\" id=\"subview1:itemViewFragment1:itemForm1:texti0023_POPUP_DAY_20221124O\" class=\"inputText_DatePicker-CurrentMonth\" tabindex=\"1\" style=\"cursor: pointer;\"><span unselectable=\"on\">24</span></td><td valign=\"middle\" align=\"center\" id=\"subview1:itemViewFragment1:itemForm1:texti0023_POPUP_DAY_20221125O\" class=\"inputText_DatePicker-CurrentMonth\" tabindex=\"1\" style=\"cursor: pointer;\"><span unselectable=\"on\">25</span></td><td valign=\"middle\" align=\"center\" id=\"subview1:itemViewFragment1:itemForm1:texti0023_POPUP_DAY_20221126O\" class=\"inputText_DatePicker-CurrentMonth\" tabindex=\"1\" style=\"cursor: pointer;\"><span unselectable=\"on\">26</span></td></tr><tr><td valign=\"middle\" align=\"center\" id=\"subview1:itemViewFragment1:itemForm1:texti0023_POPUP_DAY_20221127O\" class=\"inputText_DatePicker-CurrentMonth\" tabindex=\"1\" style=\"cursor: pointer;\"><span unselectable=\"on\">27</span></td><td valign=\"middle\" align=\"center\" id=\"subview1:itemViewFragment1:itemForm1:texti0023_POPUP_DAY_20221128O\" class=\"inputText_DatePicker-CurrentMonth\" tabindex=\"1\" style=\"cursor: pointer;\"><span unselectable=\"on\">28</span></td><td valign=\"middle\" align=\"center\" id=\"subview1:itemViewFragment1:itemForm1:texti0023_POPUP_DAY_20221129O\" class=\"inputText_DatePicker-CurrentMonth\" tabindex=\"1\" style=\"cursor: pointer;\"><span unselectable=\"on\">29</span></td><td valign=\"middle\" align=\"center\" id=\"subview1:itemViewFragment1:itemForm1:texti0023_POPUP_DAY_20221130O\" class=\"inputText_DatePicker-CurrentMonth\" tabindex=\"1\" style=\"cursor: pointer;\"><span unselectable=\"on\">30</span></td><td valign=\"middle\" align=\"center\" id=\"subview1:itemViewFragment1:itemForm1:texti0023_POPUP_DAY_20221201X\" class=\"inputText_DatePicker-OtherMonth\" tabindex=\"1\" style=\"cursor: pointer;\"><span unselectable=\"on\">1</span></td><td valign=\"middle\" align=\"center\" id=\"subview1:itemViewFragment1:itemForm1:texti0023_POPUP_DAY_20221202X\" class=\"inputText_DatePicker-OtherMonth\" tabindex=\"1\" style=\"cursor: pointer;\"><span unselectable=\"on\">2</span></td><td valign=\"middle\" align=\"center\" id=\"subview1:itemViewFragment1:itemForm1:texti0023_POPUP_DAY_20221203X\" class=\"inputText_DatePicker-OtherMonth\" tabindex=\"1\" style=\"cursor: pointer;\"><span unselectable=\"on\">3</span></td></tr><tr style=\"display: none;\"><td valign=\"middle\" align=\"center\" id=\"\" style=\"cursor: pointer;\"></td><td valign=\"middle\" align=\"center\" id=\"\" style=\"cursor: pointer;\"></td><td valign=\"middle\" align=\"center\" id=\"\" style=\"cursor: pointer;\"></td><td valign=\"middle\" align=\"center\" id=\"\" style=\"cursor: pointer;\"></td><td valign=\"middle\" align=\"center\" id=\"\" style=\"cursor: pointer;\"></td><td valign=\"middle\" align=\"center\" id=\"\" style=\"cursor: pointer;\"></td><td valign=\"middle\" align=\"center\" id=\"\" style=\"cursor: pointer;\"></td></tr></tbody></table></td></tr></tbody></table></div>\n\n"
] |
[
-2
] |
[
"calendar",
"datepicker",
"python",
"selenium"
] |
stackoverflow_0074526712_calendar_datepicker_python_selenium.txt
|
Q:
Concatenate fails in simple example
I am trying the simple examples of this page
In it it says:
arr=np.array([4,7,12])
arr1=np.array([5,9,15])
np.concatenate((arr,arr1))
# Must give array([ 4, 7, 12, 5, 9, 15])
np.concatenate((arr,arr1),axis=1)
#Must give
#[[4,5],[7,9],[12,15]]
# but it gives *** numpy.AxisError: axis 1 is out of bounds for array of dimension 1
Why is this example not working?
A:
np.vstack is what you're looking for. Note the transpose at the end, this converts vstack's 2x3 result to a 3x2 array.
import numpy as np
arr = np.array([4,7,12])
arr1 = np.array([5,9,15])
a = np.vstack((arr,arr1)).T
print(a)
Output:
[[ 4 5]
[ 7 9]
[12 15]]
|
Concatenate fails in simple example
|
I am trying the simple examples of this page
In it it says:
arr=np.array([4,7,12])
arr1=np.array([5,9,15])
np.concatenate((arr,arr1))
# Must give array([ 4, 7, 12, 5, 9, 15])
np.concatenate((arr,arr1),axis=1)
#Must give
#[[4,5],[7,9],[12,15]]
# but it gives *** numpy.AxisError: axis 1 is out of bounds for array of dimension 1
Why is this example not working?
|
[
"np.vstack is what you're looking for. Note the transpose at the end, this converts vstack's 2x3 result to a 3x2 array.\nimport numpy as np\n\narr = np.array([4,7,12])\narr1 = np.array([5,9,15])\n\na = np.vstack((arr,arr1)).T\nprint(a)\n\nOutput:\n[[ 4 5]\n [ 7 9]\n [12 15]]\n\n"
] |
[
1
] |
[] |
[] |
[
"arrays",
"numpy",
"python"
] |
stackoverflow_0074526645_arrays_numpy_python.txt
|
Q:
Python - Function
I'm new to Python which I'm currently studying function.
I'm coding mile to kilometer conversion with a constant ratio number and constant value for "mile" using the 'def_function'
This is code.
mile=12
def distance_con(mile):
km = 1.6 * mile
print(km)
return km
result=distance_con(mile)
print(result)
But i noticed that, if i delete 'return km' from the function and also result=distance_con(mile)
mile=12
def distance_con(mile):
km = 1.6 * mile
print(km)
print(km)
i get this errors
"NameError: name 'km' is not defined
"Assiging result of a function call, where the function has no return"
Kindly assist me to understand why the nameError, Because km is defined as 1.6*mile in the function and also assigning result of a function call error
I want to understand when and how to use the def_func and also any other materials to assist me understand python.
A:
you got the error at print(km) km is define within the function scope so that you cannot access outside the function that you created.
In python there's a scope for a variable that we created see https://www.datacamp.com/tutorial/scope-of-variables-python for more info
A:
You are trying to print something in the global namespace that is not defined in the global namespace.
The variable km only exists within the scope of the function. Your code doesn't reference the function, so it executes no differently than if the function wasn't there, like this:
mile = 12
print(km)
Since km was never defined outside the function it is an error.
|
Python - Function
|
I'm new to Python which I'm currently studying function.
I'm coding mile to kilometer conversion with a constant ratio number and constant value for "mile" using the 'def_function'
This is code.
mile=12
def distance_con(mile):
km = 1.6 * mile
print(km)
return km
result=distance_con(mile)
print(result)
But i noticed that, if i delete 'return km' from the function and also result=distance_con(mile)
mile=12
def distance_con(mile):
km = 1.6 * mile
print(km)
print(km)
i get this errors
"NameError: name 'km' is not defined
"Assiging result of a function call, where the function has no return"
Kindly assist me to understand why the nameError, Because km is defined as 1.6*mile in the function and also assigning result of a function call error
I want to understand when and how to use the def_func and also any other materials to assist me understand python.
|
[
"you got the error at print(km) km is define within the function scope so that you cannot access outside the function that you created.\nIn python there's a scope for a variable that we created see https://www.datacamp.com/tutorial/scope-of-variables-python for more info\n",
"You are trying to print something in the global namespace that is not defined in the global namespace.\nThe variable km only exists within the scope of the function. Your code doesn't reference the function, so it executes no differently than if the function wasn't there, like this:\nmile = 12\n\nprint(km)\n\nSince km was never defined outside the function it is an error.\n"
] |
[
1,
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0074526696_python.txt
|
Q:
Remove single quote of string using `ast` but receive: ValueError: malformed node or string on line 1: - Python
a='[{"M":{"Options":{"L":[{"M":{"Label":{"S":"5PCS "},"Selected":{"BOOL":false},"OptionId":{"S":"3080a2b2-2fd1-11ed-a261-0242ac120002"},"Price":{"N":"0"}}},{"M":{"Label":{"S":"8PCS"},"Selected":{"BOOL":false},"OptionId":{"S":"27f2148c-2fd1-11ed-a261-0242ac120002"},"Price":{"N":"600"}}}]},"Type":{"S":"multiple"},"Description":{"S":"PCS "},"Required":{"BOOL":true},"Max":{"S":"1"},"Index":{"N":"0"},"Remove":{"BOOL":false},"Selected":{"N":"0"}}}]'
ast.literal_eval(a)
I am trying to remove the outside single quote and expect the output as:
[{"M":{"Options":{"L":[{"M":{"Label":{"S":"5PCS "},"Selected":{"BOOL":false},"OptionId":{"S":"3080a2b2-2fd1-11ed-a261-0242ac120002"},"Price":{"N":"0"}}},{"M":{"Label":{"S":"8PCS"},"Selected":{"BOOL":false},"OptionId":{"S":"27f2148c-2fd1-11ed-a261-0242ac120002"},"Price":{"N":"600"}}}]},"Type":{"S":"multiple"},"Description":{"S":"PCS "},"Required":{"BOOL":true},"Max":{"S":"1"},"Index":{"N":"0"},"Remove":{"BOOL":false},"Selected":{"N":"0"}}}]
But receive :
ValueError: malformed node or string on line 1: <ast.Name object at 0x12f39fa30>
I don't understand why I received this error since my input is string. Could anyone help me to fix it?
A:
What you have is not a valid Python "literal". If you look carefully at the value of a, you'll see the value false, which is not the same as the Python Boolean literal False.
The value of a is, however, a valid JSON array (as false and true are the JSON Boolean values).
>>> json.loads(a)
[{'M': {'Options': {'L': [{'M': {'Label': {'S': '5PCS '}, 'Selected': {'BOOL': False}, 'OptionId': {'S': '3080a2b2-2fd1-11ed-a261-0242ac120002'}, 'Price': {'N': '0'}}}, {'M': {'Label': {'S': '8PCS'}, 'Selected': {'BOOL': False}, 'OptionId': {'S': '27f2148c-2fd1-11ed-a261-0242ac120002'}, 'Price': {'N': '600'}}}]}, 'Type': {'S': 'multiple'}, 'Description': {'S': 'PCS '}, 'Required': {'BOOL': True}, 'Max': {'S': '1'}, 'Index': {'N': '0'}, 'Remove': {'BOOL': False}, 'Selected': {'N': '0'}}}]
|
Remove single quote of string using `ast` but receive: ValueError: malformed node or string on line 1: - Python
|
a='[{"M":{"Options":{"L":[{"M":{"Label":{"S":"5PCS "},"Selected":{"BOOL":false},"OptionId":{"S":"3080a2b2-2fd1-11ed-a261-0242ac120002"},"Price":{"N":"0"}}},{"M":{"Label":{"S":"8PCS"},"Selected":{"BOOL":false},"OptionId":{"S":"27f2148c-2fd1-11ed-a261-0242ac120002"},"Price":{"N":"600"}}}]},"Type":{"S":"multiple"},"Description":{"S":"PCS "},"Required":{"BOOL":true},"Max":{"S":"1"},"Index":{"N":"0"},"Remove":{"BOOL":false},"Selected":{"N":"0"}}}]'
ast.literal_eval(a)
I am trying to remove the outside single quote and expect the output as:
[{"M":{"Options":{"L":[{"M":{"Label":{"S":"5PCS "},"Selected":{"BOOL":false},"OptionId":{"S":"3080a2b2-2fd1-11ed-a261-0242ac120002"},"Price":{"N":"0"}}},{"M":{"Label":{"S":"8PCS"},"Selected":{"BOOL":false},"OptionId":{"S":"27f2148c-2fd1-11ed-a261-0242ac120002"},"Price":{"N":"600"}}}]},"Type":{"S":"multiple"},"Description":{"S":"PCS "},"Required":{"BOOL":true},"Max":{"S":"1"},"Index":{"N":"0"},"Remove":{"BOOL":false},"Selected":{"N":"0"}}}]
But receive :
ValueError: malformed node or string on line 1: <ast.Name object at 0x12f39fa30>
I don't understand why I received this error since my input is string. Could anyone help me to fix it?
|
[
"What you have is not a valid Python \"literal\". If you look carefully at the value of a, you'll see the value false, which is not the same as the Python Boolean literal False.\nThe value of a is, however, a valid JSON array (as false and true are the JSON Boolean values).\n>>> json.loads(a)\n[{'M': {'Options': {'L': [{'M': {'Label': {'S': '5PCS '}, 'Selected': {'BOOL': False}, 'OptionId': {'S': '3080a2b2-2fd1-11ed-a261-0242ac120002'}, 'Price': {'N': '0'}}}, {'M': {'Label': {'S': '8PCS'}, 'Selected': {'BOOL': False}, 'OptionId': {'S': '27f2148c-2fd1-11ed-a261-0242ac120002'}, 'Price': {'N': '600'}}}]}, 'Type': {'S': 'multiple'}, 'Description': {'S': 'PCS '}, 'Required': {'BOOL': True}, 'Max': {'S': '1'}, 'Index': {'N': '0'}, 'Remove': {'BOOL': False}, 'Selected': {'N': '0'}}}]\n\n"
] |
[
1
] |
[] |
[] |
[
"character",
"python",
"string"
] |
stackoverflow_0074526406_character_python_string.txt
|
Q:
how do I construct a pandas boolean series from an arbitrary number of conditions
I have a dataframe and I want to locate rows in the dataframe based on an arbitrary number of boolean conditions on multiple columns. Currently I'm doing this by formatting a complex query string, which is an unsafe pattern (although I'm not too concerned about the specific code here). It looks like this:
df = pd.DataFrame({
'a_id': [1, 3, 5],
'b_id': [2, 7, 9],
'c_id': [3, 4, 5]
})
ids_of_interest = [2, 4]
components_to_query = ['a', 'c']
query = '({})'.format(')|('.join([
f'{c}_id.isin(@ids_of_interest)' for c in component
]))
df.query(query)
a_id b_id c_id
0 2 2 3
1 3 7 4
The only other way I can come up with to do this is below, but it involves a very non-pythonic initialization of an array that's then modified in a loop.
query = pd.Series([False]*len(df))
for c in component:
query = query | df[c + '_id'].isin(ids_of_interest)
What's the pythonic way to locate these rows (using query or any other method)?
A:
You could do with any
col = [f'{c}_id' for c in components_to_query]
out = df[df[col].isin(ids_of_interest).any(1)]
Out[268]:
a_id b_id c_id
1 3 7 4
|
how do I construct a pandas boolean series from an arbitrary number of conditions
|
I have a dataframe and I want to locate rows in the dataframe based on an arbitrary number of boolean conditions on multiple columns. Currently I'm doing this by formatting a complex query string, which is an unsafe pattern (although I'm not too concerned about the specific code here). It looks like this:
df = pd.DataFrame({
'a_id': [1, 3, 5],
'b_id': [2, 7, 9],
'c_id': [3, 4, 5]
})
ids_of_interest = [2, 4]
components_to_query = ['a', 'c']
query = '({})'.format(')|('.join([
f'{c}_id.isin(@ids_of_interest)' for c in component
]))
df.query(query)
a_id b_id c_id
0 2 2 3
1 3 7 4
The only other way I can come up with to do this is below, but it involves a very non-pythonic initialization of an array that's then modified in a loop.
query = pd.Series([False]*len(df))
for c in component:
query = query | df[c + '_id'].isin(ids_of_interest)
What's the pythonic way to locate these rows (using query or any other method)?
|
[
"You could do with any\ncol = [f'{c}_id' for c in components_to_query]\nout = df[df[col].isin(ids_of_interest).any(1)]\nOut[268]: \n a_id b_id c_id\n1 3 7 4\n\n"
] |
[
1
] |
[] |
[] |
[
"pandas",
"python"
] |
stackoverflow_0074526510_pandas_python.txt
|
Q:
How can I make a non-blocking UDP server and a periodic task in the same script?
I am trying to make a UDP server and next to it a periodic task that updates a global variable every 5 minutes.
But the problem is that my UDP server and my task part blocks the rest of the code (because I use while True:).
I was looking at this example:
https://docs.python.org/3/library/asyncio-protocol.html#asyncio-udp-echo-server-protocol
import asyncio
class EchoServerProtocol:
def connection_made(self, transport):
self.transport = transport
def datagram_received(self, data, addr):
message = data.decode()
print('Received %r from %s' % (message, addr))
print('Send %r to %s' % (message, addr))
self.transport.sendto(data, addr)
async def main():
print("Starting UDP server")
# Get a reference to the event loop as we plan to use
# low-level APIs.
loop = asyncio.get_running_loop()
# One protocol instance will be created to serve all
# client requests.
transport, protocol = await loop.create_datagram_endpoint(
lambda: EchoServerProtocol(),
local_addr=('127.0.0.1', 9999))
try:
await asyncio.sleep(3600) # Serve for 1 hour.
finally:
transport.close()
asyncio.run(main())
I see in the example that they run this for an hour. But what if I wanted to run it indefinitely? I played with run_forever(), but I don't understand how it works.
I also don't understand how to make a periodic task that doesn't use while True: at the same time.
Is this possible?
A:
Replace your asyncio.sleep(3600) with a wait for an asyncio.Event that never happens. That will suspend the task forever but leave the event loop running. The only way to terminate the program is with Ctrl-C or some other operating system action.
try:
await asyncio.Event().wait() # wait here until the Universe ends
finally:
transport.close()
A:
Instead waiting for an hour, just make an infinite loop which executes your periodic task.
Replace
await asyncio.sleep(3600)
with
while True:
print("do something every 5 minutes", datetime.datetime.now())
await asyncio.sleep(5*60)
|
How can I make a non-blocking UDP server and a periodic task in the same script?
|
I am trying to make a UDP server and next to it a periodic task that updates a global variable every 5 minutes.
But the problem is that my UDP server and my task part blocks the rest of the code (because I use while True:).
I was looking at this example:
https://docs.python.org/3/library/asyncio-protocol.html#asyncio-udp-echo-server-protocol
import asyncio
class EchoServerProtocol:
def connection_made(self, transport):
self.transport = transport
def datagram_received(self, data, addr):
message = data.decode()
print('Received %r from %s' % (message, addr))
print('Send %r to %s' % (message, addr))
self.transport.sendto(data, addr)
async def main():
print("Starting UDP server")
# Get a reference to the event loop as we plan to use
# low-level APIs.
loop = asyncio.get_running_loop()
# One protocol instance will be created to serve all
# client requests.
transport, protocol = await loop.create_datagram_endpoint(
lambda: EchoServerProtocol(),
local_addr=('127.0.0.1', 9999))
try:
await asyncio.sleep(3600) # Serve for 1 hour.
finally:
transport.close()
asyncio.run(main())
I see in the example that they run this for an hour. But what if I wanted to run it indefinitely? I played with run_forever(), but I don't understand how it works.
I also don't understand how to make a periodic task that doesn't use while True: at the same time.
Is this possible?
|
[
"Replace your asyncio.sleep(3600) with a wait for an asyncio.Event that never happens. That will suspend the task forever but leave the event loop running. The only way to terminate the program is with Ctrl-C or some other operating system action.\ntry:\n await asyncio.Event().wait() # wait here until the Universe ends\nfinally:\n transport.close()\n\n",
"Instead waiting for an hour, just make an infinite loop which executes your periodic task.\nReplace\nawait asyncio.sleep(3600)\n\nwith\nwhile True:\n print(\"do something every 5 minutes\", datetime.datetime.now())\n await asyncio.sleep(5*60)\n\n"
] |
[
1,
0
] |
[] |
[] |
[
"python",
"python_asyncio"
] |
stackoverflow_0074523668_python_python_asyncio.txt
|
Q:
Would someone please help me understand this logic?
I have a dictionary variable that stores two columns of a pandas array, and it prints perfectly. However, when I assign variable to a template for json metadata, only the one row of the array is written to the json file. I'm having trouble wrapping my head around why this is happening.
for i in range(attributesQuantity):
attributesCount = {
"trait_type": dfM.loc[i, "trait_type"],
"value": dfM.loc[i, "value"],
}
print(attributesCount)
prompt_metadata["attributes"] = [attributesCount]
I'm expecting the the same value as print(attributesCount) to be assigned to attributes in prompt_metadata.json . An example of print(attributesCount) is
{'trait_type': 'Hair Color', 'value': 'blonde haired'}
{'trait_type': ' Sex', 'value': ' boy'}
{'trait_type': ' Eye Color', 'value': ' black eyes'}
{'trait_type': ' Race', 'value': ' human'}
whereas the json looks like
"attributes": [{"trait_type": " Race", "value": " human"}]}
A:
Based on the pandas.DataFrame.loc, codes like dfM.loc[i, "trait_type"] should get the element of trait_type column in the ith row, and the print output would only be something like {"trait_type": " Race", "value": " human"}.
prompt_metadata["attributes"] in this loop, is reassigning prompt_metadata["attributes"] in each loop, probably you should try something like this:
for i in range(attributesQuantity):
attributesCount = {
"trait_type": dfM.loc[i, "trait_type"],
"value": dfM.loc[i, "value"],
}
print(attributesCount)
if prompt_metadata["attributes"] is None:
prompt_metadata["attributes"] = []
else:
prompt_metadata["attributes"].append(attributesCount)
|
Would someone please help me understand this logic?
|
I have a dictionary variable that stores two columns of a pandas array, and it prints perfectly. However, when I assign variable to a template for json metadata, only the one row of the array is written to the json file. I'm having trouble wrapping my head around why this is happening.
for i in range(attributesQuantity):
attributesCount = {
"trait_type": dfM.loc[i, "trait_type"],
"value": dfM.loc[i, "value"],
}
print(attributesCount)
prompt_metadata["attributes"] = [attributesCount]
I'm expecting the the same value as print(attributesCount) to be assigned to attributes in prompt_metadata.json . An example of print(attributesCount) is
{'trait_type': 'Hair Color', 'value': 'blonde haired'}
{'trait_type': ' Sex', 'value': ' boy'}
{'trait_type': ' Eye Color', 'value': ' black eyes'}
{'trait_type': ' Race', 'value': ' human'}
whereas the json looks like
"attributes": [{"trait_type": " Race", "value": " human"}]}
|
[
"Based on the pandas.DataFrame.loc, codes like dfM.loc[i, \"trait_type\"] should get the element of trait_type column in the ith row, and the print output would only be something like {\"trait_type\": \" Race\", \"value\": \" human\"}.\nprompt_metadata[\"attributes\"] in this loop, is reassigning prompt_metadata[\"attributes\"] in each loop, probably you should try something like this:\n for i in range(attributesQuantity):\n attributesCount = {\n \"trait_type\": dfM.loc[i, \"trait_type\"],\n \"value\": dfM.loc[i, \"value\"],\n }\n print(attributesCount)\n if prompt_metadata[\"attributes\"] is None:\n prompt_metadata[\"attributes\"] = []\n else:\n prompt_metadata[\"attributes\"].append(attributesCount)\n\n"
] |
[
0
] |
[] |
[] |
[
"pandas",
"python"
] |
stackoverflow_0074526731_pandas_python.txt
|
Q:
VS Code not finding pytest tests
I have PyTest setup in vs-code but none of the tests are being found even though running pytest from the command line works fine.
(I'm developing a Django app on Win10 using MiniConda and a Python 3.6.6 virtual env. VS Code is fully updated and I have the Python and Debugger for Chrome extensions installed)
Pytest.ini:
[pytest]
DJANGO_SETTINGS_MODULE = callsign.settings
python_files = tests.py test_*.py *_tests.py
vs-code workspace settings:
{
"folders": [
{
"path": "."
}
],
"settings": {
"python.pythonPath": "C:\\ProgramData\\Miniconda3\\envs\\callsign\\python.exe",
"python.unitTest.unittestEnabled": false,
"python.unitTest.nosetestsEnabled": false,
"python.unitTest.pyTestEnabled": true,
"python.unitTest.pyTestArgs": ["--rootdir=.\\callsign", "--verbose"]
}
}
Finally, the output from the Python Test Log inside VS code:
============================= test session starts =============================
platform win32 -- Python 3.6.6, pytest-4.1.1, py-1.7.0, pluggy-0.8.1
Django settings: callsign.settings (from ini file)
rootdir: c:\Users\benhe\Projects\CallsignCopilot\callsign, inifile: pytest.ini
plugins: django-3.4.5
collected 23 items
<Package c:\Users\benhe\Projects\CallsignCopilot\callsign\transcription>
<Module test_utils.py>
<Function test_n_digits>
<Function test_n_alpha>
<Function test_n_hex>
<Function test_n_digits_in_range>
<Function test_v1_audiofilename>
<Function test_v2_audiofilename>
<Function test_v1_bad_int_filename>
<Function test_v1_bad_non_int_filename>
<Function test_bad_format>
<Function test_no_format>
<Function test_too_many_segments>
<Function test_too_few_segments>
<Function test_good_v2_filename>
<Function test_bad_year_v2_filename>
<Function test_bad_month_v2_filename>
<Function test_bad_day_v2_filename>
<Function test_bad_date_v2_filename>
<Function test_bad_short_serial_v2_filename>
<Function test_bad_long_serial_v2_filename>
<Function test_good_v3_filename>
<Function test_good_lowercase_block_v3_filename>
<Function test_bad_non_alpha_block_v3_filename>
<Function test_real_filenames>
======================== no tests ran in 1.12 seconds =========================
Am I missing any steps to get vs-code to find the tests?
A:
If anyone comes across this post-2020, this issue in the vscode-python repo saved my life. Basically, just do the following:
Uninstall the Python extension
Delete the file that contains the extension from your ~/.vscode folder (mine looked like ms-python.python-[YEAR].[MONTH].[VERSION])
Reinstall the extension
Worked like a charm.
A:
EDIT: I downgraded to Pytest 4.0.1 after reading issue 3911 and Test Discovery now works.
Me too. When I blow away .pytest_cache and rerun Python: Discover Unit Tests, I see that the freshly generated .pytest_cache/v/cache/nodeids contains all the tests, but I still get the dialog complaining about No tests discovered.
Python 3.7.2
macOS 10.13.6
VS Code 1.30.2
Python Extension 2018.12.1
Pytest 4.1.0
.vscode/settings.json:
{
"python.linting.enabled": false,
"python.unitTest.unittestEnabled": false,
"python.unitTest.nosetestsEnabled": false,
"python.unitTest.pyTestEnabled": true,
"python.pythonPath": "venv3/bin/python"
}
Tests are in a top-level subdirectory called test. Running pytest manually works.
A:
Another thing to check, if vscode fails to discover the tests, is to make sure it doesn't do so because of the coverage module being enabled. In my case the test cases were being discovered correctly but the discovery eventually kept failing due to low test coverage, as described here. So first, make sure that the tests could actually be collected by pytest as suggested here:
pytest --collect-only
and then make sure you're not forcing coverage check (e.g. in setup.cfg) with e.g.
addopts= --cov <path> -ra
A:
In September 2021, I was able to get VS code to find the test directory again by downgrading the VS Code Python extension from version 2021.9.1191016588 to version v2021.8.1159798656. To downgrade, right-click the extension and click "Install another version..."
A:
The following steps worked for me (assuming latest PyTest installed in Visual Studio Code):
Make sure there are no errors (bottom left of Visual Studio Code)
In Visual Studio Code from File menu choose: File > Close Folder (i.e. close current project folder) and close Visual Studio Code.
Re-open Visual Studio Code and choose: File > Open Folder (re-open the folder that contains your project/test files).
Choose Testing and should have visibility of tests from here ...
A:
VScode needs to specify python configure:
Open Command Palette by Ctrl + shift + p
and write this >python: configure tests And follow the program directions
Note: You may need (Mostly you will not need) to do this first before following the previous steps
A:
My Python plugin and Test Explorer works just fine.
In my case naming the class without test_.py was the issue. In other words, naming the test file without it starting with "test_", not "tests_", makes it so the explorer does not see the issue. Ex: test_.py works but tests_.py, 12345abcde.py don't work.
A:
An obvious thing that caught me...
The test folder hierarchy needs __init__.py files in each folder.
I refactored my tests introducing an extra folder layer and forgot to add __init__.py files.
Command line didn't complain but vscode showed no tests found
A:
In my case the problem was that I had a syntax error in a source file which caused the pytest discovery to fail. Also, note that you get the traceback from Output (tab) -> Python (dropdown).
A:
If everything here fails and you checked all the basic configurations, try specifying the path to your test folder in your workspace's settings.ini file like so. The three configurations below it are from the majority of other solutions.
"python.testing.pytestArgs": [
"${workspaceFolder}/tests"
],
"python.testing.unittestEnabled": false,
"python.testing.nosetestsEnabled": false,
"python.testing.pytestEnabled": true,
|
VS Code not finding pytest tests
|
I have PyTest setup in vs-code but none of the tests are being found even though running pytest from the command line works fine.
(I'm developing a Django app on Win10 using MiniConda and a Python 3.6.6 virtual env. VS Code is fully updated and I have the Python and Debugger for Chrome extensions installed)
Pytest.ini:
[pytest]
DJANGO_SETTINGS_MODULE = callsign.settings
python_files = tests.py test_*.py *_tests.py
vs-code workspace settings:
{
"folders": [
{
"path": "."
}
],
"settings": {
"python.pythonPath": "C:\\ProgramData\\Miniconda3\\envs\\callsign\\python.exe",
"python.unitTest.unittestEnabled": false,
"python.unitTest.nosetestsEnabled": false,
"python.unitTest.pyTestEnabled": true,
"python.unitTest.pyTestArgs": ["--rootdir=.\\callsign", "--verbose"]
}
}
Finally, the output from the Python Test Log inside VS code:
============================= test session starts =============================
platform win32 -- Python 3.6.6, pytest-4.1.1, py-1.7.0, pluggy-0.8.1
Django settings: callsign.settings (from ini file)
rootdir: c:\Users\benhe\Projects\CallsignCopilot\callsign, inifile: pytest.ini
plugins: django-3.4.5
collected 23 items
<Package c:\Users\benhe\Projects\CallsignCopilot\callsign\transcription>
<Module test_utils.py>
<Function test_n_digits>
<Function test_n_alpha>
<Function test_n_hex>
<Function test_n_digits_in_range>
<Function test_v1_audiofilename>
<Function test_v2_audiofilename>
<Function test_v1_bad_int_filename>
<Function test_v1_bad_non_int_filename>
<Function test_bad_format>
<Function test_no_format>
<Function test_too_many_segments>
<Function test_too_few_segments>
<Function test_good_v2_filename>
<Function test_bad_year_v2_filename>
<Function test_bad_month_v2_filename>
<Function test_bad_day_v2_filename>
<Function test_bad_date_v2_filename>
<Function test_bad_short_serial_v2_filename>
<Function test_bad_long_serial_v2_filename>
<Function test_good_v3_filename>
<Function test_good_lowercase_block_v3_filename>
<Function test_bad_non_alpha_block_v3_filename>
<Function test_real_filenames>
======================== no tests ran in 1.12 seconds =========================
Am I missing any steps to get vs-code to find the tests?
|
[
"If anyone comes across this post-2020, this issue in the vscode-python repo saved my life. Basically, just do the following:\n\nUninstall the Python extension\nDelete the file that contains the extension from your ~/.vscode folder (mine looked like ms-python.python-[YEAR].[MONTH].[VERSION])\nReinstall the extension\n\nWorked like a charm.\n",
"EDIT: I downgraded to Pytest 4.0.1 after reading issue 3911 and Test Discovery now works.\n\nMe too. When I blow away .pytest_cache and rerun Python: Discover Unit Tests, I see that the freshly generated .pytest_cache/v/cache/nodeids contains all the tests, but I still get the dialog complaining about No tests discovered.\n\nPython 3.7.2\nmacOS 10.13.6\nVS Code 1.30.2\nPython Extension 2018.12.1\nPytest 4.1.0\n\n.vscode/settings.json:\n{\n \"python.linting.enabled\": false,\n \"python.unitTest.unittestEnabled\": false,\n \"python.unitTest.nosetestsEnabled\": false,\n \"python.unitTest.pyTestEnabled\": true,\n \"python.pythonPath\": \"venv3/bin/python\"\n}\n\nTests are in a top-level subdirectory called test. Running pytest manually works.\n",
"Another thing to check, if vscode fails to discover the tests, is to make sure it doesn't do so because of the coverage module being enabled. In my case the test cases were being discovered correctly but the discovery eventually kept failing due to low test coverage, as described here. So first, make sure that the tests could actually be collected by pytest as suggested here:\npytest --collect-only\n\nand then make sure you're not forcing coverage check (e.g. in setup.cfg) with e.g.\naddopts= --cov <path> -ra\n\n",
"In September 2021, I was able to get VS code to find the test directory again by downgrading the VS Code Python extension from version 2021.9.1191016588 to version v2021.8.1159798656. To downgrade, right-click the extension and click \"Install another version...\"\n",
"The following steps worked for me (assuming latest PyTest installed in Visual Studio Code):\n\nMake sure there are no errors (bottom left of Visual Studio Code)\n\nIn Visual Studio Code from File menu choose: File > Close Folder (i.e. close current project folder) and close Visual Studio Code.\nRe-open Visual Studio Code and choose: File > Open Folder (re-open the folder that contains your project/test files).\nChoose Testing and should have visibility of tests from here ...\n\n\n",
"VScode needs to specify python configure:\n\nOpen Command Palette by Ctrl + shift + p\nand write this >python: configure tests And follow the program directions\n\nNote: You may need (Mostly you will not need) to do this first before following the previous steps\n",
"My Python plugin and Test Explorer works just fine.\nIn my case naming the class without test_.py was the issue. In other words, naming the test file without it starting with \"test_\", not \"tests_\", makes it so the explorer does not see the issue. Ex: test_.py works but tests_.py, 12345abcde.py don't work.\n",
"An obvious thing that caught me...\nThe test folder hierarchy needs __init__.py files in each folder.\nI refactored my tests introducing an extra folder layer and forgot to add __init__.py files.\nCommand line didn't complain but vscode showed no tests found\n",
"In my case the problem was that I had a syntax error in a source file which caused the pytest discovery to fail. Also, note that you get the traceback from Output (tab) -> Python (dropdown).\n",
"If everything here fails and you checked all the basic configurations, try specifying the path to your test folder in your workspace's settings.ini file like so. The three configurations below it are from the majority of other solutions.\n\"python.testing.pytestArgs\": [\n \"${workspaceFolder}/tests\"\n],\n\"python.testing.unittestEnabled\": false,\n\"python.testing.nosetestsEnabled\": false,\n\"python.testing.pytestEnabled\": true,\n\n"
] |
[
17,
4,
4,
4,
3,
3,
2,
1,
1,
0
] |
[] |
[] |
[
"pytest",
"pytest_django",
"python",
"python_3.x",
"visual_studio_code"
] |
stackoverflow_0054387442_pytest_pytest_django_python_python_3.x_visual_studio_code.txt
|
Q:
Python: add a book with user input
I’m trying to add a book to an inventory list, based on user input and get a "str not callable" error?
#Add a book, based on user input
def add_book():
# purpose: add a book
print()
print("Adding a New Book..")
print()
title = input("Title> ")
author = input("Author> ")
isbn = input("ISBN> ")
callnumber = input("CallNumber> ")
stock = input("Stock> ")
loaned = input("Loaned> ")
inventory.append = (title, author, isbn, callnumber, stock, loaned)
I'm not sure how else to ask for input to append the new book to existing ist of books?
A:
That is not the correct syntax to append to a list.
Assuming inventory is a list type, the append() method takes a single argument and appends it to the list.
inventory.append(title)
You will need to do this for each element you wish to append, or append them as a tuple of items
inventory.append((title, author, isbn, callnumber, stock, loaned))
A:
You will first want to adjust your function to allow for a inventory "list" to be passed to it, like so:
def add_book(inventory):
From here you will be able to append a "tuple" with values separated by commas , like so:
inventory.append((title, author, isbn, callnumber, stock, loaned))
Be careful to make sure to have the tuple elements stored in their own parentheses, in addition to the ones from the append method.
|
Python: add a book with user input
|
I’m trying to add a book to an inventory list, based on user input and get a "str not callable" error?
#Add a book, based on user input
def add_book():
# purpose: add a book
print()
print("Adding a New Book..")
print()
title = input("Title> ")
author = input("Author> ")
isbn = input("ISBN> ")
callnumber = input("CallNumber> ")
stock = input("Stock> ")
loaned = input("Loaned> ")
inventory.append = (title, author, isbn, callnumber, stock, loaned)
I'm not sure how else to ask for input to append the new book to existing ist of books?
|
[
"That is not the correct syntax to append to a list.\nAssuming inventory is a list type, the append() method takes a single argument and appends it to the list.\ninventory.append(title)\n\nYou will need to do this for each element you wish to append, or append them as a tuple of items\ninventory.append((title, author, isbn, callnumber, stock, loaned))\n\n",
"You will first want to adjust your function to allow for a inventory \"list\" to be passed to it, like so:\ndef add_book(inventory):\n\nFrom here you will be able to append a \"tuple\" with values separated by commas , like so:\ninventory.append((title, author, isbn, callnumber, stock, loaned))\n\nBe careful to make sure to have the tuple elements stored in their own parentheses, in addition to the ones from the append method.\n"
] |
[
0,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0074526642_python.txt
|
Q:
Obtaining a HashMap or dictionary and a diagram in Python to visualize the overlaps between multiple lists
Context: I roughly have a dictionary of about 130 lists in the form of a key and a list of indexes.
{‘key1’:[0,1,2], ‘key2’: [2, 3, 4], ‘key3’:[5, 6],…, ‘key130’:[0, 450, 1103, 500,…]}
Lists are all different sizes.
This is a two-part problem where:
I want some form of data structure to store the number of overlaps between lists
If possible, I want a diagram that shows the overlap
PART 1:
The most similar StackOverflow questions answers were that we could find list similarities by utilizing set.intersection
List1 = [10,10,11,12,15,16,18,19]
List2 = [10,11,13,15,16,19,20]
List3 = [10,11,11,12,15,19,21,23]
print(set(List1).intersection(List2)) #compare between list 2 and 3
Which gives you:
set([10, 11, 15, 16, 19])
I could then use a for loop to traverse through each list to compare it with the next list in the dictionary and get the length of the list. This would then give me a dictionary such as:
{‘key1_key2’:1, ‘key2_key3’:0, ‘key3_key4’…, ‘key130_key1’: [29]}
PART 2:
I have in my head that a comparison table would be the best to visualize the similarities:
Key1 Key2 Key3 … Key130
Key1 X X X X
Key2 0 X X X
Key3 4 6 X X
… X …
Key130 X
However, I couldn’t find many results on how this can be achieved.
Another option was UpSetPlot as it can allow for pretty nice yet perhaps a little excessive comparison in this case: https://upsetplot.readthedocs.io/en/stable/
Of course, I’m sure both diagrams would need the similarities result to be stored a bit differently? I’m not too sure for the Comparison Table but UpSetPlot would need the dictionary (?) to be a pandaSeries. I would be interested in both diagrams to test how it would look.
Reproducible Example:
{'key1': [10,10,11,12,15,16,18,19], 'key2': [10,11,13,15,16,19,20], 'key3':[10,11,11,12,15,19,21,23], 'key4':[], 'key5':[0], 'key6':[10,55,66,77]}
Some of the more useful resources I looked at:
How to compare more than 2 Lists in Python? Python -Intersection of multiple lists? Python comparing multiple lists into Comparison Table
If there are some other sites that I missed that would be applicable to this Q, please let me know. Thank you in advance!
A:
import numpy as np
import pandas as pd
d = {'key1':[0,1,2], 'key2': [2, 3, 4], 'key3':[5, 6]}
s = []
[s.append(list(set(x) & set(y))) for x in d.values() for y in d.values()]
matrix1 = np.array(s, dtype = object)
matrix2 = matrix1.reshape(int(np.sqrt(len(matrix1))),int(np.sqrt(len(matrix1))))
matrix2 = np.vectorize(len)(matrix2)
df = pd.DataFrame(matrix2)
df.columns = d.keys()
df.index = d.keys()
print(df)
Output:
key1 key2 key3
key1 3 1 0
key2 1 3 0
key3 0 0 2
Definitely not the solution with the best performance. But it is easy to implement.
A:
The structure I would use would be a nested set of dictionaries, where the first level was all the comparisons for a given first key, and each value in the first dictionary is a dictionary containing the intersection of that value's key with each of the other keys (including itself).
You can optionally choose to store the comparison length for each pair of keys just once in the dictionary. If you do this, then when you look up a comparison, you have to consider the keys in both orders when looking up their intersections. If a comparison doesn't exist for two keys in one order (ex: [a][b]), then it will contains a comparison in the other order ([b][a]). If you'd rather be able to look up the keys without worrying about the order, you can store the values twice so that either order is valid.
Here's code that does all this, including having the option to create a sparse data structure that only contains the counts in one order for each key pair:
from pprint import pprint
# Build the comparison structure
def build_comparisons(input, sparse=True):
comparisons = {}
for key1 in input.keys():
comparisons[key1] = {}
for key2 in input.keys():
if key2 in comparisons and key1 in comparisons[key2]:
# If we've already computed the intersection for this pair of keys...
if sparse:
# For a sparse structure, don't include values for keys that
# already exist in the structure in the opposite order of keys
continue
# Use the already computed value
comparisons[key1][key2] = comparisons[key2][key1]
elif key1 == key2:
# If the keys are the same, use the length of that key's value
comparisons[key1][key2] = len(input[key1])
else:
# Compute the intersection between the two keys and take its length
l1 = set(input[key1])
l2 = set(input[key2])
comparisons[key1][key2] = len(l1.intersection(l2))
return comparisons
# Look up the intersection for a keypair. This function is only necessary
# to make it easier to look up values in a sparse structure
def get_comparison(comparisons, key1, key2):
if key1 in comparisons and key2 in comparisons[key1]:
return comparisons[key1][key2]
return comparisons[key2][key1]
# Display the lengths of each intersection in a table format
def display_comparisons(comparisons):
cell_width = max([len(key) for key in comparisons.keys()]) + 2
def print_cell(val):
print(f"{str(val):<{cell_width}}", end='')
print_cell('')
[print_cell(key) for key in comparisons.keys()]
print()
for key1 in comparisons.keys():
print_cell(key1)
for key2 in comparisons.keys():
print_cell(get_comparison(comparisons, key1, key2))
print()
input = {'key1': [10,10,11,12,15,16,18,19], 'key2': [10,11,13,15,16,19,20], 'key3':[10,11,11,12,15,19,21,23], 'key4':[], 'key5':[0], 'key6':[10,55,66,77]}
# Build the comparison structure
comparisons = build_comparisons(input)
# Show the resulting data structure
pprint(comparisons)
print()
# Display the lengths of each intersection in a table format
display_comparisons(comparisons)
Here's the resulting output:
{'key1': {'key1': 8, 'key2': 5, 'key3': 5, 'key4': 0, 'key5': 0, 'key6': 1},
'key2': {'key2': 7, 'key3': 4, 'key4': 0, 'key5': 0, 'key6': 1},
'key3': {'key3': 8, 'key4': 0, 'key5': 0, 'key6': 1},
'key4': {'key4': 0, 'key5': 0, 'key6': 0},
'key5': {'key5': 1, 'key6': 0},
'key6': {'key6': 4}}
key1 key2 key3 key4 key5 key6
key1 8 5 5 0 0 1
key2 5 7 4 0 0 1
key3 5 4 8 0 0 1
key4 0 0 0 0 0 0
key5 0 0 0 0 1 0
key6 1 1 1 0 0 4
If you set sparse to False when computing the data structure, then when you print it, you get this instead:
{'key1': {'key1': 8, 'key2': 5, 'key3': 5, 'key4': 0, 'key5': 0, 'key6': 1},
'key2': {'key1': 5, 'key2': 7, 'key3': 4, 'key4': 0, 'key5': 0, 'key6': 1},
'key3': {'key1': 5, 'key2': 4, 'key3': 8, 'key4': 0, 'key5': 0, 'key6': 1},
'key4': {'key1': 0, 'key2': 0, 'key3': 0, 'key4': 0, 'key5': 0, 'key6': 0},
'key5': {'key1': 0, 'key2': 0, 'key3': 0, 'key4': 0, 'key5': 1, 'key6': 0},
'key6': {'key1': 1, 'key2': 1, 'key3': 1, 'key4': 0, 'key5': 0, 'key6': 4}}
|
Obtaining a HashMap or dictionary and a diagram in Python to visualize the overlaps between multiple lists
|
Context: I roughly have a dictionary of about 130 lists in the form of a key and a list of indexes.
{‘key1’:[0,1,2], ‘key2’: [2, 3, 4], ‘key3’:[5, 6],…, ‘key130’:[0, 450, 1103, 500,…]}
Lists are all different sizes.
This is a two-part problem where:
I want some form of data structure to store the number of overlaps between lists
If possible, I want a diagram that shows the overlap
PART 1:
The most similar StackOverflow questions answers were that we could find list similarities by utilizing set.intersection
List1 = [10,10,11,12,15,16,18,19]
List2 = [10,11,13,15,16,19,20]
List3 = [10,11,11,12,15,19,21,23]
print(set(List1).intersection(List2)) #compare between list 2 and 3
Which gives you:
set([10, 11, 15, 16, 19])
I could then use a for loop to traverse through each list to compare it with the next list in the dictionary and get the length of the list. This would then give me a dictionary such as:
{‘key1_key2’:1, ‘key2_key3’:0, ‘key3_key4’…, ‘key130_key1’: [29]}
PART 2:
I have in my head that a comparison table would be the best to visualize the similarities:
Key1 Key2 Key3 … Key130
Key1 X X X X
Key2 0 X X X
Key3 4 6 X X
… X …
Key130 X
However, I couldn’t find many results on how this can be achieved.
Another option was UpSetPlot as it can allow for pretty nice yet perhaps a little excessive comparison in this case: https://upsetplot.readthedocs.io/en/stable/
Of course, I’m sure both diagrams would need the similarities result to be stored a bit differently? I’m not too sure for the Comparison Table but UpSetPlot would need the dictionary (?) to be a pandaSeries. I would be interested in both diagrams to test how it would look.
Reproducible Example:
{'key1': [10,10,11,12,15,16,18,19], 'key2': [10,11,13,15,16,19,20], 'key3':[10,11,11,12,15,19,21,23], 'key4':[], 'key5':[0], 'key6':[10,55,66,77]}
Some of the more useful resources I looked at:
How to compare more than 2 Lists in Python? Python -Intersection of multiple lists? Python comparing multiple lists into Comparison Table
If there are some other sites that I missed that would be applicable to this Q, please let me know. Thank you in advance!
|
[
"import numpy as np\nimport pandas as pd\n\nd = {'key1':[0,1,2], 'key2': [2, 3, 4], 'key3':[5, 6]}\ns = []\n[s.append(list(set(x) & set(y))) for x in d.values() for y in d.values()]\n\nmatrix1 = np.array(s, dtype = object)\nmatrix2 = matrix1.reshape(int(np.sqrt(len(matrix1))),int(np.sqrt(len(matrix1))))\nmatrix2 = np.vectorize(len)(matrix2)\n\ndf = pd.DataFrame(matrix2)\ndf.columns = d.keys()\ndf.index = d.keys()\n\nprint(df)\n\nOutput:\n key1 key2 key3\nkey1 3 1 0\nkey2 1 3 0\nkey3 0 0 2\n\nDefinitely not the solution with the best performance. But it is easy to implement.\n",
"The structure I would use would be a nested set of dictionaries, where the first level was all the comparisons for a given first key, and each value in the first dictionary is a dictionary containing the intersection of that value's key with each of the other keys (including itself).\nYou can optionally choose to store the comparison length for each pair of keys just once in the dictionary. If you do this, then when you look up a comparison, you have to consider the keys in both orders when looking up their intersections. If a comparison doesn't exist for two keys in one order (ex: [a][b]), then it will contains a comparison in the other order ([b][a]). If you'd rather be able to look up the keys without worrying about the order, you can store the values twice so that either order is valid.\nHere's code that does all this, including having the option to create a sparse data structure that only contains the counts in one order for each key pair:\nfrom pprint import pprint\n\n# Build the comparison structure\ndef build_comparisons(input, sparse=True):\n comparisons = {}\n for key1 in input.keys():\n comparisons[key1] = {}\n for key2 in input.keys():\n if key2 in comparisons and key1 in comparisons[key2]:\n # If we've already computed the intersection for this pair of keys...\n if sparse:\n # For a sparse structure, don't include values for keys that\n # already exist in the structure in the opposite order of keys\n continue\n # Use the already computed value\n comparisons[key1][key2] = comparisons[key2][key1]\n elif key1 == key2:\n # If the keys are the same, use the length of that key's value\n comparisons[key1][key2] = len(input[key1])\n else:\n # Compute the intersection between the two keys and take its length\n l1 = set(input[key1])\n l2 = set(input[key2])\n comparisons[key1][key2] = len(l1.intersection(l2))\n return comparisons\n\n# Look up the intersection for a keypair. This function is only necessary\n# to make it easier to look up values in a sparse structure\ndef get_comparison(comparisons, key1, key2):\n if key1 in comparisons and key2 in comparisons[key1]:\n return comparisons[key1][key2]\n return comparisons[key2][key1]\n\n# Display the lengths of each intersection in a table format\ndef display_comparisons(comparisons):\n\n cell_width = max([len(key) for key in comparisons.keys()]) + 2\n\n def print_cell(val):\n print(f\"{str(val):<{cell_width}}\", end='')\n\n print_cell('')\n [print_cell(key) for key in comparisons.keys()]\n print()\n for key1 in comparisons.keys():\n print_cell(key1)\n for key2 in comparisons.keys():\n print_cell(get_comparison(comparisons, key1, key2))\n print()\n\ninput = {'key1': [10,10,11,12,15,16,18,19], 'key2': [10,11,13,15,16,19,20], 'key3':[10,11,11,12,15,19,21,23], 'key4':[], 'key5':[0], 'key6':[10,55,66,77]}\n\n# Build the comparison structure\ncomparisons = build_comparisons(input)\n\n# Show the resulting data structure\npprint(comparisons)\n\nprint()\n\n# Display the lengths of each intersection in a table format\ndisplay_comparisons(comparisons)\n\nHere's the resulting output:\n{'key1': {'key1': 8, 'key2': 5, 'key3': 5, 'key4': 0, 'key5': 0, 'key6': 1},\n 'key2': {'key2': 7, 'key3': 4, 'key4': 0, 'key5': 0, 'key6': 1},\n 'key3': {'key3': 8, 'key4': 0, 'key5': 0, 'key6': 1},\n 'key4': {'key4': 0, 'key5': 0, 'key6': 0},\n 'key5': {'key5': 1, 'key6': 0},\n 'key6': {'key6': 4}}\n\n key1 key2 key3 key4 key5 key6 \nkey1 8 5 5 0 0 1 \nkey2 5 7 4 0 0 1 \nkey3 5 4 8 0 0 1 \nkey4 0 0 0 0 0 0 \nkey5 0 0 0 0 1 0 \nkey6 1 1 1 0 0 4 \n\nIf you set sparse to False when computing the data structure, then when you print it, you get this instead:\n{'key1': {'key1': 8, 'key2': 5, 'key3': 5, 'key4': 0, 'key5': 0, 'key6': 1},\n 'key2': {'key1': 5, 'key2': 7, 'key3': 4, 'key4': 0, 'key5': 0, 'key6': 1},\n 'key3': {'key1': 5, 'key2': 4, 'key3': 8, 'key4': 0, 'key5': 0, 'key6': 1},\n 'key4': {'key1': 0, 'key2': 0, 'key3': 0, 'key4': 0, 'key5': 0, 'key6': 0},\n 'key5': {'key1': 0, 'key2': 0, 'key3': 0, 'key4': 0, 'key5': 1, 'key6': 0},\n 'key6': {'key1': 1, 'key2': 1, 'key3': 1, 'key4': 0, 'key5': 0, 'key6': 4}}\n\n"
] |
[
1,
0
] |
[] |
[] |
[
"comparison",
"python",
"upsetplot",
"visualization"
] |
stackoverflow_0074526134_comparison_python_upsetplot_visualization.txt
|
Q:
How can I split a three letter string so that it produces a list?
I need to do an input of the string 'AEN' and it must split into ('A', 'E', 'N')
Ive tried several different splits, but it never produces what i need.
The image shows the code I have done.
What im trying is that x produces a result like y. But, Im having issues whit how to achieve it.
x=input('Letras: ')
y=input('Letras: ')
print(x.split())
print(y.split())
Letras: AEN
Letras: A E N
['AEN']
['A', 'E', 'N']
A:
You just want list, which will take an arbitrary iterable and produce a new list, one item per element. A string is considered to be an iterable of individual characters.
>>> list('AEN')
['A', 'E', 'N']
str.split is for splitting a string base on a given delimiter (or arbitrary whitespace, when no delimiter is given). For example,
>>> 'AEN'.split('E')
['A', 'N']
When the given delimiter is not found in the string, it is vacuously split into a single string, identical to the original.
|
How can I split a three letter string so that it produces a list?
|
I need to do an input of the string 'AEN' and it must split into ('A', 'E', 'N')
Ive tried several different splits, but it never produces what i need.
The image shows the code I have done.
What im trying is that x produces a result like y. But, Im having issues whit how to achieve it.
x=input('Letras: ')
y=input('Letras: ')
print(x.split())
print(y.split())
Letras: AEN
Letras: A E N
['AEN']
['A', 'E', 'N']
|
[
"You just want list, which will take an arbitrary iterable and produce a new list, one item per element. A string is considered to be an iterable of individual characters.\n>>> list('AEN')\n['A', 'E', 'N']\n\nstr.split is for splitting a string base on a given delimiter (or arbitrary whitespace, when no delimiter is given). For example,\n>>> 'AEN'.split('E')\n['A', 'N']\n\nWhen the given delimiter is not found in the string, it is vacuously split into a single string, identical to the original.\n"
] |
[
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0074526224_python.txt
|
Q:
What does singular "*" as an argument in a python function definition do?
I am trying to look through some code and don't know what the asterisk in the following code means.
def pylog(func=None, *, mode='cgen', path=WORKSPACE, backend='vhls', \
board='ultra96', freq=None):
What does the lonely asterisk signify in a function definition when not followed by the name of an argument?
I can only find results for *foo.
A:
This syntax forces arguments after the * to be called with their keyword names when someone calls the function/method.
Example:
# This is allowed
pylog(math.log, mode='cgen')
# This is *NOT* allowed
pylog(math.log, 'cgen')
|
What does singular "*" as an argument in a python function definition do?
|
I am trying to look through some code and don't know what the asterisk in the following code means.
def pylog(func=None, *, mode='cgen', path=WORKSPACE, backend='vhls', \
board='ultra96', freq=None):
What does the lonely asterisk signify in a function definition when not followed by the name of an argument?
I can only find results for *foo.
|
[
"This syntax forces arguments after the * to be called with their keyword names when someone calls the function/method.\nExample:\n# This is allowed\npylog(math.log, mode='cgen')\n\n# This is *NOT* allowed\npylog(math.log, 'cgen')\n\n"
] |
[
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0074526883_python.txt
|
Q:
Pandas: resampling data with mixed, missing or difficult to 'normalize' dates
Im trying to deal with some timeseries data that looks like this. As you can see the data is monthly, but some dates are at EOM, some at BOM and some simply a month name:
The solution i thought of was: assuming this is monthly data and that i know the start and end dates, i would like to create a date range from that start and end date and re-assign to the dataframe as the index. however, when i run this code:
pd.date_range('11/30/2020','03/01/2021', freq='MS')
I end up with this:
DatetimeIndex(['2020-12-01', '2021-01-01', '2021-02-01', '2021-03-01'], dtype='datetime64[ns]', freq='MS')
This is starting at December instead of november, so one less row than i expect.
Why is this happening and what is a good solution here?
UPDATE
doing something like the following solves the problem for me
pd.date_range(pd.to_datetime('11/30/2020').to_period('M').to_timestamp(),'03/01/2021', freq='MS')
Im fine with that - but are there better ways to solve these kind of date issues?
A:
When you use freq="MS" inside pd.date_range, pandas understands that you wish to create a range of dates with a month start frequency. The reason why it starts with '2020-12-01' is because December is the first start of a month that occurs, given '11/30/2020' as the start date. If you wish to include November in your DatetimeIndex, you could use relativedelta function from dateutil package.
To install dateutil, run the following command inside your console:
pip install python-dateutil
Then to include November in your DatetimeIndex, you can do something like this:
import pandas as pd
from dateutil.relativedelta import relativedelta
pd.date_range(
pd.Timestamp('11/30/2020') - relativedelta(day=1),
# ^------------------^
# |
# +-- This ensures that your
# start date is November first.
'03/01/2021',
freq='MS',
)
# Returns:
#
# DatetimeIndex(['2020-11-01', '2020-12-01', '2021-01-01', '2021-02-01',
# '2021-03-01'],
# dtype='datetime64[ns]', freq='MS')
Regarding your difficult to 'normalize' dates, you could try using something like this to normalize it:
import pandas as pd
from dateutil.relativedelta import relativedelta
# Your example data
sample_data = [
"5/31/2011 0:00",
"6/31/2011 0:00",
"7/31/2011 0:00",
"8/31/2011 0:00",
"Sep",
"Oct",
"Nov",
"Dec",
"1/1/2012 0:00",
"Feb",
"Mar",
"Apr",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
"1/1/2013 0:00",
"2/1/2013 0:00",
"3/1/2013 0:00",
"4/1/2013 0:00",
"5/1/2013 0:00",
"6/1/2013 0:00",
]
# Converting sample data values into `datetime64[ns]`
sample_series = pd.to_datetime(sample_data, errors = "coerce")
# ^---------------^
# |
# +-- Using this option,
# pandas converts any
# "un-normalizable" date into
# `pd.NaT`
print(sample_series)
# Prints:
#
# DatetimeIndex(['2011-05-31', 'NaT', '2011-07-31', '2011-08-31',
# 'NaT', 'NaT', 'NaT', 'NaT',
# '2012-01-01', 'NaT', 'NaT', 'NaT',
# 'NaT', 'NaT', 'NaT', 'NaT',
# 'NaT', 'NaT', 'NaT', 'NaT',
# '2013-01-01', '2013-02-01', '2013-03-01', '2013-04-01',
# '2013-05-01', '2013-06-01'],
# dtype='datetime64[ns]', freq=None)
# Create your range of dates using the minimum and maximum values of `sample_series`:
pd.date_range(sample_series.min() - relativedelta(day=1), sample_series.max(), freq='MS')
# Returns:
#
# DatetimeIndex(['2011-05-01', '2011-06-01', '2011-07-01', '2011-08-01',
# '2011-09-01', '2011-10-01', '2011-11-01', '2011-12-01',
# '2012-01-01', '2012-02-01', '2012-03-01', '2012-04-01',
# '2012-05-01', '2012-06-01', '2012-07-01', '2012-08-01',
# '2012-09-01', '2012-10-01', '2012-11-01', '2012-12-01',
# '2013-01-01', '2013-02-01', '2013-03-01', '2013-04-01',
# '2013-05-01', '2013-06-01'],
# dtype='datetime64[ns]', freq='MS')
Warning: the above code assumes that the first and last dates from your data are represented as "parseable" dates. In other words,
if you have a list of dates like this: ["Apr", "5/31/2011 0:00", "6/31/2011 0:00", "7/31/2011 0:00", "8/31/2011 0:00", "September"], the above code would create a DatetimeIndex that starts at '2011-05-01', and ends at '2011-08-01'.
A:
You need to have a start date that is compatible with the chosen freq. So for example 2020-11-01 for freq='MS' (month start).
If you don't have control over the first date (but know for sure it is a date), you can "truncate" it down to month start:
t_str = '11/30/2020'
ix = pd.date_range(pd.Timestamp(t_str).normalize().replace(day=1), freq='MS', periods=5)
>>> ix
DatetimeIndex(['2020-11-01', '2020-12-01', '2021-01-01', '2021-02-01',
'2021-03-01'],
dtype='datetime64[ns]', freq='MS')
Note BTW that it's safer to give one date (start or end) and a number of periods (the desired length of your index). That way, you know the length will be correct.
|
Pandas: resampling data with mixed, missing or difficult to 'normalize' dates
|
Im trying to deal with some timeseries data that looks like this. As you can see the data is monthly, but some dates are at EOM, some at BOM and some simply a month name:
The solution i thought of was: assuming this is monthly data and that i know the start and end dates, i would like to create a date range from that start and end date and re-assign to the dataframe as the index. however, when i run this code:
pd.date_range('11/30/2020','03/01/2021', freq='MS')
I end up with this:
DatetimeIndex(['2020-12-01', '2021-01-01', '2021-02-01', '2021-03-01'], dtype='datetime64[ns]', freq='MS')
This is starting at December instead of november, so one less row than i expect.
Why is this happening and what is a good solution here?
UPDATE
doing something like the following solves the problem for me
pd.date_range(pd.to_datetime('11/30/2020').to_period('M').to_timestamp(),'03/01/2021', freq='MS')
Im fine with that - but are there better ways to solve these kind of date issues?
|
[
"When you use freq=\"MS\" inside pd.date_range, pandas understands that you wish to create a range of dates with a month start frequency. The reason why it starts with '2020-12-01' is because December is the first start of a month that occurs, given '11/30/2020' as the start date. If you wish to include November in your DatetimeIndex, you could use relativedelta function from dateutil package.\nTo install dateutil, run the following command inside your console:\n\npip install python-dateutil\n\n\nThen to include November in your DatetimeIndex, you can do something like this:\n\nimport pandas as pd\nfrom dateutil.relativedelta import relativedelta\n\npd.date_range(\n pd.Timestamp('11/30/2020') - relativedelta(day=1),\n # ^------------------^\n # |\n # +-- This ensures that your\n # start date is November first.\n '03/01/2021',\n freq='MS',\n)\n# Returns:\n#\n# DatetimeIndex(['2020-11-01', '2020-12-01', '2021-01-01', '2021-02-01',\n# '2021-03-01'],\n# dtype='datetime64[ns]', freq='MS')\n\nRegarding your difficult to 'normalize' dates, you could try using something like this to normalize it:\n\nimport pandas as pd\nfrom dateutil.relativedelta import relativedelta\n\n# Your example data\nsample_data = [\n \"5/31/2011 0:00\",\n \"6/31/2011 0:00\",\n \"7/31/2011 0:00\",\n \"8/31/2011 0:00\",\n \"Sep\",\n \"Oct\",\n \"Nov\",\n \"Dec\",\n \"1/1/2012 0:00\",\n \"Feb\",\n \"Mar\",\n \"Apr\",\n \"May\",\n \"June\",\n \"July\",\n \"August\",\n \"September\",\n \"October\",\n \"November\",\n \"December\",\n \"1/1/2013 0:00\",\n \"2/1/2013 0:00\",\n \"3/1/2013 0:00\",\n \"4/1/2013 0:00\",\n \"5/1/2013 0:00\",\n \"6/1/2013 0:00\",\n]\n\n# Converting sample data values into `datetime64[ns]`\nsample_series = pd.to_datetime(sample_data, errors = \"coerce\")\n# ^---------------^\n# |\n# +-- Using this option,\n# pandas converts any\n# \"un-normalizable\" date into\n# `pd.NaT`\nprint(sample_series)\n# Prints:\n#\n# DatetimeIndex(['2011-05-31', 'NaT', '2011-07-31', '2011-08-31',\n# 'NaT', 'NaT', 'NaT', 'NaT',\n# '2012-01-01', 'NaT', 'NaT', 'NaT',\n# 'NaT', 'NaT', 'NaT', 'NaT',\n# 'NaT', 'NaT', 'NaT', 'NaT',\n# '2013-01-01', '2013-02-01', '2013-03-01', '2013-04-01',\n# '2013-05-01', '2013-06-01'],\n# dtype='datetime64[ns]', freq=None)\n\n\n# Create your range of dates using the minimum and maximum values of `sample_series`:\npd.date_range(sample_series.min() - relativedelta(day=1), sample_series.max(), freq='MS')\n# Returns:\n#\n# DatetimeIndex(['2011-05-01', '2011-06-01', '2011-07-01', '2011-08-01',\n# '2011-09-01', '2011-10-01', '2011-11-01', '2011-12-01',\n# '2012-01-01', '2012-02-01', '2012-03-01', '2012-04-01',\n# '2012-05-01', '2012-06-01', '2012-07-01', '2012-08-01',\n# '2012-09-01', '2012-10-01', '2012-11-01', '2012-12-01',\n# '2013-01-01', '2013-02-01', '2013-03-01', '2013-04-01',\n# '2013-05-01', '2013-06-01'],\n# dtype='datetime64[ns]', freq='MS')\n\n\nWarning: the above code assumes that the first and last dates from your data are represented as \"parseable\" dates. In other words,\nif you have a list of dates like this: [\"Apr\", \"5/31/2011 0:00\", \"6/31/2011 0:00\", \"7/31/2011 0:00\", \"8/31/2011 0:00\", \"September\"], the above code would create a DatetimeIndex that starts at '2011-05-01', and ends at '2011-08-01'.\n",
"You need to have a start date that is compatible with the chosen freq. So for example 2020-11-01 for freq='MS' (month start).\nIf you don't have control over the first date (but know for sure it is a date), you can \"truncate\" it down to month start:\nt_str = '11/30/2020'\n\nix = pd.date_range(pd.Timestamp(t_str).normalize().replace(day=1), freq='MS', periods=5)\n>>> ix\nDatetimeIndex(['2020-11-01', '2020-12-01', '2021-01-01', '2021-02-01',\n '2021-03-01'],\n dtype='datetime64[ns]', freq='MS')\n\nNote BTW that it's safer to give one date (start or end) and a number of periods (the desired length of your index). That way, you know the length will be correct.\n"
] |
[
1,
1
] |
[] |
[] |
[
"data_science",
"numpy",
"pandas",
"python"
] |
stackoverflow_0074526777_data_science_numpy_pandas_python.txt
|
Q:
How to create a data frame using two lists in Python?
L1 = ['a','b','c','a','b','c']
L2 = ['Cat','Fish','Crow','Dog','Frog','Eagle']
Desired Output 1: D1 = {'a':['Cat','Dog'],
'b':['Fish','Frog'],
'c':['Crow','Eagle']}
Desired Output 2: DF1 = A B C
Cat Fish Crow
Dog Frog Eagle
I only used from a to c for reference, I've more than 100 columns in DataFrame.
Could someone please help me with this?
A:
Try:
L1 = ["a", "b", "c", "a", "b", "c"]
L2 = ["Cat", "Fish", "Crow", "Dog", "Frog", "Eagle"]
out = {}
for a, b in zip(L1, L2):
out.setdefault(a, []).append(b)
print(out)
Prints:
{"a": ["Cat", "Dog"], "b": ["Fish", "Frog"], "c": ["Crow", "Eagle"]}
Then you can do:
out_df = pd.DataFrame(out)
out_df.columns = out_df.columns.str.upper()
print(out_df)
Prints:
A B C
0 Cat Fish Crow
1 Dog Frog Eagle
A:
Here is a way by creating a blank dictionary and then appending each item to it.
l = list(set(l1))
d = {key:[] for key in l}
for i,j in zip(l1,l2):
d.get(i).append(j)
|
How to create a data frame using two lists in Python?
|
L1 = ['a','b','c','a','b','c']
L2 = ['Cat','Fish','Crow','Dog','Frog','Eagle']
Desired Output 1: D1 = {'a':['Cat','Dog'],
'b':['Fish','Frog'],
'c':['Crow','Eagle']}
Desired Output 2: DF1 = A B C
Cat Fish Crow
Dog Frog Eagle
I only used from a to c for reference, I've more than 100 columns in DataFrame.
Could someone please help me with this?
|
[
"Try:\nL1 = [\"a\", \"b\", \"c\", \"a\", \"b\", \"c\"]\nL2 = [\"Cat\", \"Fish\", \"Crow\", \"Dog\", \"Frog\", \"Eagle\"]\n\nout = {}\nfor a, b in zip(L1, L2):\n out.setdefault(a, []).append(b)\n\nprint(out)\n\nPrints:\n{\"a\": [\"Cat\", \"Dog\"], \"b\": [\"Fish\", \"Frog\"], \"c\": [\"Crow\", \"Eagle\"]}\n\nThen you can do:\nout_df = pd.DataFrame(out)\nout_df.columns = out_df.columns.str.upper()\n\nprint(out_df)\n\nPrints:\n A B C\n0 Cat Fish Crow\n1 Dog Frog Eagle\n\n",
"Here is a way by creating a blank dictionary and then appending each item to it.\nl = list(set(l1))\nd = {key:[] for key in l}\nfor i,j in zip(l1,l2):\n d.get(i).append(j)\n\n"
] |
[
2,
0
] |
[] |
[] |
[
"dictionary",
"list",
"pandas",
"python"
] |
stackoverflow_0074525311_dictionary_list_pandas_python.txt
|
Q:
NetworkX vs Scipy all shortest path algorithms
What are the differences between the NetworkX all shortest paths algorithm and the scipy floyd warshall algorithm? Are there any reasons to prefer one over another? Which is fastest?
A:
(for those who aren't aware the numpy floyd-warshall algorithm is available in networkx)
The networkx description of floyd_warshall_numpy states:
Floyd’s algorithm is appropriate for finding shortest paths in dense graphs or graphs with negative weights when Dijkstra’s algorithm fails. This algorithm can still fail if there are negative cycles. It has running time O(n^3) with running space of O(n^2).
The networkx single_source_shortest_path works better on sparse graphs. You should be aware that if you use the various "shortest_path" algorithms, these ignore edge weights. The various Dijkstra algorithms incorporate edge weights.
There is more description here.
A:
Networkx is easier to use but, in my limited experience, scipy is much faster for shortest-path problems.
|
NetworkX vs Scipy all shortest path algorithms
|
What are the differences between the NetworkX all shortest paths algorithm and the scipy floyd warshall algorithm? Are there any reasons to prefer one over another? Which is fastest?
|
[
"(for those who aren't aware the numpy floyd-warshall algorithm is available in networkx)\nThe networkx description of floyd_warshall_numpy states: \n\nFloyd’s algorithm is appropriate for finding shortest paths in dense graphs or graphs with negative weights when Dijkstra’s algorithm fails. This algorithm can still fail if there are negative cycles. It has running time O(n^3) with running space of O(n^2).\n\nThe networkx single_source_shortest_path works better on sparse graphs. You should be aware that if you use the various \"shortest_path\" algorithms, these ignore edge weights. The various Dijkstra algorithms incorporate edge weights.\nThere is more description here.\n",
"Networkx is easier to use but, in my limited experience, scipy is much faster for shortest-path problems.\n"
] |
[
2,
0
] |
[] |
[] |
[
"networkx",
"python",
"scipy",
"shortest_path"
] |
stackoverflow_0023463713_networkx_python_scipy_shortest_path.txt
|
Q:
How to plot list if values with respect to its key of a dictionary in python
I have a dictionary with list of values
df_param = {};
for i in range(0,1000):
df_param[i]=[[0]]
print(df_param)
df_param={0: [[0], [20], [20], [20], [5], [1], [5]], 1: [[0], [20], [20], [5], [1], [5]], 2: [[0], [20], [20], [5], [5]], 3: [[0], [20], [5], [5]], 4: [[0], [5], [5]], 5: [[0], [5]], 6: [[0]], 7: [[0]], 8: [[0], [20]], 9: [[0]], 10: [[0]]}
I need to plot each key in x-axis and the list of values in y-axis.
this is my code:
for i in range(0,1000):
for j in range(0,10):
curr = df1[j][i]['Classifier'][0]
if(curr=='KNNClassifier'):
df_param[i].append([df1[j][i]['Classifier'][1]['n_neighbors']])
print(df_param)
import matplotlib.pyplot as plt
import matplotlib.pyplot as plt
for key, values in df_param.items():
plt.plot(key, values)
plt.show()
I get the below error.
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-132-176b8a768873> in <module>
1 import matplotlib.pyplot as plt
2 for key, values in df_param.items():
----> 3 plt.plot(key, values)
4 plt.show()
3 frames
/usr/local/lib/python3.7/dist-packages/matplotlib/axes/_base.py in _plot_args(self, tup, kwargs)
340
341 if x.shape[0] != y.shape[0]:
--> 342 raise ValueError(f"x and y must have same first dimension, but "
343 f"have shapes {x.shape} and {y.shape}")
344 if x.ndim > 2 or y.ndim > 2:
ValueError: x and y must have same first dimension, but have shapes (1,) and (7, 1)
A:
If your df_param is a dict of form:
{x0: [[y0_a], [y0_b], ...], x1: [[y1_a], [y1_b], ...], ...} and you wish to make a scatter plot of all the (xk, yk_i), then you can first make a proper xy array with two columns x and y:
import numpy as np
xy = np.array([
(x, y) for x, lst in df_param.items()
for sublst in lst for y in sublst
])
plt.plot(*xy.T, 'o')
|
How to plot list if values with respect to its key of a dictionary in python
|
I have a dictionary with list of values
df_param = {};
for i in range(0,1000):
df_param[i]=[[0]]
print(df_param)
df_param={0: [[0], [20], [20], [20], [5], [1], [5]], 1: [[0], [20], [20], [5], [1], [5]], 2: [[0], [20], [20], [5], [5]], 3: [[0], [20], [5], [5]], 4: [[0], [5], [5]], 5: [[0], [5]], 6: [[0]], 7: [[0]], 8: [[0], [20]], 9: [[0]], 10: [[0]]}
I need to plot each key in x-axis and the list of values in y-axis.
this is my code:
for i in range(0,1000):
for j in range(0,10):
curr = df1[j][i]['Classifier'][0]
if(curr=='KNNClassifier'):
df_param[i].append([df1[j][i]['Classifier'][1]['n_neighbors']])
print(df_param)
import matplotlib.pyplot as plt
import matplotlib.pyplot as plt
for key, values in df_param.items():
plt.plot(key, values)
plt.show()
I get the below error.
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-132-176b8a768873> in <module>
1 import matplotlib.pyplot as plt
2 for key, values in df_param.items():
----> 3 plt.plot(key, values)
4 plt.show()
3 frames
/usr/local/lib/python3.7/dist-packages/matplotlib/axes/_base.py in _plot_args(self, tup, kwargs)
340
341 if x.shape[0] != y.shape[0]:
--> 342 raise ValueError(f"x and y must have same first dimension, but "
343 f"have shapes {x.shape} and {y.shape}")
344 if x.ndim > 2 or y.ndim > 2:
ValueError: x and y must have same first dimension, but have shapes (1,) and (7, 1)
|
[
"If your df_param is a dict of form:\n{x0: [[y0_a], [y0_b], ...], x1: [[y1_a], [y1_b], ...], ...} and you wish to make a scatter plot of all the (xk, yk_i), then you can first make a proper xy array with two columns x and y:\nimport numpy as np\n\nxy = np.array([\n (x, y) for x, lst in df_param.items()\n for sublst in lst for y in sublst\n])\nplt.plot(*xy.T, 'o')\n\n\n"
] |
[
0
] |
[] |
[] |
[
"dictionary",
"matplotlib",
"python",
"visualization"
] |
stackoverflow_0074526399_dictionary_matplotlib_python_visualization.txt
|
Q:
How to use virtualenv in makefile
I want to perform several operations while working on a specified virtualenv.
For example command
make install
would be equivalent to
source path/to/virtualenv/bin/activate
pip install -r requirements.txt
Is it possible?
A:
I like using something that runs only when requirements.txt changes:
This assumes that source files are under project in your project's root directory and that tests are under project/test. (You should change project to match your actually project name.)
venv: venv/touchfile
venv/touchfile: requirements.txt
test -d venv || virtualenv venv
. venv/bin/activate; pip install -Ur requirements.txt
touch venv/touchfile
test: venv
. venv/bin/activate; nosetests project/test
clean:
rm -rf venv
find -iname "*.pyc" -delete
Run make to install packages in requirements.txt.
Run make test to run your tests (you can update this command if your tests are somewhere else).
run make clean to delete all artifacts.
A:
In make you can run a shell as command. In this shell you can do everything you can do in a shell you started from comandline. Example:
install:
( \
source path/to/virtualenv/bin/activate; \
pip install -r requirements.txt; \
)
Attention must be paid to the ;and the \.
Everything between the open and close brace will be done in a single instance of a shell.
A:
Normally make runs every command in a recipe in a different subshell. However, setting .ONESHELL: will run all the commands in a recipe in the same subshell, allowing you to activate a virtualenv and then run commands inside it.
Note that .ONESHELL: applies to the whole Makefile, not just a single recipe. It may change behaviour of existing commands, details of possible errors in the full documentation. This will not let you activate a virtualenv for use outside the Makefile, since the commands are still run inside a subshell.
Reference documentation: https://www.gnu.org/software/make/manual/html_node/One-Shell.html
Example:
.ONESHELL:
.PHONY: install
install:
source path/to/virtualenv/bin/activate
pip install -r requirements.txt
A:
I have had luck with this.
install:
source ./path/to/bin/activate; \
pip install -r requirements.txt; \
A:
This is an alternate way to run things that you want to run in virtualenv.
BIN=venv/bin/
install:
$(BIN)pip install -r requirements.txt
run:
$(BIN)python main.py
PS: This doesn't activate the virtualenv, but gets thing done. Hope you find it clean and useful.
A:
I like to set my Makefile up so that it uses a venv directory if one exists, but defaults to using the PATH.
For local development, I like to use a venv, so I run:
# Running this: # Actually runs this:
make venv # /usr/bin/python3 -m venv venv
make deps # .venv/bin/python -m pip install -r requirements.txt
make test # .venv/bin/python -m tox
If I'm installing into a container though, or into my machine, I might bypass the virtual environment:
# Running this: # Actually runs this:
make deps # /usr/bin/python3 -m pip install -r requirements.txt
make test # /usr/bin/python3 -m tox
make build # /usr/bin/python3 -m build --wheel
make install # /usr/bin/python3 -m pip install dist/*.whl
Setup
At the top of your Makefile, define these two variables:
# If `venv/bin/python` exists, it is used. If not, use PATH to find python.
SYSTEM_PYTHON = $(or $(shell which python3), $(shell which python))
PYTHON = $(or $(wildcard venv/bin/python), $(SYSTEM_PYTHON))
Which evaluate to:
# If "venv" dir exists:
SYSTEM_PYTHON = /usr/bin/python3
PYTHON = .venv/bin/python
# If "venv" dir does not exist:
SYSTEM_PYTHON = /usr/bin/python3
PYTHON = /usr/bin/python3
Note: /usr/bin/python3 could be something else on your system, depending on your PATH.
In your makefile, run executables (including pip) like this:
$(PYTHON) -m tox
You might want to create a target called "venv" that creates the venv directory:
venv:
rm -rf $(VENV)
$(SYSTEM_PYTHON) -m venv $(VENV)
And a deps target to install dependencies:
deps:
$(PYTHON) -m pip install -r requirements.txt
Example
Here's my Makefile:
MAKEFLAGS = --no-print-directory --no-builtin-rules
.DEFAULT_GOAL = all
# Variables
PACKAGE = mypackage
# If virtualenv exists, use it. If not, use PATH to find
SYSTEM_PYTHON = $(or $(shell which python3), $(shell which python))
PYTHON = $(or $(wildcard venv/bin/python), $(SYSTEM_PYTHON))
all: test build
.PHONY: all
## Environment
venv:
rm -rf venv
$(SYSTEM_PYTHON) -m venv venv
deps:
$(PYTHON) -m pip install --upgrade pip -r requirements.txt -r requirements_dev.txt
.PHONY: venv deps
## Lint, test
test:
$(PYTHON) -m tox
dev/test:
$(PYTHON) -m tox -e py38
dev/lint:
$(PYTHON) -m tox -e lint
dev/lintfix:
$(PYTHON) -m black $(PACKAGE) tests setup.py
.PHONY: test dev/test dev/lint dev/lintfix
## Build, install
build:
$(PYTHON) -m build --sdist
$(PYTHON) -m build --wheel
install:
$(PYTHON) -m pip install dist/$(PACKAGE)-*.whl
.PHONY: build install
## Clean
clean:
rm -rf .out .pytest_cache .tox *.egg-info dist build
.PHONY: clean
A:
Based on the answers above (thanks @Saurabh and @oneself!) I've written a reusable Makefile that takes care of creating virtual environment and keeping it updated: https://github.com/sio/Makefile.venv
It works by referencing correct executables within virtualenv and does not rely on the "activate" shell script. Here is an example:
test: venv
$(VENV)/python -m unittest
include Makefile.venv
Differences between Windows and other operating systems are taken into account, Makefile.venv should work fine on any OS that provides Python and make.
A:
You also could use the environment variable called "VIRTUALENVWRAPPER_SCRIPT". Like this:
install:
( \
source $$VIRTUALENVWRAPPER_SCRIPT; \
pip install -r requirements.txt; \
)
A:
A bit late to the party but here's my usual setup:
# system python interpreter. used only to create virtual environment
PY = python3
VENV = venv
BIN=$(VENV)/bin
# make it work on windows too
ifeq ($(OS), Windows_NT)
BIN=$(VENV)/Scripts
PY=python
endif
all: lint test
$(VENV): requirements.txt requirements-dev.txt setup.py
$(PY) -m venv $(VENV)
$(BIN)/pip install --upgrade -r requirements.txt
$(BIN)/pip install --upgrade -r requirements-dev.txt
$(BIN)/pip install -e .
touch $(VENV)
.PHONY: test
test: $(VENV)
$(BIN)/pytest
.PHONY: lint
lint: $(VENV)
$(BIN)/flake8
.PHONY: release
release: $(VENV)
$(BIN)/python setup.py sdist bdist_wheel upload
clean:
rm -rf $(VENV)
find . -type f -name *.pyc -delete
find . -type d -name __pycache__ -delete
I did some more detailed writeup on that, but basically the idea is that you use the system's Python to create the virtual environment and for the other targets just prefix your command with the $(BIN) variable which points to the bin or Scripts directory inside your venv. This is equivalent to the activate function.
A:
I found prepending to $PATH and adding $VIRTUAL_ENV was the best route:
No need to clutter up recipes with activate and constrain oneself to ; chaining
Shown here and here
Can simply use python as you would normally, and it will fall back onto system Python
No need for third party packages
Compatible with both Windows (if using bash) and POSIX
# SYSTEM_PYTHON defaults to Python on the local machine
SYSTEM_PYTHON = $(shell which python)
REPO_ROOT = $(shell pwd)
# Specify with REPO_ROOT so recipes can safely change directories
export VIRTUAL_ENV := ${REPO_ROOT}/venv
# bin = POSIX, Scripts = Windows
export PATH := ${VIRTUAL_ENV}/bin:${VIRTUAL_ENV}/Scripts:${PATH}
And for those interested in example usages:
# SEE: http://redsymbol.net/articles/unofficial-bash-strict-mode/
SHELL=/bin/bash -euo pipefail
.DEFAULT_GOAL := fresh-install
show-python: ## Show path to python and version.
@echo -n "python location: "
@python -c "import sys; print(sys.executable, end='')"
@echo -n ", version: "
@python -c "import platform; print(platform.python_version())"
show-venv: show-python
show-venv: ## Show output of python -m pip list.
python -m pip list
install: show-python
install: ## Install all dev dependencies into a local virtual environment.
python -m pip install -r requirements-dev.txt --progress-bar off
fresh-install: ## Run a fresh install into a local virtual environment.
-rm -rf venv
$(SYSTEM_PYTHON) -m venv venv
@$(MAKE) install
|
How to use virtualenv in makefile
|
I want to perform several operations while working on a specified virtualenv.
For example command
make install
would be equivalent to
source path/to/virtualenv/bin/activate
pip install -r requirements.txt
Is it possible?
|
[
"I like using something that runs only when requirements.txt changes:\nThis assumes that source files are under project in your project's root directory and that tests are under project/test. (You should change project to match your actually project name.)\nvenv: venv/touchfile\n\nvenv/touchfile: requirements.txt\n test -d venv || virtualenv venv\n . venv/bin/activate; pip install -Ur requirements.txt\n touch venv/touchfile\n\ntest: venv\n . venv/bin/activate; nosetests project/test\n\nclean:\n rm -rf venv\n find -iname \"*.pyc\" -delete\n\n\nRun make to install packages in requirements.txt.\nRun make test to run your tests (you can update this command if your tests are somewhere else).\nrun make clean to delete all artifacts.\n\n",
"In make you can run a shell as command. In this shell you can do everything you can do in a shell you started from comandline. Example:\ninstall:\n ( \\\n source path/to/virtualenv/bin/activate; \\\n pip install -r requirements.txt; \\\n )\n\nAttention must be paid to the ;and the \\.\nEverything between the open and close brace will be done in a single instance of a shell.\n",
"Normally make runs every command in a recipe in a different subshell. However, setting .ONESHELL: will run all the commands in a recipe in the same subshell, allowing you to activate a virtualenv and then run commands inside it.\nNote that .ONESHELL: applies to the whole Makefile, not just a single recipe. It may change behaviour of existing commands, details of possible errors in the full documentation. This will not let you activate a virtualenv for use outside the Makefile, since the commands are still run inside a subshell. \nReference documentation: https://www.gnu.org/software/make/manual/html_node/One-Shell.html\nExample:\n.ONESHELL:\n\n.PHONY: install\ninstall:\n source path/to/virtualenv/bin/activate\n pip install -r requirements.txt\n\n",
"I have had luck with this.\ninstall:\n source ./path/to/bin/activate; \\\n pip install -r requirements.txt; \\\n\n",
"This is an alternate way to run things that you want to run in virtualenv. \nBIN=venv/bin/\n\ninstall:\n $(BIN)pip install -r requirements.txt\n\nrun:\n $(BIN)python main.py\n\nPS: This doesn't activate the virtualenv, but gets thing done. Hope you find it clean and useful.\n",
"I like to set my Makefile up so that it uses a venv directory if one exists, but defaults to using the PATH.\nFor local development, I like to use a venv, so I run:\n# Running this: # Actually runs this:\nmake venv # /usr/bin/python3 -m venv venv\nmake deps # .venv/bin/python -m pip install -r requirements.txt\nmake test # .venv/bin/python -m tox\n\nIf I'm installing into a container though, or into my machine, I might bypass the virtual environment:\n# Running this: # Actually runs this:\nmake deps # /usr/bin/python3 -m pip install -r requirements.txt\nmake test # /usr/bin/python3 -m tox\nmake build # /usr/bin/python3 -m build --wheel\nmake install # /usr/bin/python3 -m pip install dist/*.whl\n\nSetup\nAt the top of your Makefile, define these two variables:\n# If `venv/bin/python` exists, it is used. If not, use PATH to find python.\nSYSTEM_PYTHON = $(or $(shell which python3), $(shell which python))\nPYTHON = $(or $(wildcard venv/bin/python), $(SYSTEM_PYTHON))\n\nWhich evaluate to:\n# If \"venv\" dir exists:\nSYSTEM_PYTHON = /usr/bin/python3\nPYTHON = .venv/bin/python\n\n# If \"venv\" dir does not exist:\nSYSTEM_PYTHON = /usr/bin/python3\nPYTHON = /usr/bin/python3\n\nNote: /usr/bin/python3 could be something else on your system, depending on your PATH.\nIn your makefile, run executables (including pip) like this:\n$(PYTHON) -m tox\n\nYou might want to create a target called \"venv\" that creates the venv directory:\nvenv:\n rm -rf $(VENV)\n $(SYSTEM_PYTHON) -m venv $(VENV)\n\nAnd a deps target to install dependencies:\ndeps:\n $(PYTHON) -m pip install -r requirements.txt\n\nExample\nHere's my Makefile:\nMAKEFLAGS = --no-print-directory --no-builtin-rules\n.DEFAULT_GOAL = all\n\n# Variables\nPACKAGE = mypackage\n\n# If virtualenv exists, use it. If not, use PATH to find\nSYSTEM_PYTHON = $(or $(shell which python3), $(shell which python))\nPYTHON = $(or $(wildcard venv/bin/python), $(SYSTEM_PYTHON))\n\nall: test build\n\n.PHONY: all\n\n## Environment\n\nvenv:\n rm -rf venv\n $(SYSTEM_PYTHON) -m venv venv\n\ndeps:\n $(PYTHON) -m pip install --upgrade pip -r requirements.txt -r requirements_dev.txt\n\n.PHONY: venv deps\n\n## Lint, test\n\ntest:\n $(PYTHON) -m tox\n\ndev/test:\n $(PYTHON) -m tox -e py38\n\ndev/lint:\n $(PYTHON) -m tox -e lint\n\ndev/lintfix:\n $(PYTHON) -m black $(PACKAGE) tests setup.py\n\n.PHONY: test dev/test dev/lint dev/lintfix\n\n## Build, install\n\nbuild:\n $(PYTHON) -m build --sdist\n $(PYTHON) -m build --wheel\n\ninstall:\n $(PYTHON) -m pip install dist/$(PACKAGE)-*.whl\n\n.PHONY: build install\n\n## Clean\n\nclean:\n rm -rf .out .pytest_cache .tox *.egg-info dist build\n\n.PHONY: clean\n\n",
"Based on the answers above (thanks @Saurabh and @oneself!) I've written a reusable Makefile that takes care of creating virtual environment and keeping it updated: https://github.com/sio/Makefile.venv\nIt works by referencing correct executables within virtualenv and does not rely on the \"activate\" shell script. Here is an example:\ntest: venv\n $(VENV)/python -m unittest\n\ninclude Makefile.venv\n\nDifferences between Windows and other operating systems are taken into account, Makefile.venv should work fine on any OS that provides Python and make.\n",
"You also could use the environment variable called \"VIRTUALENVWRAPPER_SCRIPT\". Like this:\ninstall:\n ( \\\n source $$VIRTUALENVWRAPPER_SCRIPT; \\\n pip install -r requirements.txt; \\\n )\n\n",
"A bit late to the party but here's my usual setup:\n# system python interpreter. used only to create virtual environment\nPY = python3\nVENV = venv\nBIN=$(VENV)/bin\n\n# make it work on windows too\nifeq ($(OS), Windows_NT)\n BIN=$(VENV)/Scripts\n PY=python\nendif\n\n\nall: lint test\n\n$(VENV): requirements.txt requirements-dev.txt setup.py\n $(PY) -m venv $(VENV)\n $(BIN)/pip install --upgrade -r requirements.txt\n $(BIN)/pip install --upgrade -r requirements-dev.txt\n $(BIN)/pip install -e .\n touch $(VENV)\n\n.PHONY: test\ntest: $(VENV)\n $(BIN)/pytest\n\n.PHONY: lint\nlint: $(VENV)\n $(BIN)/flake8\n\n.PHONY: release\nrelease: $(VENV)\n $(BIN)/python setup.py sdist bdist_wheel upload\n\nclean:\n rm -rf $(VENV)\n find . -type f -name *.pyc -delete\n find . -type d -name __pycache__ -delete\n\nI did some more detailed writeup on that, but basically the idea is that you use the system's Python to create the virtual environment and for the other targets just prefix your command with the $(BIN) variable which points to the bin or Scripts directory inside your venv. This is equivalent to the activate function.\n",
"I found prepending to $PATH and adding $VIRTUAL_ENV was the best route:\n\nNo need to clutter up recipes with activate and constrain oneself to ; chaining\n\nShown here and here\n\n\nCan simply use python as you would normally, and it will fall back onto system Python\n\nNo need for third party packages\nCompatible with both Windows (if using bash) and POSIX\n\n\n\n# SYSTEM_PYTHON defaults to Python on the local machine\nSYSTEM_PYTHON = $(shell which python)\n\nREPO_ROOT = $(shell pwd)\n# Specify with REPO_ROOT so recipes can safely change directories\nexport VIRTUAL_ENV := ${REPO_ROOT}/venv\n# bin = POSIX, Scripts = Windows\nexport PATH := ${VIRTUAL_ENV}/bin:${VIRTUAL_ENV}/Scripts:${PATH}\n\nAnd for those interested in example usages:\n# SEE: http://redsymbol.net/articles/unofficial-bash-strict-mode/\nSHELL=/bin/bash -euo pipefail\n.DEFAULT_GOAL := fresh-install\n\nshow-python: ## Show path to python and version.\n @echo -n \"python location: \"\n @python -c \"import sys; print(sys.executable, end='')\"\n @echo -n \", version: \"\n @python -c \"import platform; print(platform.python_version())\"\n\nshow-venv: show-python\nshow-venv: ## Show output of python -m pip list.\n python -m pip list\n\ninstall: show-python\ninstall: ## Install all dev dependencies into a local virtual environment.\n python -m pip install -r requirements-dev.txt --progress-bar off\n\nfresh-install: ## Run a fresh install into a local virtual environment.\n -rm -rf venv\n $(SYSTEM_PYTHON) -m venv venv\n @$(MAKE) install\n\n"
] |
[
75,
69,
33,
20,
15,
8,
7,
0,
0,
0
] |
[
"You should use this, it's functional for me at moment.\nreport.ipynb : merged.ipynb\n ( bash -c \"source ${HOME}/anaconda3/bin/activate py27; which -a python; \\\n jupyter nbconvert \\\n --to notebook \\\n --ExecutePreprocessor.kernel_name=python2 \\\n --ExecutePreprocessor.timeout=3000 \\\n --execute merged.ipynb \\\n --output=$< $<\" )\n\n"
] |
[
-3
] |
[
"makefile",
"python",
"virtualenv"
] |
stackoverflow_0024736146_makefile_python_virtualenv.txt
|
Q:
Strange python dictionary keys
I encounter a strange dictionary. Let's call it cp_dict. When I type:
cp_dict['ZnS-Zn']
it returns:
{Element Zn: -1.159460605, Element S: -4.384479766249999}
The child key looks like a string but without quotation marks. How I can access the child keys (for example: Element Zn) and modify the values? I tried cp_dict['Zn3P2-Zn'][Element Zn], and the error is
SyntaxError: invalid syntax. Perhaps you forgot a comma?
The cp_dict['Zn3P2-Zn']['Element Zn'] leads to:
KeyError: 'Element Zn'
I checked type(cp_dict['ZnS-Zn']) . It returns <class 'dict'>.
A:
It is quite easy to make a custom class which represents itself in that way ("looking like a string but without quotation marks"). The result returned by a __repr__ method is what gets used when representing instances inside collections such as dicts and lists:
>>> class Element:
... def __init__(self, symbol):
... self.symbol = symbol
... def __repr__(self):
... return f"Element {self.symbol}"
...
>>> d = {Element("Zn"): -1.159460605, Element("S"): -4.384479766249999}
>>> d
{Element Zn: -1.159460605, Element S: -4.384479766249999}
So, my guess is the keys of the dict are the strange items, not the dict itself. Check the type of a key, and look up it's __repr__ method. You can get the type of the first key with:
k = next(iter(cp_dict["ZnS-Zn"]))
Element = type(k)
To index the dict you will need an instance which compares equal with one of those keys. Again, look up type(k).__eq__ for that. If the __eq__ method is not customized, then you will need to use the identical key to index this dict, since the equality method will just be the default identity-based implementation which is inherited from object.
|
Strange python dictionary keys
|
I encounter a strange dictionary. Let's call it cp_dict. When I type:
cp_dict['ZnS-Zn']
it returns:
{Element Zn: -1.159460605, Element S: -4.384479766249999}
The child key looks like a string but without quotation marks. How I can access the child keys (for example: Element Zn) and modify the values? I tried cp_dict['Zn3P2-Zn'][Element Zn], and the error is
SyntaxError: invalid syntax. Perhaps you forgot a comma?
The cp_dict['Zn3P2-Zn']['Element Zn'] leads to:
KeyError: 'Element Zn'
I checked type(cp_dict['ZnS-Zn']) . It returns <class 'dict'>.
|
[
"It is quite easy to make a custom class which represents itself in that way (\"looking like a string but without quotation marks\"). The result returned by a __repr__ method is what gets used when representing instances inside collections such as dicts and lists:\n>>> class Element:\n... def __init__(self, symbol):\n... self.symbol = symbol\n... def __repr__(self):\n... return f\"Element {self.symbol}\"\n... \n>>> d = {Element(\"Zn\"): -1.159460605, Element(\"S\"): -4.384479766249999}\n>>> d\n{Element Zn: -1.159460605, Element S: -4.384479766249999}\n\nSo, my guess is the keys of the dict are the strange items, not the dict itself. Check the type of a key, and look up it's __repr__ method. You can get the type of the first key with:\nk = next(iter(cp_dict[\"ZnS-Zn\"]))\nElement = type(k)\n\nTo index the dict you will need an instance which compares equal with one of those keys. Again, look up type(k).__eq__ for that. If the __eq__ method is not customized, then you will need to use the identical key to index this dict, since the equality method will just be the default identity-based implementation which is inherited from object.\n"
] |
[
4
] |
[] |
[] |
[
"python"
] |
stackoverflow_0074526968_python.txt
|
Q:
how to compare each cell of dataframe with list of dictionary in python?
I am trying to compare column values of each rows of dataframe with predefined list of dictionary, and do filtering. I tried pandas to compare column value by row-wise with list of dictionary, but it is not quite working, I got type error. I think I may need to convert dataframe into dictionary then compare it with list of dictionary then convert back to dataframe with new column added, but this still not giving my desired output. Does anyone suggest possible workaround on this? How can we do this easily in python
working minimal example
import pandas as pd
indf=pd.DataFrame.from_dict(indf_dict)
indf_lst=indf.to_dict(orient='records')
matches=[]
for each in rules_list:
for row in indf_lst:
if row in each:
matches.append(row)
I tried pandas approach to check column values of every rows in rules_list but the attempt is not successful. Now I tried to convert indf dataframe to dictionary and compare two dictionary, but I have type error as follow:
TypeError Traceback (most recent call last)
Input In [11], in <cell line: 12>()
12 for each in rules_list:
13 for row in indf_lst:
---> 14 if row in each:
15 matches.append(row)
TypeError: unhashable type: 'dict'
objective
I need to compare columns of every rows with list of dictionary rules_list, and add new column which shows found match or not. How this can be done in python?
updated desired output
here is my desired output where I want to add two new columns when columns values hit match with list of dictionary rules_list that I defined.
output={'code0':{0:('5'),1:'nan',2:('98'),3:('98'),4:'nan',5:('15'),6:('40'),7:('52'),8:('52'),9:('40'),10:('52'),11:('52'),12:('58')},'code1':{0:('Agr','Serv'),1:('VA','HC','NIH','SAP','AUS','HOL','ATT','COL','UCL'),2:('ATT','NC'),3:('ATT','VA','NC'),4:('VA','HC','NIH','ATT','COL','UCL'),5:('Agr'),6:'nan',7:('NC'),8:('NC'),9:('VA'),10:('NC'),11:('NC'),12:('CE')},'code2':{0:'nan',1:'nan',2:('103','104','105','106','31'),3:('104','105'),4:'nan',5:('5'),6:'nan',7:('109'),8:('109'),9:('11'),10:('109'),11:('109'),12:('109')},'code3':{0:('90'),1:'nan',2:('810'),3:('810'),4:'nan',5:('58'),6:('518'),7:('610','620','682','642','621','611'),8:('620','682','642','611'),9:('113','174','131','115'),10:('612','790','110'),11:('612','110'),12:('423','114')},'code4':{0:('1'),1:'nan',2:('computerscience'),3:('computerscience'),4:'nan',5:('fishing'),6:'nan',7:('biology'),8:('biology'),9:'nan',10:('biology'),11:('biology'),12:'nan'},'code5':{0:'nan',1:'nan',2:'nan',3:'nan',4:'nan',5:'nan',6:'nan',7:'nan',8:'nan',9:('11','19','31'),10:('12','16','18','19'),11:('12','18','19'),12:('31')},'code6':{0:'nan',1:'nan',2:'nan',3:'nan',4:'nan',5:'nan',6:('594'),7:('712','479','297','639','452','172'),8:('712','479','297'),9:('164','157','388','158'),10:('285','295','236','239','269','284','237'),11:('285','295','237'),12:('372','238')},'isHit':{0:False,1:True,2:True,3:True,4:True,5:False,6:True,7:True,8:True,9:True,10:True,11:True,12:True},'rules_desc':{0:'None',1:'rules1',2:'rules2',3:'rules2',4:'rules1',5:'None',6:'rules12',7:'rules21',8:'rules21',9:'rules4',10:'rules3',11:'rules3',12:'rules5'}}
outdf=pd.DataFrame.from_dict(output)
how can I achieve this sort of mapping value from each cell of dataframe to list of dictionary? should I handle this in pandas or convert them into list then compare it? any possible thoughts? Anything close to above desired output should be fine.
A:
The code below should do what you are asking for, but I haven't tested it yet if it actually really does what it should. I have put some effort in appropriate naming of the variables to make it easier to understand what the code does and how it works.
In the first step the code transforms the list with dictionaries for the rules into a list of tuples with code and code value for each of the rules with the purpose of making the final loop for checking if there is a hit easier to put together, understand, maintain and debug.
In the second step the code transforms the dictionary with data using pandas like it is done in code mentioned in the question.
Probably there is also a pandas way of transforming the list of dictionaries in the first step, so if you read this and know how to accomplish this using pandas I would be glad to hear about that.
Maybe there is a way to accomplish the entire task using pandas and two or three lines of code ... now with the variable naming and the provided code of the loops it would be easier for you who is reading this to come up with the code and provide maybe another and better answer.
from pprint import pprint
import pandas as pd
from collections import defaultdict
# ----------------------------------------------------------------------
rules_list=rules_dict=[{'code1':('VA','HC','NIH','SAP','AUS','HOL','ATT','COL','UCL'),'rules_desc':'rules1'},{'code0':('40'),'code3':('518'),'code6':('594'),'rules_desc':'rules12'},{'code0':('98'),'code1':('ATT','NC'),'code2':('103','104','105','106','31'),'code3':('810'),'code4':('computerscience'),'rules_desc':'rules2'},{'code0':('98'),'code1':('ATT','VA','NC'),'code2':('104','105','106','31'),'code4':('computerscience'),'rules_desc':'rules2'},{'code0':('52'),'code1':('NC'),'code2':('109'),'code3':('610','620','682','642','621','611'),'code4':('biology'),'code6':('712','479','297','639','452','172'),'rules_desc':'rules2'},{'code0':('52'),'code1':('NC'),'code2':('109'),'code3':('396','340','394','393','240'),'code4':('biology'),'code5':('12','18'),'rules_desc':'rules2'},{'code0':('52'),'code1':('NC'),'code2':('109'),'code3':('612','790','110'),'code4':('biology'),'code5':('12','16','18','19'),'code6':('285','295','236','239','269','284','237'),'rules_desc':'rules3'},{'code0':('52'),'code1':('NC'),'code2':('109'),'code3':('730','320','350','379','812','374'),'code4':('biology'),'code5':('12','18','19'),'rules_desc':'rules3'},{'code0':('40'),'code1':('VA'),'code2':('11'),'code3':('113','174','131','115'),'code5':('11','19','31'),'code6':('164','157','388','158'),'rules_desc':'rules4'},{'code0':('58'),'code1':('CE'),'code2':('109'),'code3':('423','114'),'code5':('31'),'code6':('372','238'),'rules_desc':'rules5'}]
# codeNname : 'code1', 'code2', 'code3', ..., 'code6'
# ruleNname : 'rules1', 'rules12', 'rules2', ..., 'rules5'
# ruleDescrKey : 'rules_desc'
# dictRulesSpec : dictionary { codeNname:value {1,N} ... , rulesDct_ruleKey:ruleNname }
# dictCodes : dictionary { codeNname:value, codeNname:value, ... }
# Rules : List [ dictRulesSpec, dictRulesSpec, ... ]
# dictRules : { ruleNname:[codeNname, codeNnameValue], ... }
Rules = rules_list
ruleDescrKey = 'rules_desc'
dictRules = defaultdict(list)
for dictRulesSpec in Rules:
ruleNname = dictRulesSpec.pop(ruleDescrKey)
# dictRulesSpec without ruleDescrKey item has only Codes as keys, so:
dictCodes = dictRulesSpec
for codeNname, codeNnameValue in dictCodes.items():
dictRules[ruleNname].append( (codeNname, codeNnameValue) )
print(f'{Rules=}')
print(f'{dictRules=}')
print(' ------------- ')
# ----------------------------------------------------------------------
indf_dict={'code0':{0:('5'),1:'nan',2:('98'),3:('98'),4:'',5:('15'),6:('40'),7:('52'),8:('52'),9:('40'),10:('52'),11:('52'),12:('58')},'code1':{0:('Agr','Serv'),1:('VA','HC','NIH','SAP','AUS','HOL','ATT','COL','UCL'),2:('ATT','NC'),3:('ATT','VA','NC'),4:('VA','HC','NIH','ATT','COL','UCL'),5:('Agr'),6:'nan',7:('NC'),8:('NC'),9:('VA'),10:('NC'),11:('NC'),12:('CE')},'code2':{0:'nan',1:'nan',2:('103','104','105','106','31'),3:('104','105'),4:'nan',5:('5'),6:'nan',7:('109'),8:('109'),9:('11'),10:('109'),11:('109'),12:('109')},'code3':{0:('90'),1:'nan',2:('810'),3:('810'),4:'nan',5:('58'),6:('518'),7:('610','620','682','642','621','611'),8:('620','682','642','611'),9:('113','174','131','115'),10:('612','790','110'),11:('612','110'),12:('423','114')},'code4':{0:('1'),1:'nan',2:('computerscience'),3:('computerscience'),4:'nan',5:('fishing'),6:'nan',7:('biology'),8:('biology'),9:'nan',10:('biology'),11:('biology'),12:'nan'},'code5':{0:'nan',1:'nan',2:'nan',3:'nan',4:'nan',5:'nan',6:'nan',7:'nan',8:'nan',9:('11','19','31'),10:('12','16','18','19'),11:('12','18','19'),12:'31'},'code6':{0:'nan',1:'nan',2:'nan',3:'nan',4:'nan',5:'nan',6:'594',7:('712','479','297','639','452','172'),8:('712','479','297'),9:('164','157','388','158'),10:('285','295','236','239','269','284','237'),11:('285','295','237'),12:('372','238')}}
dictDataRowsByCodeNname = indf_dict
df_dictDataRowsByCodeNname = pd.DataFrame.from_dict(dictDataRowsByCodeNname)
print(f'{dictDataRowsByCodeNname=}')
listDataRowsByRow = df_dictDataRowsByCodeNname.to_dict(orient='records')
print(f'{listDataRowsByRow=}')
print(' ------------- ')
isHit_Column = []
rules_desc_Column = []
# The loop below tests for only one hit within the rule ...
for dctDataRow in listDataRowsByRow:
isHit = False
for ruleNname, listTuplesCodeNnameValue in dictRules.items():
if isHit:
break
for codeNname, codeNnameValue in listTuplesCodeNnameValue:
if isHit:
break
else:
if dctDataRow[codeNname] == codeNnameValue:
isHit = True
bckpRuleNname = ruleNname
break
rules_desc_Column.append( bckpRuleNname if isHit else None)
isHit_Column.append(isHit)
print(f'{rules_desc_Column = }')
print(f'{isHit_Column = }')
print('================================')
df_dictDataRowsByCodeNname['isHit'] = isHit_Column
df_dictDataRowsByCodeNname['rules_desc'] = rules_desc_Column
print(df_dictDataRowsByCodeNname)
print('================================')
isHit_Column = []
rules_desc_Column = []
# The loop below tests for all hits within the rule and
# lists all rules that apply in case of hits:
for dctDataRow in listDataRowsByRow:
lstRulesWithHits = []
for ruleNname, listTuplesCodeNnameValue in dictRules.items():
ruleItemsWithHits = 0
for codeNname, codeNnameValue in listTuplesCodeNnameValue:
if dctDataRow[codeNname] == codeNnameValue:
ruleItemsWithHits += 1
if ruleItemsWithHits == len(listTuplesCodeNnameValue):
lstRulesWithHits.append(ruleNname)
isHit = bool(lstRulesWithHits)
rules_desc_Column.append( lstRulesWithHits if isHit else None)
isHit_Column.append(isHit)
df_dictDataRowsByCodeNname['isHit'] = isHit_Column
df_dictDataRowsByCodeNname['rules_desc'] = rules_desc_Column
print(df_dictDataRowsByCodeNname)
print('================================')
which gives:
Rules=[{'code1': ('VA', 'HC', 'NIH', 'SAP', 'AUS', 'HOL', 'ATT', 'COL', 'UCL')}, {'code0': '40', 'code3': '518', 'code6': '594'}, {'code0': '98', 'code1': ('ATT', 'NC'), 'code2': ('103', '104', '105', '106', '31'), 'code3': '810', 'code4': 'computerscience'}, {'code0': '98', 'code1': ('ATT', 'VA', 'NC'), 'code2': ('104', '105', '106', '31'), 'code4': 'computerscience'}, {'code0': '52', 'code1': 'NC', 'code2': '109', 'code3': ('610', '620', '682', '642', '621', '611'), 'code4': 'biology', 'code6': ('712', '479', '297', '639', '452', '172')}, {'code0': '52', 'code1': 'NC', 'code2': '109', 'code3': ('396', '340', '394', '393', '240'), 'code4': 'biology', 'code5': ('12', '18')}, {'code0': '52', 'code1': 'NC', 'code2': '109', 'code3': ('612', '790', '110'), 'code4': 'biology', 'code5': ('12', '16', '18', '19'), 'code6': ('285', '295', '236', '239', '269', '284', '237')}, {'code0': '52', 'code1': 'NC', 'code2': '109', 'code3': ('730', '320', '350', '379', '812', '374'), 'code4': 'biology', 'code5': ('12', '18', '19')}, {'code0': '40', 'code1': 'VA', 'code2': '11', 'code3': ('113', '174', '131', '115'), 'code5': ('11', '19', '31'), 'code6': ('164', '157', '388', '158')}, {'code0': '58', 'code1': 'CE', 'code2': '109', 'code3': ('423', '114'), 'code5': '31', 'code6': ('372', '238')}]
dictRules=defaultdict(<class 'list'>, {'rules1': [('code1', ('VA', 'HC', 'NIH', 'SAP', 'AUS', 'HOL', 'ATT', 'COL', 'UCL'))], 'rules12': [('code0', '40'), ('code3', '518'), ('code6', '594')], 'rules2': [('code0', '98'), ('code1', ('ATT', 'NC')), ('code2', ('103', '104', '105', '106', '31')), ('code3', '810'), ('code4', 'computerscience'), ('code0', '98'), ('code1', ('ATT', 'VA', 'NC')), ('code2', ('104', '105', '106', '31')), ('code4', 'computerscience'), ('code0', '52'), ('code1', 'NC'), ('code2', '109'), ('code3', ('610', '620', '682', '642', '621', '611')), ('code4', 'biology'), ('code6', ('712', '479', '297', '639', '452', '172')), ('code0', '52'), ('code1', 'NC'), ('code2', '109'), ('code3', ('396', '340', '394', '393', '240')), ('code4', 'biology'), ('code5', ('12', '18'))], 'rules3': [('code0', '52'), ('code1', 'NC'), ('code2', '109'), ('code3', ('612', '790', '110')), ('code4', 'biology'), ('code5', ('12', '16', '18', '19')), ('code6', ('285', '295', '236', '239', '269', '284', '237')), ('code0', '52'), ('code1', 'NC'), ('code2', '109'), ('code3', ('730', '320', '350', '379', '812', '374')), ('code4', 'biology'), ('code5', ('12', '18', '19'))], 'rules4': [('code0', '40'), ('code1', 'VA'), ('code2', '11'), ('code3', ('113', '174', '131', '115')), ('code5', ('11', '19', '31')), ('code6', ('164', '157', '388', '158'))], 'rules5': [('code0', '58'), ('code1', 'CE'), ('code2', '109'), ('code3', ('423', '114')), ('code5', '31'), ('code6', ('372', '238'))]})
-------------
dictDataRowsByCodeNname={'code0': {0: '5', 1: 'nan', 2: '98', 3: '98', 4: '', 5: '15', 6: '40', 7: '52', 8: '52', 9: '40', 10: '52', 11: '52', 12: '58'}, 'code1': {0: ('Agr', 'Serv'), 1: ('VA', 'HC', 'NIH', 'SAP', 'AUS', 'HOL', 'ATT', 'COL', 'UCL'), 2: ('ATT', 'NC'), 3: ('ATT', 'VA', 'NC'), 4: ('VA', 'HC', 'NIH', 'ATT', 'COL', 'UCL'), 5: 'Agr', 6: 'nan', 7: 'NC', 8: 'NC', 9: 'VA', 10: 'NC', 11: 'NC', 12: 'CE'}, 'code2': {0: 'nan', 1: 'nan', 2: ('103', '104', '105', '106', '31'), 3: ('104', '105'), 4: 'nan', 5: '5', 6: 'nan', 7: '109', 8: '109', 9: '11', 10: '109', 11: '109', 12: '109'}, 'code3': {0: '90', 1: 'nan', 2: '810', 3: '810', 4: 'nan', 5: '58', 6: '518', 7: ('610', '620', '682', '642', '621', '611'), 8: ('620', '682', '642', '611'), 9: ('113', '174', '131', '115'), 10: ('612', '790', '110'), 11: ('612', '110'), 12: ('423', '114')}, 'code4': {0: '1', 1: 'nan', 2: 'computerscience', 3: 'computerscience', 4: 'nan', 5: 'fishing', 6: 'nan', 7: 'biology', 8: 'biology', 9: 'nan', 10: 'biology', 11: 'biology', 12: 'nan'}, 'code5': {0: 'nan', 1: 'nan', 2: 'nan', 3: 'nan', 4: 'nan', 5: 'nan', 6: 'nan', 7: 'nan', 8: 'nan', 9: ('11', '19', '31'), 10: ('12', '16', '18', '19'), 11: ('12', '18', '19'), 12: '31'}, 'code6': {0: 'nan', 1: 'nan', 2: 'nan', 3: 'nan', 4: 'nan', 5: 'nan', 6: '594', 7: ('712', '479', '297', '639', '452', '172'), 8: ('712', '479', '297'), 9: ('164', '157', '388', '158'), 10: ('285', '295', '236', '239', '269', '284', '237'), 11: ('285', '295', '237'), 12: ('372', '238')}}
listDataRowsByRow=[{'code0': '5', 'code1': ('Agr', 'Serv'), 'code2': 'nan', 'code3': '90', 'code4': '1', 'code5': 'nan', 'code6': 'nan'}, {'code0': 'nan', 'code1': ('VA', 'HC', 'NIH', 'SAP', 'AUS', 'HOL', 'ATT', 'COL', 'UCL'), 'code2': 'nan', 'code3': 'nan', 'code4': 'nan', 'code5': 'nan', 'code6': 'nan'}, {'code0': '98', 'code1': ('ATT', 'NC'), 'code2': ('103', '104', '105', '106', '31'), 'code3': '810', 'code4': 'computerscience', 'code5': 'nan', 'code6': 'nan'}, {'code0': '98', 'code1': ('ATT', 'VA', 'NC'), 'code2': ('104', '105'), 'code3': '810', 'code4': 'computerscience', 'code5': 'nan', 'code6': 'nan'}, {'code0': '', 'code1': ('VA', 'HC', 'NIH', 'ATT', 'COL', 'UCL'), 'code2': 'nan', 'code3': 'nan', 'code4': 'nan', 'code5': 'nan', 'code6': 'nan'}, {'code0': '15', 'code1': 'Agr', 'code2': '5', 'code3': '58', 'code4': 'fishing', 'code5': 'nan', 'code6': 'nan'}, {'code0': '40', 'code1': 'nan', 'code2': 'nan', 'code3': '518', 'code4': 'nan', 'code5': 'nan', 'code6': '594'}, {'code0': '52', 'code1': 'NC', 'code2': '109', 'code3': ('610', '620', '682', '642', '621', '611'), 'code4': 'biology', 'code5': 'nan', 'code6': ('712', '479', '297', '639', '452', '172')}, {'code0': '52', 'code1': 'NC', 'code2': '109', 'code3': ('620', '682', '642', '611'), 'code4': 'biology', 'code5': 'nan', 'code6': ('712', '479', '297')}, {'code0': '40', 'code1': 'VA', 'code2': '11', 'code3': ('113', '174', '131', '115'), 'code4': 'nan', 'code5': ('11', '19', '31'), 'code6': ('164', '157', '388', '158')}, {'code0': '52', 'code1': 'NC', 'code2': '109', 'code3': ('612', '790', '110'), 'code4': 'biology', 'code5': ('12', '16', '18', '19'), 'code6': ('285', '295', '236', '239', '269', '284', '237')}, {'code0': '52', 'code1': 'NC', 'code2': '109', 'code3': ('612', '110'), 'code4': 'biology', 'code5': ('12', '18', '19'), 'code6': ('285', '295', '237')}, {'code0': '58', 'code1': 'CE', 'code2': '109', 'code3': ('423', '114'), 'code4': 'nan', 'code5': '31', 'code6': ('372', '238')}]
-------------
rules_desc_Column = [None, 'rules12', 'rules3', 'rules3', None, None, 'rules2', 'rules3', 'rules3', 'rules2', 'rules3', 'rules3', 'rules3']
isHit_Column = [False, True, True, True, False, False, True, True, True, True, True, True, True]
================================
code0 code1 ... isHit rules_desc
0 5 (Agr, Serv) ... False None
1 nan (VA, HC, NIH, SAP, AUS, HOL, ATT, COL, UCL) ... True rules12
2 98 (ATT, NC) ... True rules3
3 98 (ATT, VA, NC) ... True rules3
4 (VA, HC, NIH, ATT, COL, UCL) ... False None
5 15 Agr ... False None
6 40 nan ... True rules2
7 52 NC ... True rules3
8 52 NC ... True rules3
9 40 VA ... True rules2
10 52 NC ... True rules3
11 52 NC ... True rules3
12 58 CE ... True rules3
[13 rows x 9 columns]
================================
code0 code1 ... isHit rules_desc
0 5 (Agr, Serv) ... False None
1 nan (VA, HC, NIH, SAP, AUS, HOL, ATT, COL, UCL) ... True [rules1]
2 98 (ATT, NC) ... False None
3 98 (ATT, VA, NC) ... False None
4 (VA, HC, NIH, ATT, COL, UCL) ... False None
5 15 Agr ... False None
6 40 nan ... True [rules12]
7 52 NC ... False None
8 52 NC ... False None
9 40 VA ... True [rules4]
10 52 NC ... False None
11 52 NC ... False None
12 58 CE ... True [rules5]
[13 rows x 9 columns]
================================
P.S. The first final loop in the code above does NOT accumulate the hits providing a list of all rules which apply if there is a hit. In other words the search for hits is stopped after the first hit and first rule item which give a hit.
The second final loop tests all rule items and collects the rules which give hits in a list.
A:
Perhaps this will get you started. The only tricky thing here is the all function. What I'm saying here is, "for every key and value in this particular rule, if the value is found in the list of values for the corresponding key in our data row, and that's true for EVERY part of this rule, then it is a winner".
When you have nested data like this, pandas is not the right tool. You could probably make it work, but this is way easier.
A key point here is that you need to search the VALUES in your data dictionary. Right? You have {0:'5',2:'98'...}, but we don't care about 0 and 2. We only care about the strings.
for row in indf_dict:
for rno,rule in enumerate(rules_list):
print("New rule", rno)
match = all( val in row[key].values() for key,val in rule.items() if key in row)
if match:
print("Rule", rno, "matches")
Output:
New rule 0
Rule 0 matches
New rule 1
Rule 1 matches
New rule 2
Rule 2 matches
New rule 3
New rule 4
Rule 4 matches
New rule 5
New rule 6
Rule 6 matches
New rule 7
New rule 8
Rule 8 matches
New rule 9
Rule 9 matches
|
how to compare each cell of dataframe with list of dictionary in python?
|
I am trying to compare column values of each rows of dataframe with predefined list of dictionary, and do filtering. I tried pandas to compare column value by row-wise with list of dictionary, but it is not quite working, I got type error. I think I may need to convert dataframe into dictionary then compare it with list of dictionary then convert back to dataframe with new column added, but this still not giving my desired output. Does anyone suggest possible workaround on this? How can we do this easily in python
working minimal example
import pandas as pd
indf=pd.DataFrame.from_dict(indf_dict)
indf_lst=indf.to_dict(orient='records')
matches=[]
for each in rules_list:
for row in indf_lst:
if row in each:
matches.append(row)
I tried pandas approach to check column values of every rows in rules_list but the attempt is not successful. Now I tried to convert indf dataframe to dictionary and compare two dictionary, but I have type error as follow:
TypeError Traceback (most recent call last)
Input In [11], in <cell line: 12>()
12 for each in rules_list:
13 for row in indf_lst:
---> 14 if row in each:
15 matches.append(row)
TypeError: unhashable type: 'dict'
objective
I need to compare columns of every rows with list of dictionary rules_list, and add new column which shows found match or not. How this can be done in python?
updated desired output
here is my desired output where I want to add two new columns when columns values hit match with list of dictionary rules_list that I defined.
output={'code0':{0:('5'),1:'nan',2:('98'),3:('98'),4:'nan',5:('15'),6:('40'),7:('52'),8:('52'),9:('40'),10:('52'),11:('52'),12:('58')},'code1':{0:('Agr','Serv'),1:('VA','HC','NIH','SAP','AUS','HOL','ATT','COL','UCL'),2:('ATT','NC'),3:('ATT','VA','NC'),4:('VA','HC','NIH','ATT','COL','UCL'),5:('Agr'),6:'nan',7:('NC'),8:('NC'),9:('VA'),10:('NC'),11:('NC'),12:('CE')},'code2':{0:'nan',1:'nan',2:('103','104','105','106','31'),3:('104','105'),4:'nan',5:('5'),6:'nan',7:('109'),8:('109'),9:('11'),10:('109'),11:('109'),12:('109')},'code3':{0:('90'),1:'nan',2:('810'),3:('810'),4:'nan',5:('58'),6:('518'),7:('610','620','682','642','621','611'),8:('620','682','642','611'),9:('113','174','131','115'),10:('612','790','110'),11:('612','110'),12:('423','114')},'code4':{0:('1'),1:'nan',2:('computerscience'),3:('computerscience'),4:'nan',5:('fishing'),6:'nan',7:('biology'),8:('biology'),9:'nan',10:('biology'),11:('biology'),12:'nan'},'code5':{0:'nan',1:'nan',2:'nan',3:'nan',4:'nan',5:'nan',6:'nan',7:'nan',8:'nan',9:('11','19','31'),10:('12','16','18','19'),11:('12','18','19'),12:('31')},'code6':{0:'nan',1:'nan',2:'nan',3:'nan',4:'nan',5:'nan',6:('594'),7:('712','479','297','639','452','172'),8:('712','479','297'),9:('164','157','388','158'),10:('285','295','236','239','269','284','237'),11:('285','295','237'),12:('372','238')},'isHit':{0:False,1:True,2:True,3:True,4:True,5:False,6:True,7:True,8:True,9:True,10:True,11:True,12:True},'rules_desc':{0:'None',1:'rules1',2:'rules2',3:'rules2',4:'rules1',5:'None',6:'rules12',7:'rules21',8:'rules21',9:'rules4',10:'rules3',11:'rules3',12:'rules5'}}
outdf=pd.DataFrame.from_dict(output)
how can I achieve this sort of mapping value from each cell of dataframe to list of dictionary? should I handle this in pandas or convert them into list then compare it? any possible thoughts? Anything close to above desired output should be fine.
|
[
"The code below should do what you are asking for, but I haven't tested it yet if it actually really does what it should. I have put some effort in appropriate naming of the variables to make it easier to understand what the code does and how it works.\nIn the first step the code transforms the list with dictionaries for the rules into a list of tuples with code and code value for each of the rules with the purpose of making the final loop for checking if there is a hit easier to put together, understand, maintain and debug.\nIn the second step the code transforms the dictionary with data using pandas like it is done in code mentioned in the question.\nProbably there is also a pandas way of transforming the list of dictionaries in the first step, so if you read this and know how to accomplish this using pandas I would be glad to hear about that.\nMaybe there is a way to accomplish the entire task using pandas and two or three lines of code ... now with the variable naming and the provided code of the loops it would be easier for you who is reading this to come up with the code and provide maybe another and better answer.\nfrom pprint import pprint\nimport pandas as pd\nfrom collections import defaultdict\n# ----------------------------------------------------------------------\nrules_list=rules_dict=[{'code1':('VA','HC','NIH','SAP','AUS','HOL','ATT','COL','UCL'),'rules_desc':'rules1'},{'code0':('40'),'code3':('518'),'code6':('594'),'rules_desc':'rules12'},{'code0':('98'),'code1':('ATT','NC'),'code2':('103','104','105','106','31'),'code3':('810'),'code4':('computerscience'),'rules_desc':'rules2'},{'code0':('98'),'code1':('ATT','VA','NC'),'code2':('104','105','106','31'),'code4':('computerscience'),'rules_desc':'rules2'},{'code0':('52'),'code1':('NC'),'code2':('109'),'code3':('610','620','682','642','621','611'),'code4':('biology'),'code6':('712','479','297','639','452','172'),'rules_desc':'rules2'},{'code0':('52'),'code1':('NC'),'code2':('109'),'code3':('396','340','394','393','240'),'code4':('biology'),'code5':('12','18'),'rules_desc':'rules2'},{'code0':('52'),'code1':('NC'),'code2':('109'),'code3':('612','790','110'),'code4':('biology'),'code5':('12','16','18','19'),'code6':('285','295','236','239','269','284','237'),'rules_desc':'rules3'},{'code0':('52'),'code1':('NC'),'code2':('109'),'code3':('730','320','350','379','812','374'),'code4':('biology'),'code5':('12','18','19'),'rules_desc':'rules3'},{'code0':('40'),'code1':('VA'),'code2':('11'),'code3':('113','174','131','115'),'code5':('11','19','31'),'code6':('164','157','388','158'),'rules_desc':'rules4'},{'code0':('58'),'code1':('CE'),'code2':('109'),'code3':('423','114'),'code5':('31'),'code6':('372','238'),'rules_desc':'rules5'}]\n# codeNname : 'code1', 'code2', 'code3', ..., 'code6'\n# ruleNname : 'rules1', 'rules12', 'rules2', ..., 'rules5'\n# ruleDescrKey : 'rules_desc'\n# dictRulesSpec : dictionary { codeNname:value {1,N} ... , rulesDct_ruleKey:ruleNname }\n# dictCodes : dictionary { codeNname:value, codeNname:value, ... }\n# Rules : List [ dictRulesSpec, dictRulesSpec, ... ]\n# dictRules : { ruleNname:[codeNname, codeNnameValue], ... }\nRules = rules_list\nruleDescrKey = 'rules_desc'\ndictRules = defaultdict(list)\nfor dictRulesSpec in Rules:\n ruleNname = dictRulesSpec.pop(ruleDescrKey)\n # dictRulesSpec without ruleDescrKey item has only Codes as keys, so:\n dictCodes = dictRulesSpec \n for codeNname, codeNnameValue in dictCodes.items(): \n dictRules[ruleNname].append( (codeNname, codeNnameValue) ) \nprint(f'{Rules=}')\nprint(f'{dictRules=}')\nprint(' ------------- ')\n# ----------------------------------------------------------------------\nindf_dict={'code0':{0:('5'),1:'nan',2:('98'),3:('98'),4:'',5:('15'),6:('40'),7:('52'),8:('52'),9:('40'),10:('52'),11:('52'),12:('58')},'code1':{0:('Agr','Serv'),1:('VA','HC','NIH','SAP','AUS','HOL','ATT','COL','UCL'),2:('ATT','NC'),3:('ATT','VA','NC'),4:('VA','HC','NIH','ATT','COL','UCL'),5:('Agr'),6:'nan',7:('NC'),8:('NC'),9:('VA'),10:('NC'),11:('NC'),12:('CE')},'code2':{0:'nan',1:'nan',2:('103','104','105','106','31'),3:('104','105'),4:'nan',5:('5'),6:'nan',7:('109'),8:('109'),9:('11'),10:('109'),11:('109'),12:('109')},'code3':{0:('90'),1:'nan',2:('810'),3:('810'),4:'nan',5:('58'),6:('518'),7:('610','620','682','642','621','611'),8:('620','682','642','611'),9:('113','174','131','115'),10:('612','790','110'),11:('612','110'),12:('423','114')},'code4':{0:('1'),1:'nan',2:('computerscience'),3:('computerscience'),4:'nan',5:('fishing'),6:'nan',7:('biology'),8:('biology'),9:'nan',10:('biology'),11:('biology'),12:'nan'},'code5':{0:'nan',1:'nan',2:'nan',3:'nan',4:'nan',5:'nan',6:'nan',7:'nan',8:'nan',9:('11','19','31'),10:('12','16','18','19'),11:('12','18','19'),12:'31'},'code6':{0:'nan',1:'nan',2:'nan',3:'nan',4:'nan',5:'nan',6:'594',7:('712','479','297','639','452','172'),8:('712','479','297'),9:('164','157','388','158'),10:('285','295','236','239','269','284','237'),11:('285','295','237'),12:('372','238')}}\ndictDataRowsByCodeNname = indf_dict\ndf_dictDataRowsByCodeNname = pd.DataFrame.from_dict(dictDataRowsByCodeNname)\nprint(f'{dictDataRowsByCodeNname=}')\nlistDataRowsByRow = df_dictDataRowsByCodeNname.to_dict(orient='records')\nprint(f'{listDataRowsByRow=}')\nprint(' ------------- ')\nisHit_Column = []\nrules_desc_Column = []\n# The loop below tests for only one hit within the rule ...\nfor dctDataRow in listDataRowsByRow: \n isHit = False\n for ruleNname, listTuplesCodeNnameValue in dictRules.items():\n if isHit:\n break\n for codeNname, codeNnameValue in listTuplesCodeNnameValue:\n if isHit:\n break\n else:\n if dctDataRow[codeNname] == codeNnameValue: \n isHit = True\n bckpRuleNname = ruleNname\n break\n rules_desc_Column.append( bckpRuleNname if isHit else None)\n isHit_Column.append(isHit)\n\nprint(f'{rules_desc_Column = }')\nprint(f'{isHit_Column = }') \nprint('================================')\ndf_dictDataRowsByCodeNname['isHit'] = isHit_Column\ndf_dictDataRowsByCodeNname['rules_desc'] = rules_desc_Column\nprint(df_dictDataRowsByCodeNname)\nprint('================================')\n\nisHit_Column = []\nrules_desc_Column = []\n# The loop below tests for all hits within the rule and\n# lists all rules that apply in case of hits: \nfor dctDataRow in listDataRowsByRow: \n lstRulesWithHits = []\n for ruleNname, listTuplesCodeNnameValue in dictRules.items():\n ruleItemsWithHits = 0\n for codeNname, codeNnameValue in listTuplesCodeNnameValue:\n if dctDataRow[codeNname] == codeNnameValue: \n ruleItemsWithHits += 1\n if ruleItemsWithHits == len(listTuplesCodeNnameValue):\n lstRulesWithHits.append(ruleNname)\n isHit = bool(lstRulesWithHits)\n rules_desc_Column.append( lstRulesWithHits if isHit else None)\n isHit_Column.append(isHit)\ndf_dictDataRowsByCodeNname['isHit'] = isHit_Column\ndf_dictDataRowsByCodeNname['rules_desc'] = rules_desc_Column\nprint(df_dictDataRowsByCodeNname)\nprint('================================')\n\nwhich gives:\nRules=[{'code1': ('VA', 'HC', 'NIH', 'SAP', 'AUS', 'HOL', 'ATT', 'COL', 'UCL')}, {'code0': '40', 'code3': '518', 'code6': '594'}, {'code0': '98', 'code1': ('ATT', 'NC'), 'code2': ('103', '104', '105', '106', '31'), 'code3': '810', 'code4': 'computerscience'}, {'code0': '98', 'code1': ('ATT', 'VA', 'NC'), 'code2': ('104', '105', '106', '31'), 'code4': 'computerscience'}, {'code0': '52', 'code1': 'NC', 'code2': '109', 'code3': ('610', '620', '682', '642', '621', '611'), 'code4': 'biology', 'code6': ('712', '479', '297', '639', '452', '172')}, {'code0': '52', 'code1': 'NC', 'code2': '109', 'code3': ('396', '340', '394', '393', '240'), 'code4': 'biology', 'code5': ('12', '18')}, {'code0': '52', 'code1': 'NC', 'code2': '109', 'code3': ('612', '790', '110'), 'code4': 'biology', 'code5': ('12', '16', '18', '19'), 'code6': ('285', '295', '236', '239', '269', '284', '237')}, {'code0': '52', 'code1': 'NC', 'code2': '109', 'code3': ('730', '320', '350', '379', '812', '374'), 'code4': 'biology', 'code5': ('12', '18', '19')}, {'code0': '40', 'code1': 'VA', 'code2': '11', 'code3': ('113', '174', '131', '115'), 'code5': ('11', '19', '31'), 'code6': ('164', '157', '388', '158')}, {'code0': '58', 'code1': 'CE', 'code2': '109', 'code3': ('423', '114'), 'code5': '31', 'code6': ('372', '238')}]\ndictRules=defaultdict(<class 'list'>, {'rules1': [('code1', ('VA', 'HC', 'NIH', 'SAP', 'AUS', 'HOL', 'ATT', 'COL', 'UCL'))], 'rules12': [('code0', '40'), ('code3', '518'), ('code6', '594')], 'rules2': [('code0', '98'), ('code1', ('ATT', 'NC')), ('code2', ('103', '104', '105', '106', '31')), ('code3', '810'), ('code4', 'computerscience'), ('code0', '98'), ('code1', ('ATT', 'VA', 'NC')), ('code2', ('104', '105', '106', '31')), ('code4', 'computerscience'), ('code0', '52'), ('code1', 'NC'), ('code2', '109'), ('code3', ('610', '620', '682', '642', '621', '611')), ('code4', 'biology'), ('code6', ('712', '479', '297', '639', '452', '172')), ('code0', '52'), ('code1', 'NC'), ('code2', '109'), ('code3', ('396', '340', '394', '393', '240')), ('code4', 'biology'), ('code5', ('12', '18'))], 'rules3': [('code0', '52'), ('code1', 'NC'), ('code2', '109'), ('code3', ('612', '790', '110')), ('code4', 'biology'), ('code5', ('12', '16', '18', '19')), ('code6', ('285', '295', '236', '239', '269', '284', '237')), ('code0', '52'), ('code1', 'NC'), ('code2', '109'), ('code3', ('730', '320', '350', '379', '812', '374')), ('code4', 'biology'), ('code5', ('12', '18', '19'))], 'rules4': [('code0', '40'), ('code1', 'VA'), ('code2', '11'), ('code3', ('113', '174', '131', '115')), ('code5', ('11', '19', '31')), ('code6', ('164', '157', '388', '158'))], 'rules5': [('code0', '58'), ('code1', 'CE'), ('code2', '109'), ('code3', ('423', '114')), ('code5', '31'), ('code6', ('372', '238'))]})\n ------------- \ndictDataRowsByCodeNname={'code0': {0: '5', 1: 'nan', 2: '98', 3: '98', 4: '', 5: '15', 6: '40', 7: '52', 8: '52', 9: '40', 10: '52', 11: '52', 12: '58'}, 'code1': {0: ('Agr', 'Serv'), 1: ('VA', 'HC', 'NIH', 'SAP', 'AUS', 'HOL', 'ATT', 'COL', 'UCL'), 2: ('ATT', 'NC'), 3: ('ATT', 'VA', 'NC'), 4: ('VA', 'HC', 'NIH', 'ATT', 'COL', 'UCL'), 5: 'Agr', 6: 'nan', 7: 'NC', 8: 'NC', 9: 'VA', 10: 'NC', 11: 'NC', 12: 'CE'}, 'code2': {0: 'nan', 1: 'nan', 2: ('103', '104', '105', '106', '31'), 3: ('104', '105'), 4: 'nan', 5: '5', 6: 'nan', 7: '109', 8: '109', 9: '11', 10: '109', 11: '109', 12: '109'}, 'code3': {0: '90', 1: 'nan', 2: '810', 3: '810', 4: 'nan', 5: '58', 6: '518', 7: ('610', '620', '682', '642', '621', '611'), 8: ('620', '682', '642', '611'), 9: ('113', '174', '131', '115'), 10: ('612', '790', '110'), 11: ('612', '110'), 12: ('423', '114')}, 'code4': {0: '1', 1: 'nan', 2: 'computerscience', 3: 'computerscience', 4: 'nan', 5: 'fishing', 6: 'nan', 7: 'biology', 8: 'biology', 9: 'nan', 10: 'biology', 11: 'biology', 12: 'nan'}, 'code5': {0: 'nan', 1: 'nan', 2: 'nan', 3: 'nan', 4: 'nan', 5: 'nan', 6: 'nan', 7: 'nan', 8: 'nan', 9: ('11', '19', '31'), 10: ('12', '16', '18', '19'), 11: ('12', '18', '19'), 12: '31'}, 'code6': {0: 'nan', 1: 'nan', 2: 'nan', 3: 'nan', 4: 'nan', 5: 'nan', 6: '594', 7: ('712', '479', '297', '639', '452', '172'), 8: ('712', '479', '297'), 9: ('164', '157', '388', '158'), 10: ('285', '295', '236', '239', '269', '284', '237'), 11: ('285', '295', '237'), 12: ('372', '238')}}\nlistDataRowsByRow=[{'code0': '5', 'code1': ('Agr', 'Serv'), 'code2': 'nan', 'code3': '90', 'code4': '1', 'code5': 'nan', 'code6': 'nan'}, {'code0': 'nan', 'code1': ('VA', 'HC', 'NIH', 'SAP', 'AUS', 'HOL', 'ATT', 'COL', 'UCL'), 'code2': 'nan', 'code3': 'nan', 'code4': 'nan', 'code5': 'nan', 'code6': 'nan'}, {'code0': '98', 'code1': ('ATT', 'NC'), 'code2': ('103', '104', '105', '106', '31'), 'code3': '810', 'code4': 'computerscience', 'code5': 'nan', 'code6': 'nan'}, {'code0': '98', 'code1': ('ATT', 'VA', 'NC'), 'code2': ('104', '105'), 'code3': '810', 'code4': 'computerscience', 'code5': 'nan', 'code6': 'nan'}, {'code0': '', 'code1': ('VA', 'HC', 'NIH', 'ATT', 'COL', 'UCL'), 'code2': 'nan', 'code3': 'nan', 'code4': 'nan', 'code5': 'nan', 'code6': 'nan'}, {'code0': '15', 'code1': 'Agr', 'code2': '5', 'code3': '58', 'code4': 'fishing', 'code5': 'nan', 'code6': 'nan'}, {'code0': '40', 'code1': 'nan', 'code2': 'nan', 'code3': '518', 'code4': 'nan', 'code5': 'nan', 'code6': '594'}, {'code0': '52', 'code1': 'NC', 'code2': '109', 'code3': ('610', '620', '682', '642', '621', '611'), 'code4': 'biology', 'code5': 'nan', 'code6': ('712', '479', '297', '639', '452', '172')}, {'code0': '52', 'code1': 'NC', 'code2': '109', 'code3': ('620', '682', '642', '611'), 'code4': 'biology', 'code5': 'nan', 'code6': ('712', '479', '297')}, {'code0': '40', 'code1': 'VA', 'code2': '11', 'code3': ('113', '174', '131', '115'), 'code4': 'nan', 'code5': ('11', '19', '31'), 'code6': ('164', '157', '388', '158')}, {'code0': '52', 'code1': 'NC', 'code2': '109', 'code3': ('612', '790', '110'), 'code4': 'biology', 'code5': ('12', '16', '18', '19'), 'code6': ('285', '295', '236', '239', '269', '284', '237')}, {'code0': '52', 'code1': 'NC', 'code2': '109', 'code3': ('612', '110'), 'code4': 'biology', 'code5': ('12', '18', '19'), 'code6': ('285', '295', '237')}, {'code0': '58', 'code1': 'CE', 'code2': '109', 'code3': ('423', '114'), 'code4': 'nan', 'code5': '31', 'code6': ('372', '238')}]\n ------------- \nrules_desc_Column = [None, 'rules12', 'rules3', 'rules3', None, None, 'rules2', 'rules3', 'rules3', 'rules2', 'rules3', 'rules3', 'rules3']\nisHit_Column = [False, True, True, True, False, False, True, True, True, True, True, True, True]\n================================\n code0 code1 ... isHit rules_desc\n0 5 (Agr, Serv) ... False None\n1 nan (VA, HC, NIH, SAP, AUS, HOL, ATT, COL, UCL) ... True rules12\n2 98 (ATT, NC) ... True rules3\n3 98 (ATT, VA, NC) ... True rules3\n4 (VA, HC, NIH, ATT, COL, UCL) ... False None\n5 15 Agr ... False None\n6 40 nan ... True rules2\n7 52 NC ... True rules3\n8 52 NC ... True rules3\n9 40 VA ... True rules2\n10 52 NC ... True rules3\n11 52 NC ... True rules3\n12 58 CE ... True rules3\n\n[13 rows x 9 columns]\n================================\n code0 code1 ... isHit rules_desc\n0 5 (Agr, Serv) ... False None\n1 nan (VA, HC, NIH, SAP, AUS, HOL, ATT, COL, UCL) ... True [rules1]\n2 98 (ATT, NC) ... False None\n3 98 (ATT, VA, NC) ... False None\n4 (VA, HC, NIH, ATT, COL, UCL) ... False None\n5 15 Agr ... False None\n6 40 nan ... True [rules12]\n7 52 NC ... False None\n8 52 NC ... False None\n9 40 VA ... True [rules4]\n10 52 NC ... False None\n11 52 NC ... False None\n12 58 CE ... True [rules5]\n\n[13 rows x 9 columns]\n================================\n\nP.S. The first final loop in the code above does NOT accumulate the hits providing a list of all rules which apply if there is a hit. In other words the search for hits is stopped after the first hit and first rule item which give a hit.\nThe second final loop tests all rule items and collects the rules which give hits in a list.\n",
"Perhaps this will get you started. The only tricky thing here is the all function. What I'm saying here is, \"for every key and value in this particular rule, if the value is found in the list of values for the corresponding key in our data row, and that's true for EVERY part of this rule, then it is a winner\".\nWhen you have nested data like this, pandas is not the right tool. You could probably make it work, but this is way easier.\nA key point here is that you need to search the VALUES in your data dictionary. Right? You have {0:'5',2:'98'...}, but we don't care about 0 and 2. We only care about the strings.\nfor row in indf_dict:\n for rno,rule in enumerate(rules_list):\n print(\"New rule\", rno)\n match = all( val in row[key].values() for key,val in rule.items() if key in row)\n if match:\n print(\"Rule\", rno, \"matches\")\n\nOutput:\nNew rule 0\nRule 0 matches\nNew rule 1\nRule 1 matches\nNew rule 2\nRule 2 matches\nNew rule 3\nNew rule 4\nRule 4 matches\nNew rule 5\nNew rule 6\nRule 6 matches\nNew rule 7\nNew rule 8\nRule 8 matches\nNew rule 9\nRule 9 matches\n\n"
] |
[
2,
1
] |
[] |
[] |
[
"dataframe",
"pandas",
"python"
] |
stackoverflow_0074525516_dataframe_pandas_python.txt
|
Q:
Python-Custom decimal precision printing
I want my integer variable to be rounded to 4 decimal places. A number like 3.345679 should be represented as 3.3457.Additionally, the value zero must be represented as 0 and not any other representation.(e.g., -0.0, 0.0, 0.00000). Additionally, I do not want to add extra 0s to floating point numbers. For example, 3.9 should be represented as 3.9, not as 3.9000
A:
You'll need to examine the number before you print it. You could write a function for determining how many zeros would appear if you rounded to 4 decimal places:
def getZeroCount(num):
# this check avoids infinite loop
if num == 0:
return 4
x = num
tens = 0
while x % 10 == 0:
tens += 1
x /= 10
return tens
Then format the string based on this value:
a = 3.345679
zeros = getZeroCount(a)
stringToPrint = '{:.{w}f}'.format(a, w=4-zeros)
print(stringToPrint)
A:
You can use function round() with a number of decimal places.
examples = [
0,
3.345679,
3.9,
3.0,
3.00001,
3
]
decimal_places = 4
for example in examples:
print(round(example, decimal_places))
The code above outputs:
0
3.3457
3.9
3.0
3.0
3
The only potential problem here is that floating point numbers are printed with at least one symbol after the dot - so there's "3.0" where "3" could be.
A:
def custom_decimal(x):
if x == 0:
s = '0'
else:
s = f'{x:0.4f}'.rstrip('0')
return s
>>> for x in ( 3.345679, -0.0, 0.0, 0.00000, 3.9):
print(custom_decimal(x))
3.3457
0
0
0
3.9
|
Python-Custom decimal precision printing
|
I want my integer variable to be rounded to 4 decimal places. A number like 3.345679 should be represented as 3.3457.Additionally, the value zero must be represented as 0 and not any other representation.(e.g., -0.0, 0.0, 0.00000). Additionally, I do not want to add extra 0s to floating point numbers. For example, 3.9 should be represented as 3.9, not as 3.9000
|
[
"You'll need to examine the number before you print it. You could write a function for determining how many zeros would appear if you rounded to 4 decimal places:\ndef getZeroCount(num):\n # this check avoids infinite loop\n if num == 0:\n return 4\n\n x = num\n tens = 0\n while x % 10 == 0:\n tens += 1\n x /= 10\n\n return tens\n\nThen format the string based on this value:\na = 3.345679\nzeros = getZeroCount(a)\nstringToPrint = '{:.{w}f}'.format(a, w=4-zeros)\nprint(stringToPrint)\n\n",
"You can use function round() with a number of decimal places.\nexamples = [\n 0,\n 3.345679,\n 3.9,\n 3.0,\n 3.00001,\n 3\n]\n\ndecimal_places = 4\n\nfor example in examples:\n print(round(example, decimal_places))\n\nThe code above outputs:\n0\n3.3457\n3.9\n3.0\n3.0\n3\n\nThe only potential problem here is that floating point numbers are printed with at least one symbol after the dot - so there's \"3.0\" where \"3\" could be.\n",
"def custom_decimal(x):\n if x == 0:\n s = '0'\n else:\n s = f'{x:0.4f}'.rstrip('0')\n return s\n\n>>> for x in ( 3.345679, -0.0, 0.0, 0.00000, 3.9):\n print(custom_decimal(x))\n\n3.3457\n0\n0\n0\n3.9\n\n"
] |
[
0,
0,
0
] |
[] |
[] |
[
"format",
"precision",
"printing",
"python"
] |
stackoverflow_0074525555_format_precision_printing_python.txt
|
Q:
Unzip file content hosted in s3 to multiple cloudfront url through a single lambda function
Is there any specific way to unzip single file contents from s3 to multiple cloudfront urls by triggering lambda once.
Lets say in there is a zip file contains multiple jpg/ png files already uploaded to s3. Intention is to run lambda function only once to unzip all its file content and make them available in multiple cloudfront urls.
in s3 bucket
archive.zip
a.jpg
b.jpg
c.jpg
through cloudfront
https://1232.cloudfront.net/a.jpg
https://1232.cloudfront.net/b.jpg
https://1232.cloudfront.net/c.jpg
I am looking for a solution such that lambda function trigger function calls whenever a s3 upload happens and make all files available in the zip through cloudfront multiple urls.
A:
Hello Prathap Parameswar,
I think you can resolve your problem like this:
First you need to exact your zip file
Seconds you upload them again to S3.
This is lambda python function:
import json
import boto3
from io import BytesIO
import zipfile
def lambda_handler(event, context):
# TODO implement
s3_resource = boto3.resource('s3')
source_bucket = 'upload-zip-folder'
target_bucket = 'upload-extracted-folder'
my_bucket = s3_resource.Bucket(source_bucket)
for file in my_bucket.objects.all():
if(str(file.key).endswith('.zip')):
zip_obj = s3_resource.Object(bucket_name=source_bucket, key=file.key)
buffer = BytesIO(zip_obj.get()["Body"].read())
z = zipfile.ZipFile(buffer)
for filename in z.namelist():
file_info = z.getinfo(filename)
try:
response = s3_resource.meta.client.upload_fileobj(
z.open(filename),
Bucket=target_bucket,
Key=f'{filename}'
)
except Exception as e:
print(e)
else:
print(file.key+ ' is not a zip file.')
Hope this can help you
|
Unzip file content hosted in s3 to multiple cloudfront url through a single lambda function
|
Is there any specific way to unzip single file contents from s3 to multiple cloudfront urls by triggering lambda once.
Lets say in there is a zip file contains multiple jpg/ png files already uploaded to s3. Intention is to run lambda function only once to unzip all its file content and make them available in multiple cloudfront urls.
in s3 bucket
archive.zip
a.jpg
b.jpg
c.jpg
through cloudfront
https://1232.cloudfront.net/a.jpg
https://1232.cloudfront.net/b.jpg
https://1232.cloudfront.net/c.jpg
I am looking for a solution such that lambda function trigger function calls whenever a s3 upload happens and make all files available in the zip through cloudfront multiple urls.
|
[
"Hello Prathap Parameswar,\nI think you can resolve your problem like this:\n\nFirst you need to exact your zip file\nSeconds you upload them again to S3.\n\nThis is lambda python function:\nimport json\nimport boto3\nfrom io import BytesIO\nimport zipfile\n\ndef lambda_handler(event, context):\n # TODO implement\n \n s3_resource = boto3.resource('s3')\n source_bucket = 'upload-zip-folder'\n target_bucket = 'upload-extracted-folder'\n\n my_bucket = s3_resource.Bucket(source_bucket)\n\n for file in my_bucket.objects.all():\n if(str(file.key).endswith('.zip')):\n zip_obj = s3_resource.Object(bucket_name=source_bucket, key=file.key)\n buffer = BytesIO(zip_obj.get()[\"Body\"].read())\n \n z = zipfile.ZipFile(buffer)\n for filename in z.namelist():\n file_info = z.getinfo(filename)\n try:\n response = s3_resource.meta.client.upload_fileobj(\n z.open(filename),\n Bucket=target_bucket,\n Key=f'{filename}'\n )\n except Exception as e:\n print(e)\n else:\n print(file.key+ ' is not a zip file.')\n\nHope this can help you\n"
] |
[
0
] |
[] |
[] |
[
"amazon_s3",
"amazon_web_services",
"aws_lambda",
"node.js",
"python"
] |
stackoverflow_0074526898_amazon_s3_amazon_web_services_aws_lambda_node.js_python.txt
|
Q:
Delete specific duplicate values in the same row
en
ko
Fetishistic transvestism(F65.1)
물품음란성 의상도착증(F65.1)
Obsessive-compulsive disorder(F42.-)
강박장애(F42.-)
Conduct disorders(F91.-)
행동장애(F91.-)
Schizophrenia(F20.-)
조현병(F20.-)
I want to remove duplicate values in the same row in this data frame.
en
ko
Fetishistic transvestism
물품음란성 의상도착증
Obsessive-compulsive disorder
강박장애
Conduct disorders
행동장애
Schizophrenia
조현병
A:
Probably you can use difflib:
import difflib
import pandas as pd
def remove_common_postfix(row: pd.Series, column1: str, column2: str):
"""
Remove common postfix of 2 columns in 1 row
:param row: a dataframe row
:param column1: column name 1
:param column2: column name 2
:return: a dataframe row
"""
a = row[column1]
b = row[column2]
sequence_matcher = difflib.SequenceMatcher(None, a, b)
match = sequence_matcher.find_longest_match(0, len(a), 0, len(b))
row[column1], row[column2] = a[:match.a], b[:match.b]
return row
if __name__ == "__main__":
values = [["Fetishistic transvestism(F65.1)", "물품음란성 의상도착증(F65.1)"],
["Obsessive-compulsive disorder(F42.-)", "강박장애(F42.-)"]]
df = pd.DataFrame(values, columns=["en", "ko"])
print(df)
df = df.apply(lambda row: remove_common_postfix(row, "en", "ko"), axis=1)
print(df)
The output seems good:
|
Delete specific duplicate values in the same row
|
en
ko
Fetishistic transvestism(F65.1)
물품음란성 의상도착증(F65.1)
Obsessive-compulsive disorder(F42.-)
강박장애(F42.-)
Conduct disorders(F91.-)
행동장애(F91.-)
Schizophrenia(F20.-)
조현병(F20.-)
I want to remove duplicate values in the same row in this data frame.
en
ko
Fetishistic transvestism
물품음란성 의상도착증
Obsessive-compulsive disorder
강박장애
Conduct disorders
행동장애
Schizophrenia
조현병
|
[
"Probably you can use difflib:\nimport difflib\nimport pandas as pd\n\ndef remove_common_postfix(row: pd.Series, column1: str, column2: str):\n \"\"\"\n Remove common postfix of 2 columns in 1 row\n :param row: a dataframe row\n :param column1: column name 1\n :param column2: column name 2\n :return: a dataframe row\n \"\"\"\n a = row[column1]\n b = row[column2]\n sequence_matcher = difflib.SequenceMatcher(None, a, b)\n\n match = sequence_matcher.find_longest_match(0, len(a), 0, len(b))\n row[column1], row[column2] = a[:match.a], b[:match.b]\n\n return row\n\n\nif __name__ == \"__main__\":\n values = [[\"Fetishistic transvestism(F65.1)\", \"물품음란성 의상도착증(F65.1)\"],\n [\"Obsessive-compulsive disorder(F42.-)\", \"강박장애(F42.-)\"]]\n\n df = pd.DataFrame(values, columns=[\"en\", \"ko\"])\n print(df)\n df = df.apply(lambda row: remove_common_postfix(row, \"en\", \"ko\"), axis=1)\n print(df)\n\nThe output seems good:\n\n"
] |
[
0
] |
[] |
[] |
[
"dataframe",
"pandas",
"python"
] |
stackoverflow_0074526440_dataframe_pandas_python.txt
|
Q:
Need to drop the oldest record (can be multiple "oldest records")
My dataset looks like this:
ID
DATE
111
29/07/2022
111
30/03/2022
111
30/03/2022
111
30/03/2022
111
02/08/2022
222
08/11/2022
222
07/07/2022
222
11/11/2022
222
10/07/2022
I need to drop the oldest record per ID but keeping all the others, the problem is that I may have various "oldest records" with the same date. I'm looking for something like this:
ID
DATE
111
29/07/2022
111
02/08/2022
222
08/11/2022
222
11/11/2022
222
10/07/2022
I tried sorting and dropping duplicates, which almost worked in every case (ID=222) but when it comes to ID=111, with various "oldest records" to drop, it didn't function as I expected.
A:
You can try this:
def discard_min(g):
return g[g > g.min()]
newdf = df.groupby('ID')['DATE'].apply(discard_min).droplevel(1).reset_index()
>>> newdf
ID DATE
0 111 2022-07-29
1 111 2022-08-02
2 222 2022-11-08
3 222 2022-11-11
4 222 2022-07-10
Reproducible setup for the above:
df = pd.DataFrame(
[[111, '29/07/2022'], [111, '30/03/2022'], [111, '30/03/2022'],
[111, '30/03/2022'], [111, '02/08/2022'], [222, '08/11/2022'],
[222, '07/07/2022'], [222, '11/11/2022'], [222, '10/07/2022']],
columns=['ID', 'DATE'])
df['DATE'] = pd.to_datetime(df['DATE'], infer_datetime_format=True)
|
Need to drop the oldest record (can be multiple "oldest records")
|
My dataset looks like this:
ID
DATE
111
29/07/2022
111
30/03/2022
111
30/03/2022
111
30/03/2022
111
02/08/2022
222
08/11/2022
222
07/07/2022
222
11/11/2022
222
10/07/2022
I need to drop the oldest record per ID but keeping all the others, the problem is that I may have various "oldest records" with the same date. I'm looking for something like this:
ID
DATE
111
29/07/2022
111
02/08/2022
222
08/11/2022
222
11/11/2022
222
10/07/2022
I tried sorting and dropping duplicates, which almost worked in every case (ID=222) but when it comes to ID=111, with various "oldest records" to drop, it didn't function as I expected.
|
[
"You can try this:\ndef discard_min(g):\n return g[g > g.min()]\n\nnewdf = df.groupby('ID')['DATE'].apply(discard_min).droplevel(1).reset_index()\n>>> newdf\n ID DATE\n0 111 2022-07-29\n1 111 2022-08-02\n2 222 2022-11-08\n3 222 2022-11-11\n4 222 2022-07-10\n\nReproducible setup for the above:\ndf = pd.DataFrame(\n [[111, '29/07/2022'], [111, '30/03/2022'], [111, '30/03/2022'],\n [111, '30/03/2022'], [111, '02/08/2022'], [222, '08/11/2022'],\n [222, '07/07/2022'], [222, '11/11/2022'], [222, '10/07/2022']],\n columns=['ID', 'DATE'])\ndf['DATE'] = pd.to_datetime(df['DATE'], infer_datetime_format=True)\n\n"
] |
[
2
] |
[] |
[] |
[
"date",
"numpy",
"pandas",
"python",
"sorting"
] |
stackoverflow_0074526324_date_numpy_pandas_python_sorting.txt
|
Q:
I'm having trouble cleaning up this Bad code script. I found a few errors already but I'm currently stuck on this part
I need to correct this script on a bad code. There is 5 total errors. Here's what I've corrected so far. I'm stuck at defining an array in line 3. I've gone through and tried to correct this line by line but have had no luck. Would greatly appreciate a push in the right direction to get this code fixed.
from array import array
students=array()
def getString(prompt, field):
valid=False
while valid==False:
myString=input(prompt)
if (len(myString)>0):
valid=True
else:
print("The student's " + field + " cannot be empty. Please try again.")
return myString
def getFloat(promp, field):
while True:
try:
fNum=float(getString(prompt, field))
break
except ValueError:
print("That is not a valid number for " + field + ", please try again")
return fNum
def addStudent():
first=getString("Enter the student's first name: ", "first name")
last=getString("Enter the student's last name: ", "last name")
major=getString("Enter the student's major: ", "major")
gpa=getFloat("Enter the student's GPA: ", "GPA")
students.append({"first":first,"last":last,"major":major,"gpa":gpa})
def displayStudents():
print("\nCollege Roster:")
print("*************************************************************************")
if (len(students)==0):
print("There are no students to display.")
else:
print("First Name".ljust(20," ")+"Last Name".ljust(30," ")+"Major".ljust(15," ")+"GPA".ljust(6," "))
for i in range(len(students)):
print(students[i]['first'].ljust(20, " "), end="")
print(students[i]['last'].ljust(30, " "), end="")
print(students[i]['major'].ljust(15, " "), end="")
print(str(students[i]['gpa']).ljust(6, " "))
print("*************************************************************************")
def Main():
keepGoing=true
menu="""
*************************************************************************
College Roster System
*************************************************************************
Main Menu:
a) Enter a new Student
b) View all Students
c) Clear Students List
d) Exit
*************************************************************************
Choose an option: """
while keepGoing:
choice=input(menu)
if choice!="":
if choice.lower()=="a":
addStudent()
elif choice.lower()=="b":
displayStudents()
elif choice.lower()=="c":
students.clear()
print("\nThe list of students is cleared.")
elif choice.lower()=="d":
keepGoing=False
else:
print("\nThat is not a valid selection. Please try again.\n")
else:
print("\nYour selection cannot be empty. Please try again.\n")
print("\nOkay, goodbye!!!")
if __name__=="__BC02.py__":
main()
I'm stuck trying to define the array. I know there is also additional errors, but I can't get pass this part.
A:
Here is a version of your code that compiles and seems to run correctly:
students=[]
def getString(prompt, field):
valid=False
while valid==False:
myString=input(prompt)
if (len(myString)>0):
valid=True
else:
print("The student's " + field + " cannot be empty. Please try again.")
return myString
def getFloat(prompt, field):
while True:
try:
fNum=float(getString(prompt, field))
break
except ValueError:
print("That is not a valid number for " + field + ", please try again")
return fNum
def addStudent():
first=getString("Enter the student's first name: ", "first name")
last=getString("Enter the student's last name: ", "last name")
major=getString("Enter the student's major: ", "major")
gpa=getFloat("Enter the student's GPA: ", "GPA")
students.append({"first":first,"last":last,"major":major,"gpa":gpa})
def displayStudents():
print("\nCollege Roster:")
print("*************************************************************************")
if (len(students)==0):
print("There are no students to display.")
else:
print("First Name".ljust(20," ")+"Last Name".ljust(30," ")+"Major".ljust(15," ")+"GPA".ljust(6," "))
for i in range(len(students)):
print(students[i]['first'].ljust(20, " "), end="")
print(students[i]['last'].ljust(30, " "), end="")
print(students[i]['major'].ljust(15, " "), end="")
print(str(students[i]['gpa']).ljust(6, " "))
print("*************************************************************************")
def main():
keepGoing=True
menu="""
*************************************************************************
College Roster System
*************************************************************************
Main Menu:
a) Enter a new Student
b) View all Students
c) Clear Students List
d) Exit
*************************************************************************
Choose an option: """
while keepGoing:
choice=input(menu)
if choice!="":
if choice.lower()=="a":
addStudent()
elif choice.lower()=="b":
displayStudents()
elif choice.lower()=="c":
students.clear()
print("\nThe list of students is cleared.")
elif choice.lower()=="d":
keepGoing=False
else:
print("\nThat is not a valid selection. Please try again.\n")
else:
print("\nYour selection cannot be empty. Please try again.\n")
print("\nOkay, goodbye!!!")
if __name__=="__main__":
main()
Most of the errors were basic typos. For the first error on line 3, I think it's best to use a standard Python list to store the data for each student. A list is created using [].
|
I'm having trouble cleaning up this Bad code script. I found a few errors already but I'm currently stuck on this part
|
I need to correct this script on a bad code. There is 5 total errors. Here's what I've corrected so far. I'm stuck at defining an array in line 3. I've gone through and tried to correct this line by line but have had no luck. Would greatly appreciate a push in the right direction to get this code fixed.
from array import array
students=array()
def getString(prompt, field):
valid=False
while valid==False:
myString=input(prompt)
if (len(myString)>0):
valid=True
else:
print("The student's " + field + " cannot be empty. Please try again.")
return myString
def getFloat(promp, field):
while True:
try:
fNum=float(getString(prompt, field))
break
except ValueError:
print("That is not a valid number for " + field + ", please try again")
return fNum
def addStudent():
first=getString("Enter the student's first name: ", "first name")
last=getString("Enter the student's last name: ", "last name")
major=getString("Enter the student's major: ", "major")
gpa=getFloat("Enter the student's GPA: ", "GPA")
students.append({"first":first,"last":last,"major":major,"gpa":gpa})
def displayStudents():
print("\nCollege Roster:")
print("*************************************************************************")
if (len(students)==0):
print("There are no students to display.")
else:
print("First Name".ljust(20," ")+"Last Name".ljust(30," ")+"Major".ljust(15," ")+"GPA".ljust(6," "))
for i in range(len(students)):
print(students[i]['first'].ljust(20, " "), end="")
print(students[i]['last'].ljust(30, " "), end="")
print(students[i]['major'].ljust(15, " "), end="")
print(str(students[i]['gpa']).ljust(6, " "))
print("*************************************************************************")
def Main():
keepGoing=true
menu="""
*************************************************************************
College Roster System
*************************************************************************
Main Menu:
a) Enter a new Student
b) View all Students
c) Clear Students List
d) Exit
*************************************************************************
Choose an option: """
while keepGoing:
choice=input(menu)
if choice!="":
if choice.lower()=="a":
addStudent()
elif choice.lower()=="b":
displayStudents()
elif choice.lower()=="c":
students.clear()
print("\nThe list of students is cleared.")
elif choice.lower()=="d":
keepGoing=False
else:
print("\nThat is not a valid selection. Please try again.\n")
else:
print("\nYour selection cannot be empty. Please try again.\n")
print("\nOkay, goodbye!!!")
if __name__=="__BC02.py__":
main()
I'm stuck trying to define the array. I know there is also additional errors, but I can't get pass this part.
|
[
"Here is a version of your code that compiles and seems to run correctly:\nstudents=[]\n\ndef getString(prompt, field):\n valid=False\n while valid==False:\n myString=input(prompt)\n if (len(myString)>0):\n valid=True\n else:\n print(\"The student's \" + field + \" cannot be empty. Please try again.\")\n return myString\n\ndef getFloat(prompt, field):\n while True:\n try:\n fNum=float(getString(prompt, field))\n break\n except ValueError:\n print(\"That is not a valid number for \" + field + \", please try again\")\n return fNum\n\ndef addStudent():\n first=getString(\"Enter the student's first name: \", \"first name\")\n last=getString(\"Enter the student's last name: \", \"last name\")\n major=getString(\"Enter the student's major: \", \"major\")\n gpa=getFloat(\"Enter the student's GPA: \", \"GPA\")\n students.append({\"first\":first,\"last\":last,\"major\":major,\"gpa\":gpa})\n\ndef displayStudents():\n print(\"\\nCollege Roster:\")\n print(\"*************************************************************************\")\n if (len(students)==0):\n print(\"There are no students to display.\")\n else:\n print(\"First Name\".ljust(20,\" \")+\"Last Name\".ljust(30,\" \")+\"Major\".ljust(15,\" \")+\"GPA\".ljust(6,\" \"))\n for i in range(len(students)):\n print(students[i]['first'].ljust(20, \" \"), end=\"\")\n print(students[i]['last'].ljust(30, \" \"), end=\"\")\n print(students[i]['major'].ljust(15, \" \"), end=\"\")\n print(str(students[i]['gpa']).ljust(6, \" \"))\n print(\"*************************************************************************\")\n\ndef main():\n keepGoing=True\n menu=\"\"\"\n*************************************************************************\nCollege Roster System\n*************************************************************************\nMain Menu:\na) Enter a new Student\nb) View all Students\nc) Clear Students List\nd) Exit\n*************************************************************************\nChoose an option: \"\"\"\n while keepGoing:\n choice=input(menu)\n if choice!=\"\":\n if choice.lower()==\"a\":\n addStudent()\n elif choice.lower()==\"b\":\n displayStudents()\n elif choice.lower()==\"c\":\n students.clear()\n print(\"\\nThe list of students is cleared.\")\n elif choice.lower()==\"d\":\n keepGoing=False\n else:\n print(\"\\nThat is not a valid selection. Please try again.\\n\")\n else:\n print(\"\\nYour selection cannot be empty. Please try again.\\n\")\n print(\"\\nOkay, goodbye!!!\")\n\nif __name__==\"__main__\":\n main()\n\nMost of the errors were basic typos. For the first error on line 3, I think it's best to use a standard Python list to store the data for each student. A list is created using [].\n"
] |
[
0
] |
[] |
[] |
[
"arrays",
"python"
] |
stackoverflow_0074527047_arrays_python.txt
|
Q:
python my selenium "webdriver.Remote" not work? .It's a real headache
Why does my "webdriver.Remote" not work?
from selenium import webdriver
options = webdriver.ChromeOptions()
driver = webdriver.Remote(
command_executor='http://127.0.0.1:4444/wd/hub',
options=options
)
driver.get("http://www.google.com")
driver.quit()
enter image description here
I tried running "webdriver.Chrome" locally directly and it was successful
options = webdriver.ChromeOptions()
# options.add_argument("--headless")
# options.add_argument("--disable-gpu")
driver = webdriver.Chrome(options=options)
driver.get("http://www.google.com")
A:
I found that he kept Starting "Starting ChromeDriver 100.0.4896.60" while running, so I found another "ChromeDriver "in the selenium-server.jar sibling directory.How stupid of me.
|
python my selenium "webdriver.Remote" not work? .It's a real headache
|
Why does my "webdriver.Remote" not work?
from selenium import webdriver
options = webdriver.ChromeOptions()
driver = webdriver.Remote(
command_executor='http://127.0.0.1:4444/wd/hub',
options=options
)
driver.get("http://www.google.com")
driver.quit()
enter image description here
I tried running "webdriver.Chrome" locally directly and it was successful
options = webdriver.ChromeOptions()
# options.add_argument("--headless")
# options.add_argument("--disable-gpu")
driver = webdriver.Chrome(options=options)
driver.get("http://www.google.com")
|
[
"I found that he kept Starting \"Starting ChromeDriver 100.0.4896.60\" while running, so I found another \"ChromeDriver \"in the selenium-server.jar sibling directory.How stupid of me.\n"
] |
[
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0074517428_python.txt
|
Q:
model.fit gives me Graph execution error. How do I solve?
I am new to image processing and machine learning in python. I have been trying to execute a model in google colab using inceptionv3 but i am stuck at fitting the model.
r = model.fit(
training_set,
validation_data=test_set,
epochs=10,
steps_per_epoch=len(training_set),
validation_steps=len(test_set)
)
it is showing me the below errors
Epoch 1/10
---------------------------------------------------------------------------
UnimplementedError Traceback (most recent call last)
<ipython-input-24-c27d8fba63ce> in <module>()
6 epochs=10,
7 steps_per_epoch=len(training_set),
----> 8 validation_steps=len(test_set)
9 )
1 frames
/usr/local/lib/python3.7/dist-packages/tensorflow/python/eager/execute.py in quick_execute(op_name, num_outputs, inputs, attrs, ctx, name)
53 ctx.ensure_initialized()
54 tensors = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name,
---> 55 inputs, attrs, num_outputs)
56 except core._NotOkStatusException as e:
57 if name is not None:
UnimplementedError: Graph execution error:
Detected at node 'model/conv2d/Conv2D' defined at (most recent call last):
File "/usr/lib/python3.7/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "/usr/lib/python3.7/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py", line 16, in <module>
app.launch_new_instance()
File "/usr/local/lib/python3.7/dist-packages/traitlets/config/application.py", line 846, in launch_instance
app.start()
File "/usr/local/lib/python3.7/dist-packages/ipykernel/kernelapp.py", line 499, in start
self.io_loop.start()
File "/usr/local/lib/python3.7/dist-packages/tornado/platform/asyncio.py", line 132, in start
self.asyncio_loop.run_forever()
File "/usr/lib/python3.7/asyncio/base_events.py", line 541, in run_forever
self._run_once()
File "/usr/lib/python3.7/asyncio/base_events.py", line 1786, in _run_once
handle._run()
File "/usr/lib/python3.7/asyncio/events.py", line 88, in _run
self._context.run(self._callback, *self._args)
File "/usr/local/lib/python3.7/dist-packages/tornado/platform/asyncio.py", line 122, in _handle_events
handler_func(fileobj, events)
File "/usr/local/lib/python3.7/dist-packages/tornado/stack_context.py", line 300, in null_wrapper
return fn(*args, **kwargs)
File "/usr/local/lib/python3.7/dist-packages/zmq/eventloop/zmqstream.py", line 577, in _handle_events
self._handle_recv()
File "/usr/local/lib/python3.7/dist-packages/zmq/eventloop/zmqstream.py", line 606, in _handle_recv
self._run_callback(callback, msg)
File "/usr/local/lib/python3.7/dist-packages/zmq/eventloop/zmqstream.py", line 556, in _run_callback
callback(*args, **kwargs)
File "/usr/local/lib/python3.7/dist-packages/tornado/stack_context.py", line 300, in null_wrapper
return fn(*args, **kwargs)
File "/usr/local/lib/python3.7/dist-packages/ipykernel/kernelbase.py", line 283, in dispatcher
return self.dispatch_shell(stream, msg)
File "/usr/local/lib/python3.7/dist-packages/ipykernel/kernelbase.py", line 233, in dispatch_shell
handler(stream, idents, msg)
File "/usr/local/lib/python3.7/dist-packages/ipykernel/kernelbase.py", line 399, in execute_request
user_expressions, allow_stdin)
File "/usr/local/lib/python3.7/dist-packages/ipykernel/ipkernel.py", line 208, in do_execute
res = shell.run_cell(code, store_history=store_history, silent=silent)
File "/usr/local/lib/python3.7/dist-packages/ipykernel/zmqshell.py", line 537, in run_cell
return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)
File "/usr/local/lib/python3.7/dist-packages/IPython/core/interactiveshell.py", line 2718, in run_cell
interactivity=interactivity, compiler=compiler, result=result)
File "/usr/local/lib/python3.7/dist-packages/IPython/core/interactiveshell.py", line 2822, in run_ast_nodes
if self.run_code(code, result):
File "/usr/local/lib/python3.7/dist-packages/IPython/core/interactiveshell.py", line 2882, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-20-8cba7706098f>", line 12, in <module>
validation_steps=validation_data
File "/usr/local/lib/python3.7/dist-packages/keras/utils/traceback_utils.py", line 64, in error_handler
return fn(*args, **kwargs)
File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1409, in fit
tmp_logs = self.train_function(iterator)
File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1051, in train_function
return step_function(self, iterator)
File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1040, in step_function
outputs = model.distribute_strategy.run(run_step, args=(data,))
File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1030, in run_step
outputs = model.train_step(data)
File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 889, in train_step
y_pred = self(x, training=True)
File "/usr/local/lib/python3.7/dist-packages/keras/utils/traceback_utils.py", line 64, in error_handler
return fn(*args, **kwargs)
File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 490, in __call__
return super().__call__(*args, **kwargs)
File "/usr/local/lib/python3.7/dist-packages/keras/utils/traceback_utils.py", line 64, in error_handler
return fn(*args, **kwargs)
File "/usr/local/lib/python3.7/dist-packages/keras/engine/base_layer.py", line 1014, in __call__
outputs = call_fn(inputs, *args, **kwargs)
File "/usr/local/lib/python3.7/dist-packages/keras/utils/traceback_utils.py", line 92, in error_handler
return fn(*args, **kwargs)
File "/usr/local/lib/python3.7/dist-packages/keras/engine/functional.py", line 459, in call
inputs, training=training, mask=mask)
File "/usr/local/lib/python3.7/dist-packages/keras/engine/functional.py", line 596, in _run_internal_graph
outputs = node.layer(*args, **kwargs)
File "/usr/local/lib/python3.7/dist-packages/keras/utils/traceback_utils.py", line 64, in error_handler
return fn(*args, **kwargs)
File "/usr/local/lib/python3.7/dist-packages/keras/engine/base_layer.py", line 1014, in __call__
outputs = call_fn(inputs, *args, **kwargs)
File "/usr/local/lib/python3.7/dist-packages/keras/utils/traceback_utils.py", line 92, in error_handler
return fn(*args, **kwargs)
File "/usr/local/lib/python3.7/dist-packages/keras/layers/convolutional/base_conv.py", line 250, in call
outputs = self.convolution_op(inputs, self.kernel)
File "/usr/local/lib/python3.7/dist-packages/keras/layers/convolutional/base_conv.py", line 232, in convolution_op
name=self.__class__.__name__)
Node: 'model/conv2d/Conv2D'
DNN library is not found.
[[{{node model/conv2d/Conv2D}}]] [Op:__inference_train_function_12299]
the whole code is in my git repository: https://github.com/Aditya757/MyRepository.git
the image of the dataset is here: https://i.stack.imgur.com/jWaJ8.png
A:
Try to truncate to max_length=64 when tokenization. It worked in my case when training the text classification model.
The error appears when I set max_lenght to 128 or above.
|
model.fit gives me Graph execution error. How do I solve?
|
I am new to image processing and machine learning in python. I have been trying to execute a model in google colab using inceptionv3 but i am stuck at fitting the model.
r = model.fit(
training_set,
validation_data=test_set,
epochs=10,
steps_per_epoch=len(training_set),
validation_steps=len(test_set)
)
it is showing me the below errors
Epoch 1/10
---------------------------------------------------------------------------
UnimplementedError Traceback (most recent call last)
<ipython-input-24-c27d8fba63ce> in <module>()
6 epochs=10,
7 steps_per_epoch=len(training_set),
----> 8 validation_steps=len(test_set)
9 )
1 frames
/usr/local/lib/python3.7/dist-packages/tensorflow/python/eager/execute.py in quick_execute(op_name, num_outputs, inputs, attrs, ctx, name)
53 ctx.ensure_initialized()
54 tensors = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name,
---> 55 inputs, attrs, num_outputs)
56 except core._NotOkStatusException as e:
57 if name is not None:
UnimplementedError: Graph execution error:
Detected at node 'model/conv2d/Conv2D' defined at (most recent call last):
File "/usr/lib/python3.7/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "/usr/lib/python3.7/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py", line 16, in <module>
app.launch_new_instance()
File "/usr/local/lib/python3.7/dist-packages/traitlets/config/application.py", line 846, in launch_instance
app.start()
File "/usr/local/lib/python3.7/dist-packages/ipykernel/kernelapp.py", line 499, in start
self.io_loop.start()
File "/usr/local/lib/python3.7/dist-packages/tornado/platform/asyncio.py", line 132, in start
self.asyncio_loop.run_forever()
File "/usr/lib/python3.7/asyncio/base_events.py", line 541, in run_forever
self._run_once()
File "/usr/lib/python3.7/asyncio/base_events.py", line 1786, in _run_once
handle._run()
File "/usr/lib/python3.7/asyncio/events.py", line 88, in _run
self._context.run(self._callback, *self._args)
File "/usr/local/lib/python3.7/dist-packages/tornado/platform/asyncio.py", line 122, in _handle_events
handler_func(fileobj, events)
File "/usr/local/lib/python3.7/dist-packages/tornado/stack_context.py", line 300, in null_wrapper
return fn(*args, **kwargs)
File "/usr/local/lib/python3.7/dist-packages/zmq/eventloop/zmqstream.py", line 577, in _handle_events
self._handle_recv()
File "/usr/local/lib/python3.7/dist-packages/zmq/eventloop/zmqstream.py", line 606, in _handle_recv
self._run_callback(callback, msg)
File "/usr/local/lib/python3.7/dist-packages/zmq/eventloop/zmqstream.py", line 556, in _run_callback
callback(*args, **kwargs)
File "/usr/local/lib/python3.7/dist-packages/tornado/stack_context.py", line 300, in null_wrapper
return fn(*args, **kwargs)
File "/usr/local/lib/python3.7/dist-packages/ipykernel/kernelbase.py", line 283, in dispatcher
return self.dispatch_shell(stream, msg)
File "/usr/local/lib/python3.7/dist-packages/ipykernel/kernelbase.py", line 233, in dispatch_shell
handler(stream, idents, msg)
File "/usr/local/lib/python3.7/dist-packages/ipykernel/kernelbase.py", line 399, in execute_request
user_expressions, allow_stdin)
File "/usr/local/lib/python3.7/dist-packages/ipykernel/ipkernel.py", line 208, in do_execute
res = shell.run_cell(code, store_history=store_history, silent=silent)
File "/usr/local/lib/python3.7/dist-packages/ipykernel/zmqshell.py", line 537, in run_cell
return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)
File "/usr/local/lib/python3.7/dist-packages/IPython/core/interactiveshell.py", line 2718, in run_cell
interactivity=interactivity, compiler=compiler, result=result)
File "/usr/local/lib/python3.7/dist-packages/IPython/core/interactiveshell.py", line 2822, in run_ast_nodes
if self.run_code(code, result):
File "/usr/local/lib/python3.7/dist-packages/IPython/core/interactiveshell.py", line 2882, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-20-8cba7706098f>", line 12, in <module>
validation_steps=validation_data
File "/usr/local/lib/python3.7/dist-packages/keras/utils/traceback_utils.py", line 64, in error_handler
return fn(*args, **kwargs)
File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1409, in fit
tmp_logs = self.train_function(iterator)
File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1051, in train_function
return step_function(self, iterator)
File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1040, in step_function
outputs = model.distribute_strategy.run(run_step, args=(data,))
File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1030, in run_step
outputs = model.train_step(data)
File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 889, in train_step
y_pred = self(x, training=True)
File "/usr/local/lib/python3.7/dist-packages/keras/utils/traceback_utils.py", line 64, in error_handler
return fn(*args, **kwargs)
File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 490, in __call__
return super().__call__(*args, **kwargs)
File "/usr/local/lib/python3.7/dist-packages/keras/utils/traceback_utils.py", line 64, in error_handler
return fn(*args, **kwargs)
File "/usr/local/lib/python3.7/dist-packages/keras/engine/base_layer.py", line 1014, in __call__
outputs = call_fn(inputs, *args, **kwargs)
File "/usr/local/lib/python3.7/dist-packages/keras/utils/traceback_utils.py", line 92, in error_handler
return fn(*args, **kwargs)
File "/usr/local/lib/python3.7/dist-packages/keras/engine/functional.py", line 459, in call
inputs, training=training, mask=mask)
File "/usr/local/lib/python3.7/dist-packages/keras/engine/functional.py", line 596, in _run_internal_graph
outputs = node.layer(*args, **kwargs)
File "/usr/local/lib/python3.7/dist-packages/keras/utils/traceback_utils.py", line 64, in error_handler
return fn(*args, **kwargs)
File "/usr/local/lib/python3.7/dist-packages/keras/engine/base_layer.py", line 1014, in __call__
outputs = call_fn(inputs, *args, **kwargs)
File "/usr/local/lib/python3.7/dist-packages/keras/utils/traceback_utils.py", line 92, in error_handler
return fn(*args, **kwargs)
File "/usr/local/lib/python3.7/dist-packages/keras/layers/convolutional/base_conv.py", line 250, in call
outputs = self.convolution_op(inputs, self.kernel)
File "/usr/local/lib/python3.7/dist-packages/keras/layers/convolutional/base_conv.py", line 232, in convolution_op
name=self.__class__.__name__)
Node: 'model/conv2d/Conv2D'
DNN library is not found.
[[{{node model/conv2d/Conv2D}}]] [Op:__inference_train_function_12299]
the whole code is in my git repository: https://github.com/Aditya757/MyRepository.git
the image of the dataset is here: https://i.stack.imgur.com/jWaJ8.png
|
[
"Try to truncate to max_length=64 when tokenization. It worked in my case when training the text classification model.\nThe error appears when I set max_lenght to 128 or above.\n"
] |
[
0
] |
[] |
[] |
[
"machine_learning",
"python",
"tensorflow"
] |
stackoverflow_0072545450_machine_learning_python_tensorflow.txt
|
Q:
ModuleNotFoundError: No module named 'yaml' and AttributeError: module 'yaml' has no attribute 'load'?
I have a script that does import yaml and then uses yaml.load and yaml.Loader
I previously installed yaml months ago using pip3 install yaml, and that worked for another script
Now, running another script was saying ModuleNotFoundError: No module named 'yaml' again (but ipython works when doing import yaml as well as from yaml import load). Tried installing using brew but now I get a new error AttributeError: module 'yaml' has no attribute 'load'.
Why is this? And how can I fix whatever's going on? I don't have any files named 'yaml' at my script level
|
ModuleNotFoundError: No module named 'yaml' and AttributeError: module 'yaml' has no attribute 'load'?
|
I have a script that does import yaml and then uses yaml.load and yaml.Loader
I previously installed yaml months ago using pip3 install yaml, and that worked for another script
Now, running another script was saying ModuleNotFoundError: No module named 'yaml' again (but ipython works when doing import yaml as well as from yaml import load). Tried installing using brew but now I get a new error AttributeError: module 'yaml' has no attribute 'load'.
Why is this? And how can I fix whatever's going on? I don't have any files named 'yaml' at my script level
|
[] |
[] |
[
"python3 -m pip install pyyaml worked. I should rly learn pip/installing\n"
] |
[
-2
] |
[
"homebrew",
"pip",
"python",
"yaml"
] |
stackoverflow_0074526364_homebrew_pip_python_yaml.txt
|
Q:
How to display the output form a function on a label in Tkinter
I'm new to coding and im sure that my code is not very efficient but I just want to take the output from a variable and display it in a window. So far when you run it, it just displays the output in the console. I want it do to that and display it on the window. Hope that all makes sense.
from tkinter import *
root = Tk()
root.geometry("500x500")
def get_input():
year = boxYear.get()
p1 = (int(year) // 12)
p2 = (int(year) % 12)
p3 = (p2 // 4)
p4 = (p1 + p2 + p3)
days = ['wednesday', 'thursday', 'friday', 'saturday', 'sunday', 'monday', 'tuesday']
p5 = (p4 // 7)
if p4 >= 7 and p4 <= 14:
p6 = (p4 - 7)
elif p4 >= 7 and p4 > 14:
p6 = (p4 - 14)
else:
p6 = (p4)
if p6 == 7:
p6 = 0
print(days[int(p6)])
# in between these two sections there is a bunch of code that's just math. its not important.
# it just spits out a variable which is one of the days of the week
#the variable "final" is that day of the week
final = int(last)
DOTW = (days[int(final)])
outputlabel = Label(topframe, textvariable=DOTW, font=('Arial 20 bold italic'))
outputlabel.grid(row=7, columnspan=2, pady=10)
#GUI stuff
topframe = Frame(root)
topframe.pack()
bottomframe = Frame(root)
bottomframe.pack(side=BOTTOM)
printbutton = Button(topframe, text="Run Algorithm", command=lambda: get_input())
printbutton.grid(row= 5, columnspan=2, pady=30)
boxYear = Entry(topframe)
boxMonth = Entry(topframe)
boxDay = Entry(topframe)
boxYear.grid(row=1, column=1, padx=10, pady=10)
boxMonth.grid(row=2, column=1, padx=10, pady=10)
boxDay.grid(row=3, column=1, padx=10, pady=10)
root.mainloop()
I tried to add code to get it to display it in the window but it just doesn't do anything and I can't find a solution anywhere.
A:
For starters, your get_input function isn't returning a value. You should replace the print() statement with the value you'd like this function to return:
def get_input():
... # code omitted for brevity
return days[int(p6)] # return the value you want from the `days` list
That said, if you want this function to update a UI element like a Label, the preferred way to handle that is as follows:
root = Tk()
# you were close - the Label's textvariable should be an instance of StringVar
dotw_var = StringVar(root)
# if you want 'dotw_var' (and consequently, 'outputlabel') to have a default value,
# declare dotw_var as follows: dotw_var(root, 'default value string')
outputlabel = Label(topframe, textvariable=dotw_var, font=('Arial 20 bold italic'))
outputlabel.grid(row=7, columnspan=2, pady=10)
def get_input():
... # code omitted for brevity
dotw_var.set(days[int(p6)]) # set the value to update outputlabel
# note that you don't need this function to return anything after all!
Whenever dotw_var is set(), the text of outputlabel will update automatically
A:
You have used textvariable=DOTW for the outputlabel, as DOTW is a string, an internal tkinter variable will be created with empty string initially, so the label shows a empty string.
You should use text=DOTW instead. Also it is better to create outputlabel once outside the function and update its text inside the function.
Below is the required changes:
def get_input():
...
final = int(last)
DOTW = days[final] # don't need to call int() on final as it is already an integer
outputlabel.config(text=DOTW) # update outputlabel
...
# create outputlabel initially
outputlabel = Label(topframe, font=('Arial 20 bold italic'))
outputlabel.grid(row=7, columnspan=2, pady=10)
root.mainloop()
|
How to display the output form a function on a label in Tkinter
|
I'm new to coding and im sure that my code is not very efficient but I just want to take the output from a variable and display it in a window. So far when you run it, it just displays the output in the console. I want it do to that and display it on the window. Hope that all makes sense.
from tkinter import *
root = Tk()
root.geometry("500x500")
def get_input():
year = boxYear.get()
p1 = (int(year) // 12)
p2 = (int(year) % 12)
p3 = (p2 // 4)
p4 = (p1 + p2 + p3)
days = ['wednesday', 'thursday', 'friday', 'saturday', 'sunday', 'monday', 'tuesday']
p5 = (p4 // 7)
if p4 >= 7 and p4 <= 14:
p6 = (p4 - 7)
elif p4 >= 7 and p4 > 14:
p6 = (p4 - 14)
else:
p6 = (p4)
if p6 == 7:
p6 = 0
print(days[int(p6)])
# in between these two sections there is a bunch of code that's just math. its not important.
# it just spits out a variable which is one of the days of the week
#the variable "final" is that day of the week
final = int(last)
DOTW = (days[int(final)])
outputlabel = Label(topframe, textvariable=DOTW, font=('Arial 20 bold italic'))
outputlabel.grid(row=7, columnspan=2, pady=10)
#GUI stuff
topframe = Frame(root)
topframe.pack()
bottomframe = Frame(root)
bottomframe.pack(side=BOTTOM)
printbutton = Button(topframe, text="Run Algorithm", command=lambda: get_input())
printbutton.grid(row= 5, columnspan=2, pady=30)
boxYear = Entry(topframe)
boxMonth = Entry(topframe)
boxDay = Entry(topframe)
boxYear.grid(row=1, column=1, padx=10, pady=10)
boxMonth.grid(row=2, column=1, padx=10, pady=10)
boxDay.grid(row=3, column=1, padx=10, pady=10)
root.mainloop()
I tried to add code to get it to display it in the window but it just doesn't do anything and I can't find a solution anywhere.
|
[
"For starters, your get_input function isn't returning a value. You should replace the print() statement with the value you'd like this function to return:\ndef get_input():\n ... # code omitted for brevity\n return days[int(p6)] # return the value you want from the `days` list\n\nThat said, if you want this function to update a UI element like a Label, the preferred way to handle that is as follows:\nroot = Tk()\n# you were close - the Label's textvariable should be an instance of StringVar\ndotw_var = StringVar(root)\n# if you want 'dotw_var' (and consequently, 'outputlabel') to have a default value,\n# declare dotw_var as follows: dotw_var(root, 'default value string')\n\noutputlabel = Label(topframe, textvariable=dotw_var, font=('Arial 20 bold italic'))\noutputlabel.grid(row=7, columnspan=2, pady=10)\n\n\ndef get_input():\n ... # code omitted for brevity\n dotw_var.set(days[int(p6)]) # set the value to update outputlabel\n # note that you don't need this function to return anything after all!\n\nWhenever dotw_var is set(), the text of outputlabel will update automatically\n",
"You have used textvariable=DOTW for the outputlabel, as DOTW is a string, an internal tkinter variable will be created with empty string initially, so the label shows a empty string.\nYou should use text=DOTW instead. Also it is better to create outputlabel once outside the function and update its text inside the function.\nBelow is the required changes:\ndef get_input():\n ...\n final = int(last)\n DOTW = days[final] # don't need to call int() on final as it is already an integer\n outputlabel.config(text=DOTW) # update outputlabel\n\n...\n\n# create outputlabel initially\noutputlabel = Label(topframe, font=('Arial 20 bold italic'))\noutputlabel.grid(row=7, columnspan=2, pady=10)\n\nroot.mainloop()\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"label",
"python",
"tkinter",
"tkinter_layout"
] |
stackoverflow_0074504091_label_python_tkinter_tkinter_layout.txt
|
Q:
Handle event batch in eventhub triggered azure function
Am writing a event publisher and consumer. From the publisher am trying to send events as batch using eventhub_client.send_batch(batch)
Now in the consumer side am receiving event and using
if e.get_body() is not None:
try:
str = e.get_body().decode("utf-8")
msg = ast.literal_eval(str)
props = e.metadata.get('Properties')
do_something(msg, props)
except Exception as e:
print(e)
I have 2 issues
will i receive a batch OR single event when i ran consumer (publisher published a batch with 10 events)
Am i handling all the events in consumer? am not sure weather my consumer process all the 10 events.
Can somebody clarify the above questions and help me to refine the consumer code if any better way to handle events (am not sure of ast.literal_eval(str) function why has to be used as i got a sample code from some site)
A:
It completely depends on how you are receiving events, i.e., if you are using receive or receive_batch method on the EventHubConsumerClient class.
Based on your code, I suppose you are using receive, so your handler would process events one-by-one.
Check the official samples for receive and receive_batch for more information on how you can leverage either one.
|
Handle event batch in eventhub triggered azure function
|
Am writing a event publisher and consumer. From the publisher am trying to send events as batch using eventhub_client.send_batch(batch)
Now in the consumer side am receiving event and using
if e.get_body() is not None:
try:
str = e.get_body().decode("utf-8")
msg = ast.literal_eval(str)
props = e.metadata.get('Properties')
do_something(msg, props)
except Exception as e:
print(e)
I have 2 issues
will i receive a batch OR single event when i ran consumer (publisher published a batch with 10 events)
Am i handling all the events in consumer? am not sure weather my consumer process all the 10 events.
Can somebody clarify the above questions and help me to refine the consumer code if any better way to handle events (am not sure of ast.literal_eval(str) function why has to be used as i got a sample code from some site)
|
[
"It completely depends on how you are receiving events, i.e., if you are using receive or receive_batch method on the EventHubConsumerClient class.\nBased on your code, I suppose you are using receive, so your handler would process events one-by-one.\nCheck the official samples for receive and receive_batch for more information on how you can leverage either one.\n"
] |
[
0
] |
[] |
[] |
[
"azure_functions",
"python",
"python_3.x"
] |
stackoverflow_0074206420_azure_functions_python_python_3.x.txt
|
Q:
Checking if proxy is used or not
I want to use proxy with pithon web requests. To test, if my request is working or not I send request to jsonip.com. In the response it returns my real ip instead of the proxy. Also The website providing proxy also says "no activity". I want to ask is, am I connecting to proxy correctly. Here the code.
import time, requests, random
from requests.auth import HTTPProxyAuth
auth = HTTPProxyAuth("muyjgovw", "mtpysgrb3nkj")
def reqs():
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:107.0) Gecko/20100101 Firefox/107.0',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.5',
# 'Accept-Encoding': 'gzip, deflate, br',
'Referer': 'https://www.google.com/',
'Connection': 'keep-alive',
'Upgrade-Insecure-Requests': '1',
'Sec-Fetch-Dest': 'document',
'Sec-Fetch-Mode': 'navigate',
'Sec-Fetch-Site': 'cross-site',
'Sec-Fetch-User': '?1',
}
prox = [{"http": "http://64.137.58.19:6265"}]
proxies = random.choice(prox)
response = requests.get('https://jsonip.com/', headers=headers, proxies=proxies)
print(response.status_code)
print(response.json())
reqs()
The screeenshot of website showing no activity is[![enter image description here][1]][1]
Please tell me weather my code is not working or proxy is not working. Thanks
[1]: https://i.stack.imgur.com/XywSc.png
A:
Your have to do this to include the proxy
import time, requests, random
from requests.auth import HTTPProxyAuth
auth = HTTPProxyAuth("muyjgovw", "mtpysgrb3nkj")
def reqs():
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:107.0) Gecko/20100101 Firefox/107.0',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.5',
# 'Accept-Encoding': 'gzip, deflate, br',
'Referer': 'https://www.google.com/',
'Connection': 'keep-alive',
'Upgrade-Insecure-Requests': '1',
'Sec-Fetch-Dest': 'document',
'Sec-Fetch-Mode': 'navigate',
'Sec-Fetch-Site': 'cross-site',
'Sec-Fetch-User': '?1',
}
prox = [{"http": "http://64.137.58.19:6265",
"https": "http://64.137.58.19:6265" }]
proxies = random.choice(prox)
response = requests.get('https://jsonip.com/', headers=headers, proxies=proxies)
print(response.status_code)
print(response.json())
reqs()
|
Checking if proxy is used or not
|
I want to use proxy with pithon web requests. To test, if my request is working or not I send request to jsonip.com. In the response it returns my real ip instead of the proxy. Also The website providing proxy also says "no activity". I want to ask is, am I connecting to proxy correctly. Here the code.
import time, requests, random
from requests.auth import HTTPProxyAuth
auth = HTTPProxyAuth("muyjgovw", "mtpysgrb3nkj")
def reqs():
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:107.0) Gecko/20100101 Firefox/107.0',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.5',
# 'Accept-Encoding': 'gzip, deflate, br',
'Referer': 'https://www.google.com/',
'Connection': 'keep-alive',
'Upgrade-Insecure-Requests': '1',
'Sec-Fetch-Dest': 'document',
'Sec-Fetch-Mode': 'navigate',
'Sec-Fetch-Site': 'cross-site',
'Sec-Fetch-User': '?1',
}
prox = [{"http": "http://64.137.58.19:6265"}]
proxies = random.choice(prox)
response = requests.get('https://jsonip.com/', headers=headers, proxies=proxies)
print(response.status_code)
print(response.json())
reqs()
The screeenshot of website showing no activity is[![enter image description here][1]][1]
Please tell me weather my code is not working or proxy is not working. Thanks
[1]: https://i.stack.imgur.com/XywSc.png
|
[
"Your have to do this to include the proxy\nimport time, requests, random\nfrom requests.auth import HTTPProxyAuth\nauth = HTTPProxyAuth(\"muyjgovw\", \"mtpysgrb3nkj\")\n\ndef reqs(): \n headers = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:107.0) Gecko/20100101 Firefox/107.0',\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',\n 'Accept-Language': 'en-US,en;q=0.5',\n # 'Accept-Encoding': 'gzip, deflate, br',\n 'Referer': 'https://www.google.com/',\n 'Connection': 'keep-alive',\n 'Upgrade-Insecure-Requests': '1',\n 'Sec-Fetch-Dest': 'document',\n 'Sec-Fetch-Mode': 'navigate',\n 'Sec-Fetch-Site': 'cross-site',\n 'Sec-Fetch-User': '?1',\n }\n prox = [{\"http\": \"http://64.137.58.19:6265\",\n \"https\": \"http://64.137.58.19:6265\" }]\n proxies = random.choice(prox)\n response = requests.get('https://jsonip.com/', headers=headers, proxies=proxies)\n print(response.status_code)\n print(response.json())\nreqs()\n\n"
] |
[
1
] |
[] |
[] |
[
"proxy",
"python",
"python_requests"
] |
stackoverflow_0074522314_proxy_python_python_requests.txt
|
Q:
How to retrieve SQL result column value using column name in Python?
Is there a way to retrieve SQL result column value using column name instead of column index in Python? I'm using Python 3 with mySQL. The syntax I'm looking for is pretty much like the Java construct:
Object id = rs.get("CUSTOMER_ID");
I've a table with quite a number of columns and it is a real pain to constantly work out the index for each column I need to access. Furthermore the index is making my code hard to read.
Thanks!
A:
The MySQLdb module has a DictCursor:
Use it like this (taken from Writing MySQL Scripts with Python DB-API):
cursor = conn.cursor(MySQLdb.cursors.DictCursor)
cursor.execute("SELECT name, category FROM animal")
result_set = cursor.fetchall()
for row in result_set:
print "%s, %s" % (row["name"], row["category"])
edit: According to user1305650 this works for pymysql as well.
A:
This post is old but may come up via searching.
Now you can use mysql.connector to retrive a dictionary as shown here:
https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursordict.html
Here is the example on the mysql site:
cnx = mysql.connector.connect(database='world')
cursor = cnx.cursor(dictionary=True)
cursor.execute("SELECT * FROM country WHERE Continent = 'Europe'")
print("Countries in Europe:")
for row in cursor:
print("* {Name}".format(Name=row['Name']))
A:
you must look for something called " dictionary in cursor "
i'm using mysql connector and i have to add this parameter to my cursor , so i can use my columns names instead of index's
db = mysql.connector.connect(
host=db_info['mysql_host'],
user=db_info['mysql_user'],
passwd=db_info['mysql_password'],
database=db_info['mysql_db'])
cur = db.cursor()
cur = db.cursor( buffered=True , dictionary=True)
A:
import pymysql
# Open database connection
db = pymysql.connect("localhost","root","","gkdemo1")
# prepare a cursor object using cursor() method
cursor = db.cursor()
# execute SQL query using execute() method.
cursor.execute("SELECT * from user")
# Get the fields name (only once!)
field_name = [field[0] for field in cursor.description]
# Fetch a single row using fetchone() method.
values = cursor.fetchone()
# create the row dictionary to be able to call row['login']
**row = dict(zip(field_name, values))**
# print the dictionary
print(row)
# print specific field
print(**row['login']**)
# print all field
for key in row:
print(**key," = ",row[key]**)
# close database connection
db.close()
A:
import mysql
import mysql.connector
db = mysql.connector.connect(
host = "localhost",
user = "root",
passwd = "P@ssword1",
database = "appbase"
)
cursor = db.cursor(dictionary=True)
sql = "select Id, Email from appuser limit 0,1"
cursor.execute(sql)
result = cursor.fetchone()
print(result)
# output => {'Id': 1, 'Email': 'me@gmail.com'}
print(result["Id"])
# output => 1
print(result["Email"])
# output => me@gmail.com
A:
python 2.7
import pymysql
conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='password', db='sakila')
cur = conn.cursor()
n = cur.execute('select * from actor')
c = cur.fetchall()
for i in c:
print i[1]
A:
Of course there is. In Python 2.7.2+...
import MySQLdb as mdb
con = mdb.connect('localhost', 'user', 'password', 'db');
cur = con.cursor()
cur.execute('SELECT Foo, Bar FROM Table')
for i in range(int(cur.numrows)):
foo, bar = cur.fetchone()
print 'foo = %s' % foo
print 'bar = %s' % bar
A:
selecting values from particular column:
import pymysql
db = pymysql.connect("localhost","root","root","school")
cursor=db.cursor()
sql="""select Total from student"""
l=[]
try:
#query execution
cursor.execute(sql)
#fetch all rows
rs = cursor.fetchall()
#iterate through rows
for i in rs:
#converting set to list
k=list(i)
#taking the first element from the list and append it to the list
l.append(k[0])
db.commit()
except:
db.rollback()
db.close()
print(l)
A:
You didn't provide many details, but you could try something like this:
# conn is an ODBC connection to the DB
dbCursor = conn.cursor()
sql = ('select field1, field2 from table')
dbCursor = conn.cursor()
dbCursor.execute(sql)
for row in dbCursor:
# Now you should be able to access the fields as properties of "row"
myVar1 = row.field1
myVar2 = row.field2
conn.close()
A:
import mysql.connector as mysql
...
cursor = mysql.cnx.cursor()
cursor.execute('select max(id) max_id from ids')
(id) = [ id for id in cursor ]
A:
Dictionary Cursor might save your day
cursor = db.cursor(dictionary=True)
|
How to retrieve SQL result column value using column name in Python?
|
Is there a way to retrieve SQL result column value using column name instead of column index in Python? I'm using Python 3 with mySQL. The syntax I'm looking for is pretty much like the Java construct:
Object id = rs.get("CUSTOMER_ID");
I've a table with quite a number of columns and it is a real pain to constantly work out the index for each column I need to access. Furthermore the index is making my code hard to read.
Thanks!
|
[
"The MySQLdb module has a DictCursor:\nUse it like this (taken from Writing MySQL Scripts with Python DB-API):\ncursor = conn.cursor(MySQLdb.cursors.DictCursor)\ncursor.execute(\"SELECT name, category FROM animal\")\nresult_set = cursor.fetchall()\nfor row in result_set:\n print \"%s, %s\" % (row[\"name\"], row[\"category\"])\n\nedit: According to user1305650 this works for pymysql as well.\n",
"This post is old but may come up via searching.\nNow you can use mysql.connector to retrive a dictionary as shown here:\nhttps://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursordict.html\nHere is the example on the mysql site:\ncnx = mysql.connector.connect(database='world')\ncursor = cnx.cursor(dictionary=True)\ncursor.execute(\"SELECT * FROM country WHERE Continent = 'Europe'\")\n\nprint(\"Countries in Europe:\")\nfor row in cursor:\n print(\"* {Name}\".format(Name=row['Name']))\n\n",
"you must look for something called \" dictionary in cursor \"\ni'm using mysql connector and i have to add this parameter to my cursor , so i can use my columns names instead of index's \ndb = mysql.connector.connect(\n host=db_info['mysql_host'],\n user=db_info['mysql_user'],\n passwd=db_info['mysql_password'],\n database=db_info['mysql_db'])\n\ncur = db.cursor()\n\ncur = db.cursor( buffered=True , dictionary=True)\n\n",
"import pymysql\n# Open database connection\ndb = pymysql.connect(\"localhost\",\"root\",\"\",\"gkdemo1\")\n\n# prepare a cursor object using cursor() method\ncursor = db.cursor()\n\n# execute SQL query using execute() method.\ncursor.execute(\"SELECT * from user\")\n\n# Get the fields name (only once!)\nfield_name = [field[0] for field in cursor.description]\n\n# Fetch a single row using fetchone() method.\nvalues = cursor.fetchone()\n\n# create the row dictionary to be able to call row['login']\n**row = dict(zip(field_name, values))**\n\n# print the dictionary\nprint(row)\n\n# print specific field\nprint(**row['login']**)\n\n# print all field\nfor key in row:\n print(**key,\" = \",row[key]**)\n\n# close database connection\ndb.close()\n\n",
"import mysql\nimport mysql.connector\n\ndb = mysql.connector.connect(\n host = \"localhost\",\n user = \"root\",\n passwd = \"P@ssword1\",\n database = \"appbase\"\n)\n\ncursor = db.cursor(dictionary=True)\n\nsql = \"select Id, Email from appuser limit 0,1\"\ncursor.execute(sql)\nresult = cursor.fetchone()\n\nprint(result)\n# output => {'Id': 1, 'Email': 'me@gmail.com'}\n\nprint(result[\"Id\"])\n# output => 1\n\nprint(result[\"Email\"])\n# output => me@gmail.com\n\n",
"python 2.7\nimport pymysql\n\nconn = pymysql.connect(host='localhost', port=3306, user='root', passwd='password', db='sakila')\n\ncur = conn.cursor()\n\nn = cur.execute('select * from actor')\nc = cur.fetchall()\n\nfor i in c:\n print i[1]\n\n",
"Of course there is. In Python 2.7.2+...\nimport MySQLdb as mdb\ncon = mdb.connect('localhost', 'user', 'password', 'db');\ncur = con.cursor()\ncur.execute('SELECT Foo, Bar FROM Table')\nfor i in range(int(cur.numrows)):\n foo, bar = cur.fetchone()\n print 'foo = %s' % foo\n print 'bar = %s' % bar\n\n",
"selecting values from particular column:\nimport pymysql\ndb = pymysql.connect(\"localhost\",\"root\",\"root\",\"school\")\ncursor=db.cursor()\nsql=\"\"\"select Total from student\"\"\"\nl=[]\ntry:\n #query execution\n cursor.execute(sql)\n #fetch all rows \n rs = cursor.fetchall()\n #iterate through rows\n for i in rs:\n #converting set to list\n k=list(i)\n #taking the first element from the list and append it to the list\n l.append(k[0])\n db.commit()\nexcept:\n db.rollback()\ndb.close()\nprint(l)\n\n",
"You didn't provide many details, but you could try something like this:\n# conn is an ODBC connection to the DB\ndbCursor = conn.cursor()\nsql = ('select field1, field2 from table') \ndbCursor = conn.cursor()\ndbCursor.execute(sql)\nfor row in dbCursor:\n # Now you should be able to access the fields as properties of \"row\"\n myVar1 = row.field1\n myVar2 = row.field2\nconn.close()\n\n",
"import mysql.connector as mysql\n...\ncursor = mysql.cnx.cursor()\ncursor.execute('select max(id) max_id from ids')\n(id) = [ id for id in cursor ]\n\n",
"Dictionary Cursor might save your day\ncursor = db.cursor(dictionary=True)\n\n"
] |
[
95,
31,
22,
14,
7,
6,
3,
2,
1,
0,
0
] |
[] |
[] |
[
"mysql",
"python"
] |
stackoverflow_0010195139_mysql_python.txt
|
Q:
Where is indentation problem in my Python code?
I'm trying to solve my homework coding assignment, but I'm facing a indentation error in my code. I spent quite long time now tryibg to figure out what I'm doing wrong but I don't see the error. Moreover, a friend of mine has a very similar code and it works just fine for him.
The Indentation error being raised after I add lines 141 and 142.
Starts in main() function with word "with". Click to see the image ->
Indent error lines 141, 142
I also tried to put the functionality in separate function, and when I try to call it in main(), I face the same error. Full code attached below.
Thank you community!
`
#Imports
import sys
import os
from bitstring import BitArray
#Declaration of variables
op = ''
rt = ''
rs = ''
imm = ''
ans = ''
shamt = ''
funct = ''
comm = ''
RegDst = ''
ALUSrc = ''
MemtoReg = ''
RegWrite = ''
MemRead = ''
MemWrite = ''
branch = ''
ALUOp1 = ''
ALUOp2 = ''
zeroBit = ''
oper = ''
#Dictionaries
opDict = {'001000' : 'addi', '000000' : {'100000' : 'add', '100010' : 'sub'}}
regValues = [0, 0, 0, 0, 0, 0, 0, 0]
regMap = {'00000' : 0 , '00001' : 1, '00010' : 2, '00011' : 3, '00100' : 4, '00101' : 5, '00110' : 6, '00111' : 7}
#Main function
def program(request, newFile, newFileTwo, count):
splitInput(request, newFile)
ans = str(regValues).replace(",", "")
ans = ans.replace("[","")
ans = ans.replace("]","")
ans = ans.replace(" ","|")
newFileTwo.write(str(count) + "|" + ans + '\n')
#Utility functions
def splitInput(inn, file):
op = inn[0:6]
if (op == '001000'):
# I-Type
rt = inn[6:11]
rs = inn[11:16]
imm = inn[16:32]
b = BitArray(bin=imm)
ans = b.int
oper = 'addi'
decideCtrl(oper, file)
addi(rt, rs, ans)
elif (op == '000000'):
# R - Type
rs = inn[6:11]
rt = inn[11:16]
rd = inn[16:21]
shamt = inn[21:26]
funct = inn[26:33].replace("\n", "")
# Add / Sub
if(opDict['000000'][funct] == 'add'):
# Add command
oper = 'add'
decideCtrl(oper, file)
add(rs,rt,rd)
elif(opDict['000000'][funct] == 'sub'):
# Sub Command
oper = 'sub'
decideCtrl(oper, file)
sub(rd, rs, rt)
#Dedice on control signals
def decideCtrl(op, file):
match op:
case 'add':
RegDst = '1'
RegWrite = '1'
ALUSrc = '0'
MemtoReg = '0'
RegWrite = '1'
MemRead = '0'
MemWrite = '0'
branch = '0'
ALUOp1 = '1'
ALUOp2 = '0'
comm = 'add'
file.write(RegDst + ALUSrc + MemtoReg + RegWrite + MemRead + MemWrite + branch + ALUOp1 + ALUOp2 +'\n')
case 'sub':
RegDst = '1'
RegWrite = '1'
ALUSrc = '0'
MemtoReg = '0'
RegWrite = '1'
MemRead = '0'
MemWrite = '0'
branch = '0'
ALUOp1 = '1'
ALUOp2 = '0'
comm = 'sub'
file.write(RegDst + ALUSrc + MemtoReg + RegWrite + MemRead + MemWrite + branch + ALUOp1 + ALUOp2 + '\n')
case 'addi':
RegDst = '0'
RegWrite = '1'
ALUSrc = '1'
MemtoReg = '0'
RegWrite = '1'
MemRead = '0'
MemWrite = '0'
branch = '0'
ALUOp1 = '0'
ALUOp2 = '0'
comm = 'addi'
file.write(RegDst + ALUSrc + MemtoReg + RegWrite + MemRead + MemWrite + branch + ALUOp1 + ALUOp2 + '\n')
#Commands
def add(rs, rt, rd):
regValues[regMap[rd]] = regValues[regMap[rs]] + regValues[regMap[rt]]
def sub(rd, rs, rt):
regValues[regMap[rd]] = regValues[regMap[rs]] - regValues[regMap[rt]]
def addi(rt, rs, imm):
regValues[regMap[rs]] = regValues[regMap[rt]] + imm
def main():
PCount = 65536
count = 0
# inputName = str(sys.argv[1])
# F = open(inputName, "r")
with open(filename, "r") as file:
storedLines = file.read().splitlines()
newFile = open("outputOne.txt", "w")
newFileTwo = open("outputTwo.txt", "w")
ans = str(regValues).replace(",", "")
ans = ans.replace("[","")
ans = ans.replace("]","")
ans = ans.replace(" ","|")
newFileTwo.write(str(PCount) + "|" + ans + '\n')
# for comms in F:
# if (count == 100):
# F.close()
# newFile.close()
# newFileTwo.close()
# exit()
# PCount = PCount + 4
# program(comms, newFile, newFileTwo, PCount)
# count = count + 1
#F.close()
newFile.close()
newFileTwo.close()
# Use open file to store the lines with their indicies
# When beq or bne compare and if it's true -> grab the label imm -> convert to decimal
# -> divide by 4 to get actual line
# Ad
# While i less than size of array of lines go one by one and do logic
# storedLines[i] - line of a code in a file. Do logic to each [i]
# Add internal pc counter (intpc=0). By each iteration of i intpc goes +4
# at the end of while loop internalPC = 4
# i == internalPC // 4
# App Entry Point
if __name__ == "__main__":
main()
`
Compared my code to friend's and it looks like it works for him (The same lines, 141, 142)
Tried to put functionality in separate function -> Does not work
I expect the code to put the all contents of a provided file into array using with
A:
I've fixed the indentation errors I was able to find in your code, made some changes to it, and added some remark comments as "# NOTE: ...":
# == Necessary Imports =========================================================
import sys
import os
from bitstring import BitArray
# == Variables =================================================================
op = ""
rt = ""
rs = ""
imm = ""
ans = ""
shamt = ""
funct = ""
comm = ""
RegDst = ""
ALUSrc = ""
MemtoReg = ""
RegWrite = ""
MemRead = ""
MemWrite = ""
branch = ""
ALUOp1 = ""
ALUOp2 = ""
zeroBit = ""
oper = ""
# == Dictionaries ==============================================================
opDict = {"001000": "addi", "000000": {"100000": "add", "100010": "sub"}}
regValues = [0, 0, 0, 0, 0, 0, 0, 0]
regMap = {
"00000": 0,
"00001": 1,
"00010": 2,
"00011": 3,
"00100": 4,
"00101": 5,
"00110": 6,
"00111": 7,
}
# == Main Function =============================================================
def program(request, newFile, newFileTwo, count):
splitInput(request, newFile)
ans = (
str(count)
+ "|"
+ str(regValues)
.replace(",", "")
.replace("[", "")
.replace("]", "")
.replace(" ", "|")
+ "\n"
)
newFileTwo.write(ans)
# == Utility Function ==========================================================
def splitInput(inn, file):
op = inn[:6]
if op == "000000":
# R-Type
rs = inn[6:11]
rt = inn[11:16]
rd = inn[16:21]
# NOTE: `shamt` shadows the global variable `shamt`.
shamt = inn[21:26]
# NOTE: `funct` shadows the global variable `funct`.
funct = inn[26:33].replace("\n", "")
# Add / Sub
if opDict["000000"][funct] == "add":
decideCtrl("add", file)
add(rs, rt, rd)
elif opDict["000000"][funct] == "sub":
decideCtrl("sub", file)
sub(rd, rs, rt)
elif op == "001000":
# I-Type
# NOTE: `rt` shadows the global variable `rt`.
rt = inn[6:11]
# NOTE: `rs` shadows the global variable `rs`.
rs = inn[11:16]
# NOTE: `imm` shadows the global variable `imm`.
imm = inn[16:32]
# NOTE: `ans` shadows the global variable `ans`.
ans = BitArray(bin=imm).int
decideCtrl("addi", file)
addi(rt, rs, ans)
# Dedice on control signals
def decideCtrl(op, file):
RegDst = "1"
ALUSrc = "0"
MemtoReg = "0"
RegWrite = "1"
MemRead = "0"
MemWrite = "0"
branch = "0"
ALUOp1 = "1"
ALUOp2 = "0"
match op:
case "add":
# NOTE: `comm` seems to be unused.
# NOTE: `comm` shadows the global variable `comm`.
comm = "add"
case "sub":
# NOTE: `comm` seems to be unused.
# NOTE: `comm` shadows the global variable `comm`.
comm = "sub"
case "addi":
RegDst = "0"
ALUSrc = "1"
ALUOp1 = "0"
# NOTE: `comm` seems to be unused.
# NOTE: `comm` shadows the global variable `comm`.
comm = "addi"
file.write(RegDst + ALUSrc + MemtoReg + RegWrite + MemRead + MemWrite
+ branch + ALUOp1 + ALUOp2 + "\n")
# == Functions =================================================================
# NOTE: renamed the function parameters to avoid shadowing the global variables.x
def add(_rs, _rt, _rd):
regValues[regMap[_rd]] = regValues[regMap[_rs]] + regValues[regMap[_rt]]
# NOTE: renamed the function parameters to avoid shadowing the global variables.x
def sub(_rd, _rs, _rt):
regValues[regMap[_rd]] = regValues[regMap[_rs]] - regValues[regMap[_rt]]
# NOTE: renamed the function parameters to avoid shadowing the global variables.x
def addi(_rt, _rs, _imm):
regValues[regMap[_rs]] = regValues[regMap[_rt]] + _imm
def main():
PCount = 65536
# NOTE: commented this line, because it's not being used anywhere.
# QUESTION: where do you define the variable "filename"?
# with open(filename, mode="r", encoding="utf-8") as file:
# storedLines = file.read().splitlines()
ans = (
str(regValues)
.replace(",", "")
.replace("[", "")
.replace("]", "")
.replace(" ", "|")
)
# NOTE: specified the `encoding` parameter, as it's a good practice.
# NOTE: modified to `with open` as it's a good practice.
with open("outputTwo.txt", mode = "w", encoding = "utf-8") as newFileTwo,\
open("outputOne.txt", mode = "w", encoding = "utf-8") as newFile:
newFileTwo.write(f"{PCount}|{ans}\n")
# NOTE: creating some sample data for `F`, as I couldn't find it anywhere.
F = [
"0010000000000000000000000000000000",
"0010000000000000000000000000000000",
"0010000000000000000000000000000000",
"0010000000000000000000000000000000",
"0010000000000000000000000000000000",
"0010000000000000000000000000000000",
"0010000000000000000000000000000000",
"0010000000000000000000000000000000",
"0010000000000000000000000000000000",
"0010000000000000000000000000000000",
]
for count, comms in enumerate(F):
if count == 100:
# newFile.close() # If you use `with open`, you dont't need to close the file.
# newFileTwo.close() # If you use `with open`, you dont't need to close the file.
exit()
PCount += 4
program(comms, newFile, newFileTwo, PCount)
# Use open file to store the lines with their indicies
# When beq or bne compare and if:
# true -> grab label imm -> convert to decimal -> divide by 4 to get actual line
# Ad
# While `i` is less than the size of the lines array, iterate through it,
# and do the following logic:
# storedLines[i] - line of a code in a file. Do logic to each [i]
# Add internal pc counter (`intpc=0`). By each iteration of `i`, `intpc` goes +4
# at the end of while loop internalPC = 4
# i == internalPC // 4
# App Entry Point
if __name__ == "__main__":
main()
|
Where is indentation problem in my Python code?
|
I'm trying to solve my homework coding assignment, but I'm facing a indentation error in my code. I spent quite long time now tryibg to figure out what I'm doing wrong but I don't see the error. Moreover, a friend of mine has a very similar code and it works just fine for him.
The Indentation error being raised after I add lines 141 and 142.
Starts in main() function with word "with". Click to see the image ->
Indent error lines 141, 142
I also tried to put the functionality in separate function, and when I try to call it in main(), I face the same error. Full code attached below.
Thank you community!
`
#Imports
import sys
import os
from bitstring import BitArray
#Declaration of variables
op = ''
rt = ''
rs = ''
imm = ''
ans = ''
shamt = ''
funct = ''
comm = ''
RegDst = ''
ALUSrc = ''
MemtoReg = ''
RegWrite = ''
MemRead = ''
MemWrite = ''
branch = ''
ALUOp1 = ''
ALUOp2 = ''
zeroBit = ''
oper = ''
#Dictionaries
opDict = {'001000' : 'addi', '000000' : {'100000' : 'add', '100010' : 'sub'}}
regValues = [0, 0, 0, 0, 0, 0, 0, 0]
regMap = {'00000' : 0 , '00001' : 1, '00010' : 2, '00011' : 3, '00100' : 4, '00101' : 5, '00110' : 6, '00111' : 7}
#Main function
def program(request, newFile, newFileTwo, count):
splitInput(request, newFile)
ans = str(regValues).replace(",", "")
ans = ans.replace("[","")
ans = ans.replace("]","")
ans = ans.replace(" ","|")
newFileTwo.write(str(count) + "|" + ans + '\n')
#Utility functions
def splitInput(inn, file):
op = inn[0:6]
if (op == '001000'):
# I-Type
rt = inn[6:11]
rs = inn[11:16]
imm = inn[16:32]
b = BitArray(bin=imm)
ans = b.int
oper = 'addi'
decideCtrl(oper, file)
addi(rt, rs, ans)
elif (op == '000000'):
# R - Type
rs = inn[6:11]
rt = inn[11:16]
rd = inn[16:21]
shamt = inn[21:26]
funct = inn[26:33].replace("\n", "")
# Add / Sub
if(opDict['000000'][funct] == 'add'):
# Add command
oper = 'add'
decideCtrl(oper, file)
add(rs,rt,rd)
elif(opDict['000000'][funct] == 'sub'):
# Sub Command
oper = 'sub'
decideCtrl(oper, file)
sub(rd, rs, rt)
#Dedice on control signals
def decideCtrl(op, file):
match op:
case 'add':
RegDst = '1'
RegWrite = '1'
ALUSrc = '0'
MemtoReg = '0'
RegWrite = '1'
MemRead = '0'
MemWrite = '0'
branch = '0'
ALUOp1 = '1'
ALUOp2 = '0'
comm = 'add'
file.write(RegDst + ALUSrc + MemtoReg + RegWrite + MemRead + MemWrite + branch + ALUOp1 + ALUOp2 +'\n')
case 'sub':
RegDst = '1'
RegWrite = '1'
ALUSrc = '0'
MemtoReg = '0'
RegWrite = '1'
MemRead = '0'
MemWrite = '0'
branch = '0'
ALUOp1 = '1'
ALUOp2 = '0'
comm = 'sub'
file.write(RegDst + ALUSrc + MemtoReg + RegWrite + MemRead + MemWrite + branch + ALUOp1 + ALUOp2 + '\n')
case 'addi':
RegDst = '0'
RegWrite = '1'
ALUSrc = '1'
MemtoReg = '0'
RegWrite = '1'
MemRead = '0'
MemWrite = '0'
branch = '0'
ALUOp1 = '0'
ALUOp2 = '0'
comm = 'addi'
file.write(RegDst + ALUSrc + MemtoReg + RegWrite + MemRead + MemWrite + branch + ALUOp1 + ALUOp2 + '\n')
#Commands
def add(rs, rt, rd):
regValues[regMap[rd]] = regValues[regMap[rs]] + regValues[regMap[rt]]
def sub(rd, rs, rt):
regValues[regMap[rd]] = regValues[regMap[rs]] - regValues[regMap[rt]]
def addi(rt, rs, imm):
regValues[regMap[rs]] = regValues[regMap[rt]] + imm
def main():
PCount = 65536
count = 0
# inputName = str(sys.argv[1])
# F = open(inputName, "r")
with open(filename, "r") as file:
storedLines = file.read().splitlines()
newFile = open("outputOne.txt", "w")
newFileTwo = open("outputTwo.txt", "w")
ans = str(regValues).replace(",", "")
ans = ans.replace("[","")
ans = ans.replace("]","")
ans = ans.replace(" ","|")
newFileTwo.write(str(PCount) + "|" + ans + '\n')
# for comms in F:
# if (count == 100):
# F.close()
# newFile.close()
# newFileTwo.close()
# exit()
# PCount = PCount + 4
# program(comms, newFile, newFileTwo, PCount)
# count = count + 1
#F.close()
newFile.close()
newFileTwo.close()
# Use open file to store the lines with their indicies
# When beq or bne compare and if it's true -> grab the label imm -> convert to decimal
# -> divide by 4 to get actual line
# Ad
# While i less than size of array of lines go one by one and do logic
# storedLines[i] - line of a code in a file. Do logic to each [i]
# Add internal pc counter (intpc=0). By each iteration of i intpc goes +4
# at the end of while loop internalPC = 4
# i == internalPC // 4
# App Entry Point
if __name__ == "__main__":
main()
`
Compared my code to friend's and it looks like it works for him (The same lines, 141, 142)
Tried to put functionality in separate function -> Does not work
I expect the code to put the all contents of a provided file into array using with
|
[
"I've fixed the indentation errors I was able to find in your code, made some changes to it, and added some remark comments as \"# NOTE: ...\":\n\n# == Necessary Imports =========================================================\nimport sys\nimport os\n\nfrom bitstring import BitArray\n\n\n# == Variables =================================================================\nop = \"\"\nrt = \"\"\nrs = \"\"\nimm = \"\"\nans = \"\"\nshamt = \"\"\nfunct = \"\"\ncomm = \"\"\nRegDst = \"\"\nALUSrc = \"\"\nMemtoReg = \"\"\nRegWrite = \"\"\nMemRead = \"\"\nMemWrite = \"\"\nbranch = \"\"\nALUOp1 = \"\"\nALUOp2 = \"\"\nzeroBit = \"\"\noper = \"\"\n\n# == Dictionaries ==============================================================\nopDict = {\"001000\": \"addi\", \"000000\": {\"100000\": \"add\", \"100010\": \"sub\"}}\nregValues = [0, 0, 0, 0, 0, 0, 0, 0]\nregMap = {\n \"00000\": 0,\n \"00001\": 1,\n \"00010\": 2,\n \"00011\": 3,\n \"00100\": 4,\n \"00101\": 5,\n \"00110\": 6,\n \"00111\": 7,\n}\n\n\n# == Main Function =============================================================\ndef program(request, newFile, newFileTwo, count):\n splitInput(request, newFile)\n ans = (\n str(count)\n + \"|\"\n + str(regValues)\n .replace(\",\", \"\")\n .replace(\"[\", \"\")\n .replace(\"]\", \"\")\n .replace(\" \", \"|\")\n + \"\\n\"\n )\n newFileTwo.write(ans)\n\n\n# == Utility Function ==========================================================\ndef splitInput(inn, file):\n op = inn[:6]\n if op == \"000000\":\n # R-Type\n rs = inn[6:11]\n rt = inn[11:16]\n rd = inn[16:21]\n # NOTE: `shamt` shadows the global variable `shamt`.\n shamt = inn[21:26]\n # NOTE: `funct` shadows the global variable `funct`.\n funct = inn[26:33].replace(\"\\n\", \"\")\n\n # Add / Sub\n if opDict[\"000000\"][funct] == \"add\":\n decideCtrl(\"add\", file)\n add(rs, rt, rd)\n elif opDict[\"000000\"][funct] == \"sub\":\n decideCtrl(\"sub\", file)\n sub(rd, rs, rt)\n\n elif op == \"001000\":\n # I-Type\n # NOTE: `rt` shadows the global variable `rt`.\n rt = inn[6:11]\n # NOTE: `rs` shadows the global variable `rs`.\n rs = inn[11:16]\n # NOTE: `imm` shadows the global variable `imm`.\n imm = inn[16:32]\n # NOTE: `ans` shadows the global variable `ans`.\n ans = BitArray(bin=imm).int\n decideCtrl(\"addi\", file)\n addi(rt, rs, ans)\n\n\n# Dedice on control signals\ndef decideCtrl(op, file):\n RegDst = \"1\"\n ALUSrc = \"0\"\n MemtoReg = \"0\"\n RegWrite = \"1\"\n MemRead = \"0\"\n MemWrite = \"0\"\n branch = \"0\"\n ALUOp1 = \"1\"\n ALUOp2 = \"0\"\n\n match op:\n case \"add\":\n # NOTE: `comm` seems to be unused.\n # NOTE: `comm` shadows the global variable `comm`.\n comm = \"add\"\n\n case \"sub\":\n # NOTE: `comm` seems to be unused.\n # NOTE: `comm` shadows the global variable `comm`.\n comm = \"sub\"\n\n case \"addi\":\n RegDst = \"0\"\n ALUSrc = \"1\"\n ALUOp1 = \"0\"\n # NOTE: `comm` seems to be unused.\n # NOTE: `comm` shadows the global variable `comm`.\n comm = \"addi\"\n\n file.write(RegDst + ALUSrc + MemtoReg + RegWrite + MemRead + MemWrite\n + branch + ALUOp1 + ALUOp2 + \"\\n\")\n\n\n# == Functions =================================================================\n# NOTE: renamed the function parameters to avoid shadowing the global variables.x\ndef add(_rs, _rt, _rd):\n regValues[regMap[_rd]] = regValues[regMap[_rs]] + regValues[regMap[_rt]]\n\n\n# NOTE: renamed the function parameters to avoid shadowing the global variables.x\ndef sub(_rd, _rs, _rt):\n regValues[regMap[_rd]] = regValues[regMap[_rs]] - regValues[regMap[_rt]]\n\n\n# NOTE: renamed the function parameters to avoid shadowing the global variables.x\ndef addi(_rt, _rs, _imm):\n regValues[regMap[_rs]] = regValues[regMap[_rt]] + _imm\n\n\ndef main():\n\n PCount = 65536\n # NOTE: commented this line, because it's not being used anywhere.\n # QUESTION: where do you define the variable \"filename\"?\n # with open(filename, mode=\"r\", encoding=\"utf-8\") as file:\n # storedLines = file.read().splitlines()\n\n ans = (\n str(regValues)\n .replace(\",\", \"\")\n .replace(\"[\", \"\")\n .replace(\"]\", \"\")\n .replace(\" \", \"|\")\n )\n # NOTE: specified the `encoding` parameter, as it's a good practice.\n # NOTE: modified to `with open` as it's a good practice.\n with open(\"outputTwo.txt\", mode = \"w\", encoding = \"utf-8\") as newFileTwo,\\\n open(\"outputOne.txt\", mode = \"w\", encoding = \"utf-8\") as newFile:\n newFileTwo.write(f\"{PCount}|{ans}\\n\")\n\n # NOTE: creating some sample data for `F`, as I couldn't find it anywhere.\n F = [\n \"0010000000000000000000000000000000\",\n \"0010000000000000000000000000000000\",\n \"0010000000000000000000000000000000\",\n \"0010000000000000000000000000000000\",\n \"0010000000000000000000000000000000\",\n \"0010000000000000000000000000000000\",\n \"0010000000000000000000000000000000\",\n \"0010000000000000000000000000000000\",\n \"0010000000000000000000000000000000\",\n \"0010000000000000000000000000000000\",\n ]\n\n for count, comms in enumerate(F):\n if count == 100:\n # newFile.close() # If you use `with open`, you dont't need to close the file.\n # newFileTwo.close() # If you use `with open`, you dont't need to close the file.\n exit()\n PCount += 4\n program(comms, newFile, newFileTwo, PCount)\n\n\n# Use open file to store the lines with their indicies\n# When beq or bne compare and if:\n# true -> grab label imm -> convert to decimal -> divide by 4 to get actual line\n\n# Ad\n# While `i` is less than the size of the lines array, iterate through it,\n# and do the following logic:\n# storedLines[i] - line of a code in a file. Do logic to each [i]\n# Add internal pc counter (`intpc=0`). By each iteration of `i`, `intpc` goes +4\n# at the end of while loop internalPC = 4\n# i == internalPC // 4\n\n# App Entry Point\nif __name__ == \"__main__\":\n main()\n\n\n\n"
] |
[
0
] |
[] |
[] |
[
"compiler_errors",
"indentation",
"pylance",
"python",
"syntax_error"
] |
stackoverflow_0074526466_compiler_errors_indentation_pylance_python_syntax_error.txt
|
Q:
Is there a way to detect exisiting link from a text file in python
I have code in jupyter notebook with the help of requests to get confirmation on whether that url existed or not and after that prints out the output into the text file. Here is the line code for that
import requests
Instaurl = open("dictionaries/insta.txt", 'w', encoding="utf-8")
cli = ['duolingo', 'ryanair', 'mcguinness.paddy', 'duolingodeutschland', 'duolingobrasil']
exist=[]
url = []
for i in cli:
r = requests.get("https://www.instagram.com/"+i+"/")
if r.apparent_encoding == 'Windows-1252':
exist.append(i)
url.append("instagram.com/"+i+"/")
Instaurl.write(url)
Let's say that inside the cli list, i accidentally added the same existing username as before into the text file (duolingo for example). Is there a way where if the requests found the same URL from the text file, it would not be added into the the text file again?
Thank you!
A:
You defined a list:
cli = ['duolingo', ...]
It sounds like you would prefer to define a set:
cli = {'duolingo', ...}
That way, duplicates will be suppressed.
It happens for dups in the initial
assignment, and for any duplicate cli.add(entry) you might attempt later.
|
Is there a way to detect exisiting link from a text file in python
|
I have code in jupyter notebook with the help of requests to get confirmation on whether that url existed or not and after that prints out the output into the text file. Here is the line code for that
import requests
Instaurl = open("dictionaries/insta.txt", 'w', encoding="utf-8")
cli = ['duolingo', 'ryanair', 'mcguinness.paddy', 'duolingodeutschland', 'duolingobrasil']
exist=[]
url = []
for i in cli:
r = requests.get("https://www.instagram.com/"+i+"/")
if r.apparent_encoding == 'Windows-1252':
exist.append(i)
url.append("instagram.com/"+i+"/")
Instaurl.write(url)
Let's say that inside the cli list, i accidentally added the same existing username as before into the text file (duolingo for example). Is there a way where if the requests found the same URL from the text file, it would not be added into the the text file again?
Thank you!
|
[
"You defined a list:\ncli = ['duolingo', ...]\n\nIt sounds like you would prefer to define a set:\ncli = {'duolingo', ...}\n\nThat way, duplicates will be suppressed.\nIt happens for dups in the initial\nassignment, and for any duplicate cli.add(entry) you might attempt later.\n"
] |
[
0
] |
[] |
[] |
[
"jupyter_notebook",
"python",
"python_requests"
] |
stackoverflow_0074527269_jupyter_notebook_python_python_requests.txt
|
Q:
Remove a widget generated with for loop
I work on a python project, and I would like to create a history where each history is erasable with a "delete" button placed in the Frame of the widget
I tried to add the « delete » button in the loop where the widget was generated but it didn’t work as planned
history_files = os.listdir(history_directory)
history_files.sort(reverse=True)
number_of_h = 0
for file in history_files:
file_dat = open(history_directory+"\\"+file)
file_dat_lines = file_dat.readlines()
action_amount_h = file_dat_lines[0]
h_comment = file_dat_lines[1]
h_date = file_dat_lines[2]
h_time = file_dat_lines[3]
history_f = Frame(history_win_f, bg=bg_theme, height=120, width=485, highlightbackground=bg_theme_2, highlightthickness=1)
history_f.grid_propagate(False)
history_f.columnconfigure(1, weight=70)
history_f.columnconfigure(2, weight=30)
history_f.rowconfigure(1, weight=60)
history_f.rowconfigure(2, weight=40)
action_h_f = LabelFrame(history_f, bg=bg_theme, width=390, height=120, font='Courrier 13 bold', labelanchor="n")
action_h_f.grid_propagate(False)
action_h_f.rowconfigure(1, weight=30)
action_h_f.rowconfigure(2, weight=70)
action_h_f.columnconfigure(1, weight=100)
action_h_f.grid(row=1, column=1, sticky="w")
date_h_f = LabelFrame(history_f, bg=bg_theme, height=120, width=95, text=' Date ', labelanchor="n", font='Courrier 10 bold')
date_h_f.grid(row=1, rowspan=2, column=2, sticky="nesw")
date_h_f.rowconfigure(1, weight=50)
date_h_f.rowconfigure(2, weight=50)
date_h_f.columnconfigure(1, weight=100)
date_l = Label(date_h_f, text="Le "+h_date, bg=bg_theme, fg=fg_theme_2, font='Courrier 8').grid(row=1, column=1, sticky="nesw")
time_l = Label(date_h_f, text="A "+h_time, bg=bg_theme, fg=fg_theme_2, font='Courrier 8').grid(row=2, column=1, sticky="nesw")
date_h_f.grid_propagate(False)
h_edit_a = Label(action_h_f, bg=bg_theme, font="Courrier 11", justify="center")
h_edit_a_str = ""
I would appreciate any explanation, and if the code is simple, because I'm still a newbie. Thanks !
A:
It's hard to know what do you wish to accomplish. I can't see any button on your code and I'm not clear what do you wish to delete when the delete button is clicked.
As per my understanding, If the delete button is on the history_f, and you wish to remove or delete the Labels i.e. date_l and time_l then following is how you can do it.
for file in history_files:
file_dat = open(history_directory+"\\"+file)
file_dat_lines = file_dat.readlines()
action_amount_h = file_dat_lines[0]
h_comment = file_dat_lines[1]
h_date = file_dat_lines[2]
h_time = file_dat_lines[3]
history_f = Frame(history_win_f, bg=bg_theme, height=120, width=485, highlightbackground=bg_theme_2, highlightthickness=1)
history_f.grid_propagate(False)
history_f.columnconfigure(1, weight=70)
history_f.columnconfigure(2, weight=30)
history_f.rowconfigure(1, weight=60)
history_f.rowconfigure(2, weight=40)
action_h_f = LabelFrame(history_f, bg=bg_theme, width=390, height=120, font='Courrier 13 bold', labelanchor="n")
action_h_f.grid_propagate(False)
action_h_f.rowconfigure(1, weight=30)
action_h_f.rowconfigure(2, weight=70)
action_h_f.columnconfigure(1, weight=100)
action_h_f.grid(row=1, column=1, sticky="w")
date_h_f = LabelFrame(history_f, bg=bg_theme, height=120, width=95, text=' Date ', labelanchor="n", font='Courrier 10 bold')
date_h_f.grid(row=1, rowspan=2, column=2, sticky="nesw")
date_h_f.rowconfigure(1, weight=50)
date_h_f.rowconfigure(2, weight=50)
date_h_f.columnconfigure(1, weight=100)
date_l = Label(date_h_f, text="Le "+h_date, bg=bg_theme, fg=fg_theme_2, font='Courrier 8').grid(row=1, column=1, sticky="nesw")
time_l = Label(date_h_f, text="A "+h_time, bg=bg_theme, fg=fg_theme_2, font='Courrier 8').grid(row=2, column=1, sticky="nesw")
date_h_f.grid_propagate(False)
h_edit_a = Label(action_h_f, bg=bg_theme, font="Courrier 11", justify="center")
h_edit_a_str = ""
############################################
#assume button is on action_h_f
ttk.Button(action_h_f, text="delete", command=lambda :
delete_record(date_l, time_l)
def delete_record(widget1, widget2):
widget1.destroy()
widget2.destroy()
you must pass the reference of both the label to the delete_record() function.
Just my guess, correct me if I am wrong.
A:
Create the delete button inside history_f frame as well and destroy history_f when it is clicked. Note that you do not call any layout function on history_f, so it will not be shown and you will get a blank window.
Below are the required changes:
...
for file in history_files:
...
history_f = Frame(history_win_f, bg=bg_theme, height=120, width=485, highlightbackground=bg_theme_2, highlightthickness=1)
history_f.pack() # call layout function on history_f
...
h_edit_a_str = ""
# create delete button and destroy history_f when clicked
Button(history_f, text="Delete", command=history_f.destroy).grid(row=1, column=4)
|
Remove a widget generated with for loop
|
I work on a python project, and I would like to create a history where each history is erasable with a "delete" button placed in the Frame of the widget
I tried to add the « delete » button in the loop where the widget was generated but it didn’t work as planned
history_files = os.listdir(history_directory)
history_files.sort(reverse=True)
number_of_h = 0
for file in history_files:
file_dat = open(history_directory+"\\"+file)
file_dat_lines = file_dat.readlines()
action_amount_h = file_dat_lines[0]
h_comment = file_dat_lines[1]
h_date = file_dat_lines[2]
h_time = file_dat_lines[3]
history_f = Frame(history_win_f, bg=bg_theme, height=120, width=485, highlightbackground=bg_theme_2, highlightthickness=1)
history_f.grid_propagate(False)
history_f.columnconfigure(1, weight=70)
history_f.columnconfigure(2, weight=30)
history_f.rowconfigure(1, weight=60)
history_f.rowconfigure(2, weight=40)
action_h_f = LabelFrame(history_f, bg=bg_theme, width=390, height=120, font='Courrier 13 bold', labelanchor="n")
action_h_f.grid_propagate(False)
action_h_f.rowconfigure(1, weight=30)
action_h_f.rowconfigure(2, weight=70)
action_h_f.columnconfigure(1, weight=100)
action_h_f.grid(row=1, column=1, sticky="w")
date_h_f = LabelFrame(history_f, bg=bg_theme, height=120, width=95, text=' Date ', labelanchor="n", font='Courrier 10 bold')
date_h_f.grid(row=1, rowspan=2, column=2, sticky="nesw")
date_h_f.rowconfigure(1, weight=50)
date_h_f.rowconfigure(2, weight=50)
date_h_f.columnconfigure(1, weight=100)
date_l = Label(date_h_f, text="Le "+h_date, bg=bg_theme, fg=fg_theme_2, font='Courrier 8').grid(row=1, column=1, sticky="nesw")
time_l = Label(date_h_f, text="A "+h_time, bg=bg_theme, fg=fg_theme_2, font='Courrier 8').grid(row=2, column=1, sticky="nesw")
date_h_f.grid_propagate(False)
h_edit_a = Label(action_h_f, bg=bg_theme, font="Courrier 11", justify="center")
h_edit_a_str = ""
I would appreciate any explanation, and if the code is simple, because I'm still a newbie. Thanks !
|
[
"It's hard to know what do you wish to accomplish. I can't see any button on your code and I'm not clear what do you wish to delete when the delete button is clicked.\nAs per my understanding, If the delete button is on the history_f, and you wish to remove or delete the Labels i.e. date_l and time_l then following is how you can do it.\nfor file in history_files:\n file_dat = open(history_directory+\"\\\\\"+file)\n file_dat_lines = file_dat.readlines()\n action_amount_h = file_dat_lines[0]\n h_comment = file_dat_lines[1]\n h_date = file_dat_lines[2]\n h_time = file_dat_lines[3]\n history_f = Frame(history_win_f, bg=bg_theme, height=120, width=485, highlightbackground=bg_theme_2, highlightthickness=1)\n history_f.grid_propagate(False)\n history_f.columnconfigure(1, weight=70)\n history_f.columnconfigure(2, weight=30)\n history_f.rowconfigure(1, weight=60)\n history_f.rowconfigure(2, weight=40)\n action_h_f = LabelFrame(history_f, bg=bg_theme, width=390, height=120, font='Courrier 13 bold', labelanchor=\"n\")\n action_h_f.grid_propagate(False)\n action_h_f.rowconfigure(1, weight=30)\n action_h_f.rowconfigure(2, weight=70)\n action_h_f.columnconfigure(1, weight=100)\n action_h_f.grid(row=1, column=1, sticky=\"w\")\n date_h_f = LabelFrame(history_f, bg=bg_theme, height=120, width=95, text=' Date ', labelanchor=\"n\", font='Courrier 10 bold')\n date_h_f.grid(row=1, rowspan=2, column=2, sticky=\"nesw\")\n date_h_f.rowconfigure(1, weight=50)\n date_h_f.rowconfigure(2, weight=50)\n date_h_f.columnconfigure(1, weight=100)\n date_l = Label(date_h_f, text=\"Le \"+h_date, bg=bg_theme, fg=fg_theme_2, font='Courrier 8').grid(row=1, column=1, sticky=\"nesw\")\n time_l = Label(date_h_f, text=\"A \"+h_time, bg=bg_theme, fg=fg_theme_2, font='Courrier 8').grid(row=2, column=1, sticky=\"nesw\")\n date_h_f.grid_propagate(False)\n h_edit_a = Label(action_h_f, bg=bg_theme, font=\"Courrier 11\", justify=\"center\")\n h_edit_a_str = \"\"\n\n ############################################\n #assume button is on action_h_f\n ttk.Button(action_h_f, text=\"delete\", command=lambda : \n delete_record(date_l, time_l)\n\ndef delete_record(widget1, widget2):\n widget1.destroy()\n widget2.destroy()\n\n\nyou must pass the reference of both the label to the delete_record() function.\nJust my guess, correct me if I am wrong.\n",
"Create the delete button inside history_f frame as well and destroy history_f when it is clicked. Note that you do not call any layout function on history_f, so it will not be shown and you will get a blank window.\nBelow are the required changes:\n...\nfor file in history_files:\n ...\n history_f = Frame(history_win_f, bg=bg_theme, height=120, width=485, highlightbackground=bg_theme_2, highlightthickness=1)\n history_f.pack() # call layout function on history_f\n ...\n h_edit_a_str = \"\"\n\n # create delete button and destroy history_f when clicked\n Button(history_f, text=\"Delete\", command=history_f.destroy).grid(row=1, column=4)\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"for_loop",
"loops",
"python",
"tkinter",
"widget"
] |
stackoverflow_0074521835_for_loop_loops_python_tkinter_widget.txt
|
Q:
Using Counter on a list of Spacy tokens returns a non unique dict of the tokens
I want to count a list of spacy tokens with the counter class. I.e.:
[hello,how,are,you,hello]
where each element is of type <class 'spacy.tokens.token.Token'>.
However when i want to count the occurences of each Token within the list via counter, as seen below:
return Counter(joined)
The result is a non unique dict of the tokens or in other words: the same list as before but its a dict now and each key has the value of 1. In the screenshot below it can be seen, that the dict seemingly has the same key twice in it.
What is the reason for this?
A:
Tokens are not equivalent if they have the same text, they have to be in the same position in the same Doc object. But the output in your screenshot (don't post a screenshot of text...) is just the repr of a token, which is its text.
If you want to count just the text, use token.text, like so:
from collections import Counter
import spacy
nlp = spacy.blank("en")
doc = nlp("this is text, this is text")
out = Counter([tok.text for tok in doc])
|
Using Counter on a list of Spacy tokens returns a non unique dict of the tokens
|
I want to count a list of spacy tokens with the counter class. I.e.:
[hello,how,are,you,hello]
where each element is of type <class 'spacy.tokens.token.Token'>.
However when i want to count the occurences of each Token within the list via counter, as seen below:
return Counter(joined)
The result is a non unique dict of the tokens or in other words: the same list as before but its a dict now and each key has the value of 1. In the screenshot below it can be seen, that the dict seemingly has the same key twice in it.
What is the reason for this?
|
[
"Tokens are not equivalent if they have the same text, they have to be in the same position in the same Doc object. But the output in your screenshot (don't post a screenshot of text...) is just the repr of a token, which is its text.\nIf you want to count just the text, use token.text, like so:\nfrom collections import Counter\nimport spacy\n\nnlp = spacy.blank(\"en\")\ndoc = nlp(\"this is text, this is text\")\nout = Counter([tok.text for tok in doc])\n\n"
] |
[
0
] |
[] |
[] |
[
"counter",
"dictionary",
"nlp",
"python",
"spacy"
] |
stackoverflow_0074522022_counter_dictionary_nlp_python_spacy.txt
|
Q:
Import cv2 error but opencv-python is already installed
I've been trying to make a project with opencv, so I followed the YouTube video (It's in python), the video told me to go to cmd (win10) and use the command "pip install opencv-python" so that I can use the command import cv2. But the problem is after I did everything it still gave me an error.
I've done some research on it and nothing seem to work. I tried restarting my laptop or reinstall opencv, but nothing works for me. I'm thinking maybe it's because the PATH was wrong so it couldn't access it? But I've never worked with these before so I don't know what I'm supposed to do. I've seen some people with the same problem but the solution doesn't seem to work.
I'm using:
python 3.10.8
windows 10
IDLE Shell 3.10.1
A:
Welcome to Stack Overflow!
Try installing with pip3
pip3 install opencv-python
|
Import cv2 error but opencv-python is already installed
|
I've been trying to make a project with opencv, so I followed the YouTube video (It's in python), the video told me to go to cmd (win10) and use the command "pip install opencv-python" so that I can use the command import cv2. But the problem is after I did everything it still gave me an error.
I've done some research on it and nothing seem to work. I tried restarting my laptop or reinstall opencv, but nothing works for me. I'm thinking maybe it's because the PATH was wrong so it couldn't access it? But I've never worked with these before so I don't know what I'm supposed to do. I've seen some people with the same problem but the solution doesn't seem to work.
I'm using:
python 3.10.8
windows 10
IDLE Shell 3.10.1
|
[
"Welcome to Stack Overflow!\nTry installing with pip3\npip3 install opencv-python\n\n"
] |
[
0
] |
[] |
[] |
[
"cv2",
"pip",
"python"
] |
stackoverflow_0074526949_cv2_pip_python.txt
|
Q:
creating and visualizing spacy spans
I have a problem visualizing manually created spans in spacy:
given the simple code:
from spacy.tokens import Span
text = "Welcome to the Bank of China. "
nlp = spacy.blank("en")
doc = nlp(text)
doc.spans["xx"] = [Span(doc, 0, 1, "ORG")]
doc.spans["sc"] = [
Span(doc, 3, 6, "ORG"),
Span(doc, 5, 6, "GPE"),
Span(doc, 2, 4, "welcome")
]
the following visualizer works:
displacy.render(doc, style="span")
but if the spans do not contain the key "SC" it does not work
The error is key error "sc"
What is the problem there? why is the rendering not showing me all the spans?
The code giving the error is:
doc.spans["xx"] = [
Span(doc, 3, 6, "ORG"),
Span(doc, 5, 6, "GPE"),
Span(doc, 2, 4, "welcome")
]
displacy.render(doc, style="span", options ={"spans_key":"xx"})
A:
As explained in the displaCy documentation, by default the spans in the key "sc" are used. You can change it with the spans_key parameter.
render doesn't take spans_key correctly, you have to include it in options.
From the docs, modified to use render instead of serve:
doc.spans["custom"] = [Span(doc, 3, 6, "BANK")]
options = {"spans_key": "custom"}
displacy.render(doc, style="span", options=options)
|
creating and visualizing spacy spans
|
I have a problem visualizing manually created spans in spacy:
given the simple code:
from spacy.tokens import Span
text = "Welcome to the Bank of China. "
nlp = spacy.blank("en")
doc = nlp(text)
doc.spans["xx"] = [Span(doc, 0, 1, "ORG")]
doc.spans["sc"] = [
Span(doc, 3, 6, "ORG"),
Span(doc, 5, 6, "GPE"),
Span(doc, 2, 4, "welcome")
]
the following visualizer works:
displacy.render(doc, style="span")
but if the spans do not contain the key "SC" it does not work
The error is key error "sc"
What is the problem there? why is the rendering not showing me all the spans?
The code giving the error is:
doc.spans["xx"] = [
Span(doc, 3, 6, "ORG"),
Span(doc, 5, 6, "GPE"),
Span(doc, 2, 4, "welcome")
]
displacy.render(doc, style="span", options ={"spans_key":"xx"})
|
[
"As explained in the displaCy documentation, by default the spans in the key \"sc\" are used. You can change it with the spans_key parameter.\nrender doesn't take spans_key correctly, you have to include it in options.\nFrom the docs, modified to use render instead of serve:\ndoc.spans[\"custom\"] = [Span(doc, 3, 6, \"BANK\")]\noptions = {\"spans_key\": \"custom\"}\ndisplacy.render(doc, style=\"span\", options=options)\n\n"
] |
[
1
] |
[] |
[] |
[
"python",
"spacy"
] |
stackoverflow_0074522493_python_spacy.txt
|
Q:
How can I rewrite the line of code "asd" == "qwe" in order to have TRUE be displayed in the Terminal?
I am guessing there is an ASCII related explanation to this that I am trying to find out more about.
I was thinking of assigning a numeric value .
A:
Simply print its negatin:
print("asd" != "qwe")
or:
print(not ("asd" == "qwe"))
|
How can I rewrite the line of code "asd" == "qwe" in order to have TRUE be displayed in the Terminal?
|
I am guessing there is an ASCII related explanation to this that I am trying to find out more about.
I was thinking of assigning a numeric value .
|
[
"Simply print its negatin:\nprint(\"asd\" != \"qwe\")\n\nor:\nprint(not (\"asd\" == \"qwe\"))\n\n"
] |
[
1
] |
[] |
[] |
[
"boolean",
"pycharm",
"python"
] |
stackoverflow_0074527332_boolean_pycharm_python.txt
|
Q:
How to measure the time a script is running despite system time changes?
I'm developing a timeout functionality for an embedded device where the system time is updated via gps. This means I can't just compare two timestamps to get the elapsed time:
import time
t1 = time.time()
# system time change, e.g. from 1970-01-01 to 2022-11-10
t2 = time.time()
elapsed = t2 - t1 # this is now wrong!
Is getting the real elapsed time even possible in this case?
A:
Using time.perf_counter()
>>> wrong = time.time()
>>> right = time.perf_counter()
>>> # set clock back to correct time
>>> time.time() - wrong
1420070455.9668648
>>> time.perf_counter() - right
42.46595245699996
A:
This might work
https://docs.python.org/3/library/time.html#time.monotonic
Return the value (in fractional seconds) of a monotonic clock, i.e. a clock that cannot go backwards. The clock is not affected by system clock updates. The reference point of the returned value is undefined, so that only the difference between the results of two calls is valid.
A:
You can use the time.monotonic(). This is unaffected by system time change. This return response in float. If you want time difference in nanosecond, you can use time.monotonic_ns().
import time
t1 = time.monotonic()
t2 = time.monotonic()
elapsed = t2 - t1
Ref: You can read about it in detail over official doc: https://docs.python.org/3/library/time.html#:~:text=time.-,monotonic,-()%20%E2%86%92
A:
Leveraging CPU cycles and frequency to calculate elapsed time
Notes
This approach assumes the embedded device has no dynamic frequency scaling
Changes in timezone should not affect processing cycles
Get the CPU frequency (in Hz)
Count the number of CPU cycles required to complete the task
Divide the cycle count by the processor's clock speed (in Hz)
How to count CPU cycles?
hwcounter
See an example of how to use here
How to get CPU frequency?
See cpu_freq in psutil. Note the frequency example here
Example of how to use the above
#!/usr/bin/env python3
import psutil
from hwcounter import Timer
class Solution:
def getElapsedTime(self) -> float:
'''
Method to get elpased time of a task using cpu cycles
'''
max_freq = psutil.cpu_freq().max
print(f'CPU Max frequency: {max_freq} MHz')
# Get frequency in Hz = 1/second
max_freq_in_hz = max_freq * 10**6
with Timer() as t:
self.doTask()
print(f'Elapsed cycles: {t.cycles}')
print(f'Duration of task: {t.cycles / max_freq_in_hz} seconds')
def doTask(self):
sum = 0
for i in range(100):
sum += i
if __name__ == '__main__':
solution = Solution()
solution.getElapsedTime()
Output for a 5.3GHz CPU
CPU Max frequency: 5300.0 MHz
Elapsed cycles: 13238
Duration of task: 2.497735849056604e-06 seconds
|
How to measure the time a script is running despite system time changes?
|
I'm developing a timeout functionality for an embedded device where the system time is updated via gps. This means I can't just compare two timestamps to get the elapsed time:
import time
t1 = time.time()
# system time change, e.g. from 1970-01-01 to 2022-11-10
t2 = time.time()
elapsed = t2 - t1 # this is now wrong!
Is getting the real elapsed time even possible in this case?
|
[
"Using time.perf_counter()\n>>> wrong = time.time()\n>>> right = time.perf_counter()\n>>> # set clock back to correct time\n>>> time.time() - wrong\n1420070455.9668648\n>>> time.perf_counter() - right\n42.46595245699996\n\n",
"This might work\nhttps://docs.python.org/3/library/time.html#time.monotonic\n\nReturn the value (in fractional seconds) of a monotonic clock, i.e. a clock that cannot go backwards. The clock is not affected by system clock updates. The reference point of the returned value is undefined, so that only the difference between the results of two calls is valid.\n\n",
"You can use the time.monotonic(). This is unaffected by system time change. This return response in float. If you want time difference in nanosecond, you can use time.monotonic_ns().\nimport time\nt1 = time.monotonic()\nt2 = time.monotonic()\nelapsed = t2 - t1 \n\nRef: You can read about it in detail over official doc: https://docs.python.org/3/library/time.html#:~:text=time.-,monotonic,-()%20%E2%86%92\n",
"Leveraging CPU cycles and frequency to calculate elapsed time\n\nNotes\n\nThis approach assumes the embedded device has no dynamic frequency scaling\nChanges in timezone should not affect processing cycles\n\n\n\nGet the CPU frequency (in Hz)\nCount the number of CPU cycles required to complete the task\nDivide the cycle count by the processor's clock speed (in Hz)\n\nHow to count CPU cycles?\nhwcounter\nSee an example of how to use here\nHow to get CPU frequency?\nSee cpu_freq in psutil. Note the frequency example here\nExample of how to use the above\n#!/usr/bin/env python3\n\nimport psutil\nfrom hwcounter import Timer\n\nclass Solution:\n def getElapsedTime(self) -> float:\n '''\n Method to get elpased time of a task using cpu cycles\n '''\n max_freq = psutil.cpu_freq().max\n print(f'CPU Max frequency: {max_freq} MHz')\n\n # Get frequency in Hz = 1/second\n max_freq_in_hz = max_freq * 10**6\n\n with Timer() as t:\n self.doTask()\n\n print(f'Elapsed cycles: {t.cycles}')\n print(f'Duration of task: {t.cycles / max_freq_in_hz} seconds')\n\n def doTask(self):\n sum = 0\n for i in range(100):\n sum += i\n\nif __name__ == '__main__':\n solution = Solution()\n solution.getElapsedTime()\n\nOutput for a 5.3GHz CPU\nCPU Max frequency: 5300.0 MHz\nElapsed cycles: 13238\nDuration of task: 2.497735849056604e-06 seconds\n\n"
] |
[
2,
1,
1,
0
] |
[] |
[] |
[
"python",
"time"
] |
stackoverflow_0074400978_python_time.txt
|
Q:
Tracking claims using date/timestamp columns and creating a final count using pandas
I have an issue where I need to track the progression of patients insurance claim statuses based on the dates of those statuses. I also need to create a count of status based on certain conditions.
DF:
ClaimID
New
Accepted
Denied
Pending
Expired
Group
001
2021-01-01T09:58:35:335Z
2021-01-01T10:05:43:000Z
A
002
2021-01-01T06:30:30:000Z
2021-03-01T04:11:45:000Z
2021-03-01T04:11:53:000Z
A
003
2021-02-14T14:23:54:154Z
2021-02-15T11:11:56:000Z
2021-02-15T11:15:00:000Z
A
004
2021-02-14T15:36:05:335Z
2021-02-14T17:15:30:000Z
A
005
2021-02-14T15:56:59:009Z
2021-03-01T10:05:43:000Z
A
In the above dataset, we have 6 columns. ClaimID is simple and just indicates the ID of the claim. New, Accepted, Denied, Pending, and Expired indicate the status of the claim and the day/time those statuses were set.
What I need to do is get a count of how many claims are New on each day and how many move out of new into a new status. For example, There are 2 new claims on 2021-01-01. On that same day 1 moved to Accepted about 7 minutes later. Thus on 2021-01-01 the table of counts would read:
DF_Count:
Date
New
Accepted
Denied
Pending
Expired
2021-01-01
2
1
0
0
0
2021-01-02
1
0
0
0
0
2021-01-03
1
0
0
0
0
2021-01-04
1
0
0
0
0
2021-01-05
1
0
0
0
0
....
....
....
....
....
....
2021-02-14
4
2
0
0
0
2021-02-15
2
3
0
0
1
2021-02-16
2
2
0
0
0
Few Conditions:
If a claim moves from one status to the other on the same day (even if they are a minutes/hours apart) it would not be subtracted from the original status until the next day. This can be seen on 2021-01-01 where claim 001 moves from new to accepted on the same day but the claim is not subtracted from new until 2021-01-02.
Until something happens to a claim, it should remain in its original status. Claim 002 will remain in new until 2021-03-01 when it is approved.
If a claim changes status on a later date than its original status, it will be subtracted on that later date. For this, see status 003. It is new on 2/14 but accepted on 2/15. This is why New goes down by 2 on 2/15 (the other claim is the is 004 which is new and accepted on the same day)
For certain statuses, I do not need to look at all columns. For example, For new I only look at the dates inside Accepted and Denied. Not Pending and Expired. When I do these same steps for approved, I no longer need to look at new, just the other columns. How would I do that?
In the final DF_count table, the dates should start from the earliest date in 'New' and end on todays date.
The code needs to be grouped by the Group Column as well. For example, patients in group B (not pictured) will have to have the same start and end date but for their own claims.
I need to do this separately for all of the statuses. Not just new.
Current Solution:
My current solution has been to create an dataset with just dates from the min New Date to todays date. Then for each column, what I do is use the .loc method to find dates that are greater than New in each of the other columns. For example, in the code below I look for all cases where new is equal to approved.
df1 = df.loc[(df['New'] == df['Approved']) &
((df['Expired'].isnull()) | (df['Expired'] >= df['Accepted'])) &
((df['Pending'].isnull()) | (df['Pending'] >= df['Accepted'])) &
((df['Denied'].isnull()) | (df['Denied'] >= df['Accepted']))]
newtoaccsday = df1.loc[:, ('Group', 'Accepted')]
newtoappsday['Date'] = newtoappsday['Accepted']
newtoappsday = newtoappsday.reset_index(drop = True)
newtoappsday= newtoappsday.groupby(['Date', 'Group'], as_index = False)['Approved'].value_counts()
newtoappsday.drop(columns = {'Accepted'}, inplace = True)
newtoappsday.rename(columns = {'count': 'NewAppSDay'}, inplace = True)
newtoappsday['Date'] = newtoappsday['Date'] + timedelta(1)
df_count= df_count.merge(newtoappsday, how = 'left', on = ['Date', 'Group']).fillna(0)
--After doing the above steps for all conditions (where new goes to accepted on a later date etc.) I will do the final calculation for new:
df_count['New'] = df_count.eval('New = New - (NewAccSDay + NewAccLater + NewDenSDay + NewDenLater + NewExpLater + NewPendSDay + NewPendLater)').groupby(['Tier2_ID', 'ClaimType'])['New'].cumsum()
Any and all help would be greatly appreciated. My method above is extremely inefficient and leading to some errors. Do I need to write a for loop for this? What is the best way to go about this.
A:
First convert the date columns with something like
for i in ['New', 'Accepted', 'Denied', 'Pending', 'Expired']:
df[i] = pd.to_datetime(df[i], format="%Y-%m-%dT%H:%M:%S:%f%z")
Then develop the date range applicable based on your column conditions. In this logic if Denied is there the range is new --> denied, or if accepted new --> accepted or if no acceptance new --> today with code like (alter as per rules):
df['new_range'] = df[['New','Accepted','Denied']].apply (lambda x: pd.date_range(x['New'],x['Denied']).date.tolist() if
pd.notnull(x['Denied']) else
pd.date_range(x['New'],x['Accepted']).date.tolist() if
pd.notnull(x['Accepted']) else
pd.date_range(x['New'],datetime.today()).date.tolist()
,axis=1)
You should be able filter on a group and see date ranges in your df like:
df[df['Group']=='A']['new_range']
0 [2021-01-01]
1 [2021-01-01, 2021-01-02, 2021-01-03, 2021-01-0...
2 [2021-02-14]
3 [2021-02-14]
4 [2021-02-14, 2021-02-15, 2021-02-16, 2021-02-1..
Then you can explode the date ranges and group on counts to get the new counts for each day with code like:
new = pd.to_datetime(df[df['Group']=='A']['new_range'].explode('Date')).reset_index()
newc = new.groupby('new_range').count()
newc
new_range
2021-01-01 2
2021-01-02 1
2021-01-03 1
2021-01-04 1
2021-01-05 1
2021-01-06 1...
Similarly get counts for accepted, denied and then left joined on date to arrive at final table, fill na to 0.
By creating your rules to expand your date range, then explode over date range and groupby to get your counts you should be able to avoid much of the expensive operation.
A:
I think this is what you want or can be easily modified to your necesity:
import pandas as pd
import numpy as np
from datetime import timedelta
from datetime import date
def dateRange(d1,d2):
return [d1 + timedelta(days=x) for x in range((d2-d1).days)]
def addCount(dic,group,dat,cat):
if group not in dic:
dic[group]={}
if dat not in dic[group]:
dic[group][dat]={}
if cat not in dic[group][dat]:
dic[group][dat][cat]=0
dic[group][dat][cat]+=1
df =pd.read_csv("testdf.csv",
parse_dates=["New","Accepted","Denied","Pending", "Expired"])#,
cdic={}
for i,row in df.iterrows():
cid=row["ClaimID"]
dnew=row["New"].date()
dacc=row["Accepted"].date()
dden=row["Denied"].date()
dpen=row["Pending"].date()
dexp=row["Expired"].date()
group=row["Group"]
if not pd.isna(dacc): #Claim has been accepted
if(dnew == dacc):
dacc+=timedelta(days=1)
nend=dacc
addCount(cdic,group,dacc,"acc")
if not pd.isna(dden): # Claim has been denied
if(dnew == dden):
dden+=timedelta(days=1)
if pd.isna(dacc):
nend=dden
addCount(cdic,group,dden,"den")
if not pd.isna(dpen):
addCount(cdic,group,dpen,"pen") # Claim is pending
if not pd.isna(dexp):
addCount(cdic,group,dexp,"exp") # Claim is expired
if pd.isna(dacc) and pd.isna(dden):
nend=date.today()+timedelta(days+1)
for d in dateRange(dnew,nend): # Fill new status until first change
addCount(cdic,group,d,"new")
ndfl=[]
for group in cdic:
for dat in sorted(cdic[group].keys()):
r=cdic[group][dat]
ndfl.append([group,dat,r.get("new",0),r.get("acc",0),
r.get("den",0),r.get("pen",0),r.get("exp",0)])
ndf=pd.DataFrame(ndfl,columns=["Group", "Date","New","Accepted","Denied","Pending","Expired"])
|
Tracking claims using date/timestamp columns and creating a final count using pandas
|
I have an issue where I need to track the progression of patients insurance claim statuses based on the dates of those statuses. I also need to create a count of status based on certain conditions.
DF:
ClaimID
New
Accepted
Denied
Pending
Expired
Group
001
2021-01-01T09:58:35:335Z
2021-01-01T10:05:43:000Z
A
002
2021-01-01T06:30:30:000Z
2021-03-01T04:11:45:000Z
2021-03-01T04:11:53:000Z
A
003
2021-02-14T14:23:54:154Z
2021-02-15T11:11:56:000Z
2021-02-15T11:15:00:000Z
A
004
2021-02-14T15:36:05:335Z
2021-02-14T17:15:30:000Z
A
005
2021-02-14T15:56:59:009Z
2021-03-01T10:05:43:000Z
A
In the above dataset, we have 6 columns. ClaimID is simple and just indicates the ID of the claim. New, Accepted, Denied, Pending, and Expired indicate the status of the claim and the day/time those statuses were set.
What I need to do is get a count of how many claims are New on each day and how many move out of new into a new status. For example, There are 2 new claims on 2021-01-01. On that same day 1 moved to Accepted about 7 minutes later. Thus on 2021-01-01 the table of counts would read:
DF_Count:
Date
New
Accepted
Denied
Pending
Expired
2021-01-01
2
1
0
0
0
2021-01-02
1
0
0
0
0
2021-01-03
1
0
0
0
0
2021-01-04
1
0
0
0
0
2021-01-05
1
0
0
0
0
....
....
....
....
....
....
2021-02-14
4
2
0
0
0
2021-02-15
2
3
0
0
1
2021-02-16
2
2
0
0
0
Few Conditions:
If a claim moves from one status to the other on the same day (even if they are a minutes/hours apart) it would not be subtracted from the original status until the next day. This can be seen on 2021-01-01 where claim 001 moves from new to accepted on the same day but the claim is not subtracted from new until 2021-01-02.
Until something happens to a claim, it should remain in its original status. Claim 002 will remain in new until 2021-03-01 when it is approved.
If a claim changes status on a later date than its original status, it will be subtracted on that later date. For this, see status 003. It is new on 2/14 but accepted on 2/15. This is why New goes down by 2 on 2/15 (the other claim is the is 004 which is new and accepted on the same day)
For certain statuses, I do not need to look at all columns. For example, For new I only look at the dates inside Accepted and Denied. Not Pending and Expired. When I do these same steps for approved, I no longer need to look at new, just the other columns. How would I do that?
In the final DF_count table, the dates should start from the earliest date in 'New' and end on todays date.
The code needs to be grouped by the Group Column as well. For example, patients in group B (not pictured) will have to have the same start and end date but for their own claims.
I need to do this separately for all of the statuses. Not just new.
Current Solution:
My current solution has been to create an dataset with just dates from the min New Date to todays date. Then for each column, what I do is use the .loc method to find dates that are greater than New in each of the other columns. For example, in the code below I look for all cases where new is equal to approved.
df1 = df.loc[(df['New'] == df['Approved']) &
((df['Expired'].isnull()) | (df['Expired'] >= df['Accepted'])) &
((df['Pending'].isnull()) | (df['Pending'] >= df['Accepted'])) &
((df['Denied'].isnull()) | (df['Denied'] >= df['Accepted']))]
newtoaccsday = df1.loc[:, ('Group', 'Accepted')]
newtoappsday['Date'] = newtoappsday['Accepted']
newtoappsday = newtoappsday.reset_index(drop = True)
newtoappsday= newtoappsday.groupby(['Date', 'Group'], as_index = False)['Approved'].value_counts()
newtoappsday.drop(columns = {'Accepted'}, inplace = True)
newtoappsday.rename(columns = {'count': 'NewAppSDay'}, inplace = True)
newtoappsday['Date'] = newtoappsday['Date'] + timedelta(1)
df_count= df_count.merge(newtoappsday, how = 'left', on = ['Date', 'Group']).fillna(0)
--After doing the above steps for all conditions (where new goes to accepted on a later date etc.) I will do the final calculation for new:
df_count['New'] = df_count.eval('New = New - (NewAccSDay + NewAccLater + NewDenSDay + NewDenLater + NewExpLater + NewPendSDay + NewPendLater)').groupby(['Tier2_ID', 'ClaimType'])['New'].cumsum()
Any and all help would be greatly appreciated. My method above is extremely inefficient and leading to some errors. Do I need to write a for loop for this? What is the best way to go about this.
|
[
"First convert the date columns with something like\nfor i in ['New', 'Accepted', 'Denied', 'Pending', 'Expired']:\n df[i] = pd.to_datetime(df[i], format=\"%Y-%m-%dT%H:%M:%S:%f%z\")\n\nThen develop the date range applicable based on your column conditions. In this logic if Denied is there the range is new --> denied, or if accepted new --> accepted or if no acceptance new --> today with code like (alter as per rules):\ndf['new_range'] = df[['New','Accepted','Denied']].apply (lambda x: pd.date_range(x['New'],x['Denied']).date.tolist() if \n pd.notnull(x['Denied']) else \n pd.date_range(x['New'],x['Accepted']).date.tolist() if \n pd.notnull(x['Accepted']) else\n pd.date_range(x['New'],datetime.today()).date.tolist()\n ,axis=1)\n\nYou should be able filter on a group and see date ranges in your df like:\n df[df['Group']=='A']['new_range']\n0 [2021-01-01]\n1 [2021-01-01, 2021-01-02, 2021-01-03, 2021-01-0...\n2 [2021-02-14]\n3 [2021-02-14]\n4 [2021-02-14, 2021-02-15, 2021-02-16, 2021-02-1..\n\nThen you can explode the date ranges and group on counts to get the new counts for each day with code like:\n new = pd.to_datetime(df[df['Group']=='A']['new_range'].explode('Date')).reset_index()\n \n newc = new.groupby('new_range').count()\n newc\n\nnew_range\n2021-01-01 2\n2021-01-02 1\n2021-01-03 1\n2021-01-04 1\n2021-01-05 1\n2021-01-06 1...\n\nSimilarly get counts for accepted, denied and then left joined on date to arrive at final table, fill na to 0.\nBy creating your rules to expand your date range, then explode over date range and groupby to get your counts you should be able to avoid much of the expensive operation.\n",
"I think this is what you want or can be easily modified to your necesity:\nimport pandas as pd\nimport numpy as np\nfrom datetime import timedelta\nfrom datetime import date\n\ndef dateRange(d1,d2):\n return [d1 + timedelta(days=x) for x in range((d2-d1).days)]\n \ndef addCount(dic,group,dat,cat):\n if group not in dic:\n dic[group]={}\n if dat not in dic[group]:\n dic[group][dat]={}\n if cat not in dic[group][dat]:\n dic[group][dat][cat]=0\n dic[group][dat][cat]+=1\n \ndf =pd.read_csv(\"testdf.csv\",\n parse_dates=[\"New\",\"Accepted\",\"Denied\",\"Pending\", \"Expired\"])#,\n\ncdic={}\nfor i,row in df.iterrows():\n cid=row[\"ClaimID\"]\n dnew=row[\"New\"].date()\n dacc=row[\"Accepted\"].date()\n dden=row[\"Denied\"].date()\n dpen=row[\"Pending\"].date()\n dexp=row[\"Expired\"].date()\n group=row[\"Group\"]\n \n if not pd.isna(dacc): #Claim has been accepted\n if(dnew == dacc):\n dacc+=timedelta(days=1)\n nend=dacc\n addCount(cdic,group,dacc,\"acc\")\n if not pd.isna(dden): # Claim has been denied\n if(dnew == dden):\n dden+=timedelta(days=1)\n if pd.isna(dacc):\n nend=dden\n addCount(cdic,group,dden,\"den\")\n if not pd.isna(dpen):\n addCount(cdic,group,dpen,\"pen\") # Claim is pending\n if not pd.isna(dexp):\n addCount(cdic,group,dexp,\"exp\") # Claim is expired\n if pd.isna(dacc) and pd.isna(dden):\n nend=date.today()+timedelta(days+1)\n for d in dateRange(dnew,nend): # Fill new status until first change\n addCount(cdic,group,d,\"new\")\nndfl=[] \nfor group in cdic:\n for dat in sorted(cdic[group].keys()):\n r=cdic[group][dat]\n ndfl.append([group,dat,r.get(\"new\",0),r.get(\"acc\",0),\n r.get(\"den\",0),r.get(\"pen\",0),r.get(\"exp\",0)])\nndf=pd.DataFrame(ndfl,columns=[\"Group\", \"Date\",\"New\",\"Accepted\",\"Denied\",\"Pending\",\"Expired\"])\n\n\n"
] |
[
2,
1
] |
[] |
[] |
[
"datetime",
"for_loop",
"pandas",
"python"
] |
stackoverflow_0074479890_datetime_for_loop_pandas_python.txt
|
Q:
When generating texts in JSON, accented characters look different
I am having problems with a code created in Python, and it is that when I generate some texts in json, the accents are not appreciated.
This is the code I'm using:
import requests
url = requests.get(f"https://images.habbo.com/habbo-web-news/es/production/front.json")
summary = url.json()[0]['summary']
print(summary)
This is the text that generates me:
Nos estamos preparando para esos fríos meses de invierno con unos merecidos mimos en el Onsen japonés.
I am having problems with a code created in Python, and it is that when I generate some texts in json, the accents are not appreciated.
Someone could help me?
A:
JSON is always in unicode.
So you want utf8 encoding everywhere.
The url you mentioned sends this (correct) header:
content-type: application/json
Here is a snippet of the content:
"content": "<h2>Invierno en el Onsen Japonés</h2>\r\n<p>Hey Habbo, tus píxeles estaban rozando el estado de congelación perpetuo....
There's nothing wrong with the webserver,
nor with the code you posted.
We do see some hex escapes that apparently you don't want:
é é
í í
ó ó
You're unhappy with the component that introduced
those hex escapes.
Find it and fix it.
tl;dr: You have bad data. Fix the data, not the code you posted.
|
When generating texts in JSON, accented characters look different
|
I am having problems with a code created in Python, and it is that when I generate some texts in json, the accents are not appreciated.
This is the code I'm using:
import requests
url = requests.get(f"https://images.habbo.com/habbo-web-news/es/production/front.json")
summary = url.json()[0]['summary']
print(summary)
This is the text that generates me:
Nos estamos preparando para esos fríos meses de invierno con unos merecidos mimos en el Onsen japonés.
I am having problems with a code created in Python, and it is that when I generate some texts in json, the accents are not appreciated.
Someone could help me?
|
[
"JSON is always in unicode.\nSo you want utf8 encoding everywhere.\nThe url you mentioned sends this (correct) header:\ncontent-type: application/json\n\nHere is a snippet of the content:\n\"content\": \"<h2>Invierno en el Onsen Japonés</h2>\\r\\n<p>Hey Habbo, tus píxeles estaban rozando el estado de congelación perpetuo....\n\nThere's nothing wrong with the webserver,\nnor with the code you posted.\nWe do see some hex escapes that apparently you don't want:\n\né é\ní í\nó ó\n\nYou're unhappy with the component that introduced\nthose hex escapes.\nFind it and fix it.\ntl;dr: You have bad data. Fix the data, not the code you posted.\n"
] |
[
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0074526390_python.txt
|
Q:
Letter frequency for loop in Python
Hey can anyone help me here
I'm supposed to get a number count for each letter used in this string here using for loops and if statement.
quote= "I watched in awe as I saw her swim across the ocean"
The pseudocode given is this:
for every letter in the alphabet list:
Create a variable to store the frequency of each letter in the string and assign it an initial value of zero
for every letter in the given string:
if the letter in the string is the same as the letter in the alphabet list
increase the value of the frequency variable by one.
if the value of the frequency variable does not equal zero:
print the letter in the alphabet list followed by a colon and the value of the frequency variable
This is what i've got so far but i cannot for the life of me figure it out.
quote = "I watched in awe as I saw her swim across the ocean."
xquote= quote.lower()
print(xquote)
alphabet= ["a", "b", "c", "d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
for i in alphabet:
c_alphabet= {"a": 0, "b":0, "c":0, "d":0,"e":0,"f":0,"g":0,"h":0,"i":0,"j":0,"k":0,"l":0,"m":0,"n":0,"o":0,"p":0,"q":0,"r":0,"s":0,"t":0,"u":0,"v":0,"w":0,"x":0,"y":0,"z":0}
for i in xquote:
if i == alphabet:
c_alphabet[i]+=1
print(c_alphabet)
I don't get an error message but I just can't seem to be able to get a total number of individual letters in the string.
I'd like it to output some thing like this c_alphabet = {"a": 3, "b":1, "c": 2...)
A:
There are more eloquent ways to do this, but using your algorithm, the problem is that you're mixing up variables. You're comparing i to alphabet, shadowing the variable i, and redefining c_alphabet in every top-level loop. See the changes here:
quote = "I watched in awe as I saw her swim across the ocean."
xquote = quote.lower()
alphabet = [ "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" ]
# moved out of loop
c_alphabet = { "a": 0, "b": 0, "c": 0, "d": 0, "e": 0, "f": 0, "g": 0, "h": 0, "i": 0, "j": 0, "k": 0, "l": 0, "m": 0, "n": 0, "o": 0, "p": 0, "q": 0, "r": 0, "s": 0, "t": 0, "u": 0, "v": 0, "w": 0, "x": 0, "y": 0, "z": 0 }
for i in alphabet:
for j in xquote: # changed variable name
if i == j: # changed comparison
c_alphabet[i] += 1
print(c_alphabet)
A much more concise version would be:
# lowercase, filter to only alphanumeric characters, and then sort that
formatted = sorted(filter(str.isalnum, quote.lower()))
# build the dict
count_dict = {a: formatted.count(a) for a in formatted}
print(count_dict)
A:
The strings library has the lowercase alphabet is you're allowed to use it. I believe this is true to the pseudo code, with the exception that the keys of the count dictionary are used instead of a list. This example also prints the non-zero letter frequencies as required.
import string
quote = "I watched in awe as I saw her swim across the ocean."
count = {letter:0 for letter in string.ascii_lowercase}
for letter in quote.lower():
if letter in count:
count[letter]+=1
print(*(f'{letter}: {freq}' for letter, freq in count.items() if freq != 0), sep=", ")
A:
The best answer is usually the simplest one
from collections import Counter
Counter(quote.lower())
|
Letter frequency for loop in Python
|
Hey can anyone help me here
I'm supposed to get a number count for each letter used in this string here using for loops and if statement.
quote= "I watched in awe as I saw her swim across the ocean"
The pseudocode given is this:
for every letter in the alphabet list:
Create a variable to store the frequency of each letter in the string and assign it an initial value of zero
for every letter in the given string:
if the letter in the string is the same as the letter in the alphabet list
increase the value of the frequency variable by one.
if the value of the frequency variable does not equal zero:
print the letter in the alphabet list followed by a colon and the value of the frequency variable
This is what i've got so far but i cannot for the life of me figure it out.
quote = "I watched in awe as I saw her swim across the ocean."
xquote= quote.lower()
print(xquote)
alphabet= ["a", "b", "c", "d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
for i in alphabet:
c_alphabet= {"a": 0, "b":0, "c":0, "d":0,"e":0,"f":0,"g":0,"h":0,"i":0,"j":0,"k":0,"l":0,"m":0,"n":0,"o":0,"p":0,"q":0,"r":0,"s":0,"t":0,"u":0,"v":0,"w":0,"x":0,"y":0,"z":0}
for i in xquote:
if i == alphabet:
c_alphabet[i]+=1
print(c_alphabet)
I don't get an error message but I just can't seem to be able to get a total number of individual letters in the string.
I'd like it to output some thing like this c_alphabet = {"a": 3, "b":1, "c": 2...)
|
[
"There are more eloquent ways to do this, but using your algorithm, the problem is that you're mixing up variables. You're comparing i to alphabet, shadowing the variable i, and redefining c_alphabet in every top-level loop. See the changes here:\nquote = \"I watched in awe as I saw her swim across the ocean.\"\nxquote = quote.lower()\n\nalphabet = [ \"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\", \"j\", \"k\", \"l\", \"m\", \"n\", \"o\", \"p\", \"q\", \"r\", \"s\", \"t\", \"u\", \"v\", \"w\", \"x\", \"y\", \"z\" ]\n\n# moved out of loop\nc_alphabet = { \"a\": 0, \"b\": 0, \"c\": 0, \"d\": 0, \"e\": 0, \"f\": 0, \"g\": 0, \"h\": 0, \"i\": 0, \"j\": 0, \"k\": 0, \"l\": 0, \"m\": 0, \"n\": 0, \"o\": 0, \"p\": 0, \"q\": 0, \"r\": 0, \"s\": 0, \"t\": 0, \"u\": 0, \"v\": 0, \"w\": 0, \"x\": 0, \"y\": 0, \"z\": 0 }\n\nfor i in alphabet:\n for j in xquote: # changed variable name\n if i == j: # changed comparison\n c_alphabet[i] += 1\n\nprint(c_alphabet)\n\nA much more concise version would be:\n# lowercase, filter to only alphanumeric characters, and then sort that\nformatted = sorted(filter(str.isalnum, quote.lower()))\n# build the dict\ncount_dict = {a: formatted.count(a) for a in formatted}\nprint(count_dict)\n\n",
"The strings library has the lowercase alphabet is you're allowed to use it. I believe this is true to the pseudo code, with the exception that the keys of the count dictionary are used instead of a list. This example also prints the non-zero letter frequencies as required.\nimport string\nquote = \"I watched in awe as I saw her swim across the ocean.\"\ncount = {letter:0 for letter in string.ascii_lowercase}\nfor letter in quote.lower():\n if letter in count:\n count[letter]+=1\n\nprint(*(f'{letter}: {freq}' for letter, freq in count.items() if freq != 0), sep=\", \")\n\n",
"The best answer is usually the simplest one\nfrom collections import Counter\nCounter(quote.lower())\n\n"
] |
[
0,
0,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0074527290_python.txt
|
Q:
Python timeit ImportError
I am trying to compute the time my program takes to execute but sometimes it works fine and sometimes I get the following error:
ImportError: cannot import name 'N' from '__main__'
N = number
t = timeit.Timer(
"computeArea(N, 4)",
"from __main__ import computeArea, N")
computeTime = t.timeit(1)
print(computeTime)
A:
What do you think of just importing time and measuring the time before and after computeArea runs? Honestly speaking, this chunk of code looks pretty funky from a Python style perspective. Measuring the time yourself is easy, and can be easily modified for more interesting examples (say, taking the average time by timing the same code dozens of times).
import time
start_time = time.time()
# Do anything here. This is a filler.
for i in range(100):
print(i)
end_time = time.time()
total_time = end_time - start_time
print(f"Program took {total_time} seconds.")
|
Python timeit ImportError
|
I am trying to compute the time my program takes to execute but sometimes it works fine and sometimes I get the following error:
ImportError: cannot import name 'N' from '__main__'
N = number
t = timeit.Timer(
"computeArea(N, 4)",
"from __main__ import computeArea, N")
computeTime = t.timeit(1)
print(computeTime)
|
[
"What do you think of just importing time and measuring the time before and after computeArea runs? Honestly speaking, this chunk of code looks pretty funky from a Python style perspective. Measuring the time yourself is easy, and can be easily modified for more interesting examples (say, taking the average time by timing the same code dozens of times).\nimport time\n\nstart_time = time.time()\n\n# Do anything here. This is a filler.\nfor i in range(100):\n print(i)\n\nend_time = time.time()\ntotal_time = end_time - start_time\n\nprint(f\"Program took {total_time} seconds.\")\n\n"
] |
[
0
] |
[] |
[] |
[
"python",
"timeit"
] |
stackoverflow_0074527223_python_timeit.txt
|
Q:
How to access a value inside a value in a python dictionary
Im having a small concern if we can access a value inside a value.
Eg:
myDict = {1:"Hey", 2:"Bye,1,2,3,4"}
As in the example above..
How can I print/access the value 4 in myDict?? Is it possible with indexing??
Eg: 4 # Printing 4 from myDict
Thanks.
A:
For this you need to convert string into array by dividing it by comma ",".
Access 2nd element: result = myDict[1]
Divide it by comma: result = result.split(",")
Access element: ans = result[4]
myDict = {1:"Hey", 2:"Bye,1,2,3,4"}
result = myDict[1].split(",")
ans = result[4]
print(ans)
A:
Or make a one line loop:
value = [i for i in myDict[2].split(',') if i == '4'][0]
|
How to access a value inside a value in a python dictionary
|
Im having a small concern if we can access a value inside a value.
Eg:
myDict = {1:"Hey", 2:"Bye,1,2,3,4"}
As in the example above..
How can I print/access the value 4 in myDict?? Is it possible with indexing??
Eg: 4 # Printing 4 from myDict
Thanks.
|
[
"For this you need to convert string into array by dividing it by comma \",\".\n\nAccess 2nd element: result = myDict[1]\nDivide it by comma: result = result.split(\",\")\nAccess element: ans = result[4]\n\nmyDict = {1:\"Hey\", 2:\"Bye,1,2,3,4\"}\nresult = myDict[1].split(\",\")\nans = result[4]\nprint(ans)\n\n\n",
"Or make a one line loop:\nvalue = [i for i in myDict[2].split(',') if i == '4'][0]\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"dictionary",
"python"
] |
stackoverflow_0074527369_dictionary_python.txt
|
Q:
What to do I want to access all [i] in every tuple inside a list or a dictionary (python)?
Let's say I have a dictionary called 'testdic' that looks like this.
testdic = {
[
( ('Jane','Sophomore','Science'), (4.0,3.5,3.2) ),
( ('Kim','Junior','Business'), (3.2,2.8,4.0) ),
( ('Jack','Senior','Music'), (3.0,4.0,3.0) )
]
}
And I need to pull all the [2] of the key together to get a list that look like 'Science','Business','Music'. How would I do that?
I know that I should turn testdic into a list. So I wrote test.list = list(testdic.keys()). But then what?
I actually need to write this into a function that would take two variables; the name of the dictionary, and the index. For example, if I want to pull the names into a list. I should be able to write list(functionname(testdic,0))
I did some google search and found a code below.
def select(dic, ind):
if(type(dic) is dict):
if (ind == 0):
return dic.key()
elif(ind == 1):
return dic.values()
else:
dic=list(dic)
return [i[ind] for i in dic]
It executed. But when I tried list(select(testdic,keys(),2)), nothing comes up.
Any tips, suggestion would be helpful.
Thank you!!
A:
You wrote a list of unhashable type.
To solve this error, ensure you only assign a hashable object, such as a string or a tuple, as a key for a dictionary.
testdic = {(('Jane','Sophomore','Science'), (4.0,3.5,3.2)),
(('Kim','Junior','Business'), (3.2,2.8,4.0)),
(('Jack','Senior','Music'), (3.0,4.0,3.0))}
So you have to write (for 'Science','Business','Music')
for value in testdic:
print(value[0][2])
|
What to do I want to access all [i] in every tuple inside a list or a dictionary (python)?
|
Let's say I have a dictionary called 'testdic' that looks like this.
testdic = {
[
( ('Jane','Sophomore','Science'), (4.0,3.5,3.2) ),
( ('Kim','Junior','Business'), (3.2,2.8,4.0) ),
( ('Jack','Senior','Music'), (3.0,4.0,3.0) )
]
}
And I need to pull all the [2] of the key together to get a list that look like 'Science','Business','Music'. How would I do that?
I know that I should turn testdic into a list. So I wrote test.list = list(testdic.keys()). But then what?
I actually need to write this into a function that would take two variables; the name of the dictionary, and the index. For example, if I want to pull the names into a list. I should be able to write list(functionname(testdic,0))
I did some google search and found a code below.
def select(dic, ind):
if(type(dic) is dict):
if (ind == 0):
return dic.key()
elif(ind == 1):
return dic.values()
else:
dic=list(dic)
return [i[ind] for i in dic]
It executed. But when I tried list(select(testdic,keys(),2)), nothing comes up.
Any tips, suggestion would be helpful.
Thank you!!
|
[
"You wrote a list of unhashable type.\nTo solve this error, ensure you only assign a hashable object, such as a string or a tuple, as a key for a dictionary.\ntestdic = {(('Jane','Sophomore','Science'), (4.0,3.5,3.2)),\n\n(('Kim','Junior','Business'), (3.2,2.8,4.0)),\n\n(('Jack','Senior','Music'), (3.0,4.0,3.0))}\n\nSo you have to write (for 'Science','Business','Music')\nfor value in testdic:\n print(value[0][2])\n\n"
] |
[
0
] |
[] |
[] |
[
"python",
"spyder"
] |
stackoverflow_0074527317_python_spyder.txt
|
Q:
Azure function HTTP response type to make the API download a csv whenever get response called
new_csv = df.to_csv('sample.csv', index=False, encoding='utf-8')
return func.HttpResponse(new_csv, index=False, encoding='utf-8', mimetype='text/csv')
How can I pass the CSV file as a GET response to the func.HttpResponse in Azure functions, so that whenever the API is hit, the CSV file gets automatically downloaded as get response method.
with open(filename, 'rb') as f:
return func.HttpResponse(
body=f.read(),
mimetype='text/csv',
status_code=200
)
This piece of http response does the job of returning CSV_as_response but the file has to be statically present in the local system.
What I want is a json data -> CSV -> csv as response
A:
You can set the Content-Disposition header to attachment which forces browsers to download as a file instead of displaying the content.
|
Azure function HTTP response type to make the API download a csv whenever get response called
|
new_csv = df.to_csv('sample.csv', index=False, encoding='utf-8')
return func.HttpResponse(new_csv, index=False, encoding='utf-8', mimetype='text/csv')
How can I pass the CSV file as a GET response to the func.HttpResponse in Azure functions, so that whenever the API is hit, the CSV file gets automatically downloaded as get response method.
with open(filename, 'rb') as f:
return func.HttpResponse(
body=f.read(),
mimetype='text/csv',
status_code=200
)
This piece of http response does the job of returning CSV_as_response but the file has to be statically present in the local system.
What I want is a json data -> CSV -> csv as response
|
[
"You can set the Content-Disposition header to attachment which forces browsers to download as a file instead of displaying the content.\n"
] |
[
0
] |
[] |
[] |
[
"azure",
"azure_devops",
"azure_functions",
"function",
"python"
] |
stackoverflow_0072217126_azure_azure_devops_azure_functions_function_python.txt
|
Q:
How do you check if a variable references another declared object in Python?
Printing type of one variable just returns the pointed data's type
i = [5,6,7,8]
j = i
print(type(j))
<class 'list'>
and j references a mutable type. So
j[0] = 3
print(i)
print(j)
[3, 6, 7, 8]
[3, 6, 7, 8]
I want a function that returns true for j and false for i. If it's built-in or anyone could write that it would be appreciated.
A:
There's no 'pointers' in Python, like there are in C++ (or similar languages). The only distinction in Python is mutable vs. immutable. But all variables are just references to objects.
Variables with immutable types refer to values that you cannot modify, only replace. int is an example of an immutable type.
When you run your code, you assign 5 to i, then you assign the value of i to j, so that j now also has the value 5, but since these are immutable values, you can only change the entire value of either variable, which won't affect the value of the other.
Variables with mutable types have values that you can modify. list is an example of a mutable type.
When you run this:
xs = [1, 2, 3]
ys = xs
xs[0] = 999
The last statement modifies the value of both variables, as the list that was the value of xs is the same list that was assigned to ys and the final instruction modifies that value.
Immutable types including numbers, strings and tuples as well as a few other simple types. Mutable types include lists, dictionaries, and most other more complex classes.
Also, for example have a look at this:
a = 1
b = 1
c = b + 1
d = 2
print(id(a), id(b), id(c), id(d))
This will print four numbers, but note how the first two numbers will be the same (as they both refer to 1) and the second two are the same as well (as they both refer to 2).
Having said all that, if you want to test if something is mutable, there's no easy way to do that - but a common reason to want to do so is because you want to test if something is hashable, which you could test:
s = 'test'
print(s.__hash__ is None) # False
xs = [1, 2, 3]
print(xs.__hash__ is None) # True
|
How do you check if a variable references another declared object in Python?
|
Printing type of one variable just returns the pointed data's type
i = [5,6,7,8]
j = i
print(type(j))
<class 'list'>
and j references a mutable type. So
j[0] = 3
print(i)
print(j)
[3, 6, 7, 8]
[3, 6, 7, 8]
I want a function that returns true for j and false for i. If it's built-in or anyone could write that it would be appreciated.
|
[
"There's no 'pointers' in Python, like there are in C++ (or similar languages). The only distinction in Python is mutable vs. immutable. But all variables are just references to objects.\nVariables with immutable types refer to values that you cannot modify, only replace. int is an example of an immutable type.\nWhen you run your code, you assign 5 to i, then you assign the value of i to j, so that j now also has the value 5, but since these are immutable values, you can only change the entire value of either variable, which won't affect the value of the other.\nVariables with mutable types have values that you can modify. list is an example of a mutable type.\nWhen you run this:\nxs = [1, 2, 3]\nys = xs\nxs[0] = 999\n\nThe last statement modifies the value of both variables, as the list that was the value of xs is the same list that was assigned to ys and the final instruction modifies that value.\nImmutable types including numbers, strings and tuples as well as a few other simple types. Mutable types include lists, dictionaries, and most other more complex classes.\nAlso, for example have a look at this:\na = 1\nb = 1\nc = b + 1\nd = 2\nprint(id(a), id(b), id(c), id(d))\n\nThis will print four numbers, but note how the first two numbers will be the same (as they both refer to 1) and the second two are the same as well (as they both refer to 2).\nHaving said all that, if you want to test if something is mutable, there's no easy way to do that - but a common reason to want to do so is because you want to test if something is hashable, which you could test:\ns = 'test'\nprint(s.__hash__ is None) # False\n\n\nxs = [1, 2, 3]\nprint(xs.__hash__ is None) # True\n\n"
] |
[
2
] |
[] |
[] |
[
"pointers",
"python"
] |
stackoverflow_0074527549_pointers_python.txt
|
Q:
ValueError: shapes (1,6) and (5,5) not aligned: 6 (dim 1) != 5 (dim 0)
The NN must have 5 inputs, 4 hidden layers and 1 output. Learning rate 0.2, error threshold 0.2. Retrieves the data from an excel:
The error ValueError: shapes (1,6) and (5,5) not aligned: 6 (dim 1) != 5 (dim 0) is being displayed. I think I have something wrong with multiplying of weights and matrices the error line: hidden_in = np.dot(inputs, w1). I can't seem to solve it. Can someone help?
def train(inputs_list, w1, w2, w3, targets_list, lr, error):
....
while global_error > error:
# local error
local_error = np.array([])
for i, inputs in enumerate(inputs_list):
# translates the inputs sheet into a two-dimensional view (to enable the transposition operation)
inputs = np.array(inputs, ndmin=2)
print("Inputs", inputs)
# targets - contains the local target for this input
targets = np.array(targets_list[i], ndmin=2)
print("Target should be 1", targets)
# forward propagation
# scalar product of string and weight matrix
hidden_in = np.dot(inputs, w1)
# apply an activation function to a vector
hidden_out = f(hidden_in)
# adding an imaginary unit to the beginning of the vector to train the network
hidden_out = np.array(np.insert(hidden_out, 0, [1]), ndmin=2)
# scalar product of string and weight matrix
hidden_in2 = np.dot(hidden_out, w2)
# apply an activation function to a vector
hidden_out2 = f(hidden_in2)
# adding an imaginary one to the beginning of the vector
hidden_out2 = np.array(np.insert(hidden_out2, 0, [1]), ndmin=2)
# scalar product of string and weight matrix
final_in = np.dot(hidden_out2, w3)
# the activation function of the output layer is a straight line y = x, so
# here the value of "out" is equal to the value of "in"
final_out = final_in
# output layer error calculation
output_error = targets - final_out
# calculating the error of the second hidden layer
hidden_error2 = np.dot(output_error, w3.T)
# calculating the error of the first hidden layer
hidden_error = np.dot(hidden_error2[:, 1:], w2.T)
# adding the current error to the list of local errors
local_error = np.append(local_error, output_error)
# error backpropagation
# changing the weight matrix 3 because derivative of the activation function (y = x)
# y` = 1 in dW = lr*output_error*hidden_out2.T is not multiplied by this derivative
w3 += lr * output_error * hidden_out2.T
# in the backpropagation method, the imaginary one is excluded for the coincidence of dimensions
# hidden_error2[:,1:] - means the whole vector except for the first element
w2 += lr * hidden_error2[:, 1:] * f1(hidden_out2[:, 1:]) * hidden_out.T
w1 += lr * hidden_error[:, 1:] * f1(hidden_out[:, 1:]) * inputs.T
# global error is the module average of all local errors
global_error = abs(np.mean(local_error))
# global_error = np.sqrt(((local_error) ** 2).mean())
last_gl_e = global_error
# epoch incremented by 1
era += 1
# output to the console the current global error
# print('era=',era, 'global_error=', global_error, 'k_sup=', k_sup)
# a global error is added to the list of errors
list_error.append(global_error)
# if during training the number of epochs exceeds the threshold of 10000, then training will stop
if era > 1000:
print('gl=', global_error)
break
# returns the modified weights, number of epochs, and list of errors
print(global_error)
return w1, w2, w3, era, list_error
# function to test the trained network and output the result
def query(inputs_list, w1, w2, w3):
# create a list in which we will store "outs" for the test set
final_out = np.array([])
for i, inputs in enumerate(inputs_list):
# forward propagation just like training for "out"
inputs = np.array(inputs, ndmin=2)
hidden_in = np.dot(inputs, w1)
hidden_out = f(hidden_in)
hidden_out = np.array(np.insert(hidden_out, 0, [1]), ndmin=2)
hidden_in2 = np.dot(hidden_out, w2)
hidden_out2 = f(hidden_in2)
hidden_out2 = np.array(np.insert(hidden_out2, 0, [1]), ndmin=2)
final_in = np.dot(hidden_out2, w3)
final_out = np.append(final_out, final_in)
# return the value of the vector "out" rounded to an integer
return np.around(final_out)
# read data from csv using pandas library
# Titanic Passenger Data
# Set the column that will be indexed index_col='PassengerId'
data_titanic = "titanic_dataset.csv"
data = pd.read_csv(data_titanic)
# column Survived from data
# .values means that the data from the dataframe is converted to a numpy array
target_data = data['Survived'].values
# remove the Survived column from the dataset and convert it to an array
# data = data.drop(columns=['Survived']).values
data = data.drop('Survived', 1).values
# compose a sample of the training set from the first 600 rows of the dataset
inputs = data[0:600]
# add a column of imaginary ones for the set
inputs = np.c_[np.ones(600), inputs]
# compose the target set
targets = target_data[0:600]
# from the remaining 114 lines we make a test set
test = data[600:714]
test = np.c_[np.ones(114), test]
targets_test = target_data[600:714]
# learning rate
lr = 0.2
# allowable learning error (** is the degree)
eps = 0.2
# number of nodes in the input layer, taking into account one
# i.e. number of dataset columns +1 imaginary one
input_layer = 5
hidden_layer = 4
hidden_layer2 = 2
output_layer = 1
# initialization of weights depending on the number of nodes in the network layers
w1, w2, w3 = init_weight(input_layer, hidden_layer, hidden_layer2, output_layer)
w1, w2, w3, era, lst = train(inputs, w1, w2, w3, targets, lr, eps)
A:
Going by the convention that of weights are (n_neurons, n_inputs), I think the shape of your first hidden layer (W1) should be -> number of neurons in that layer, number of attributes/features in the sample.
Assuming you are outputing the Survived column, your features should be 5.
If there are 4 neurons in that layer, then the shape is (4,5) and your input's shapes will be (n_features, number_of_samples in a batch = m) or (5,m).
In this case the hidden_in = np.dot(inputs, w1) should be of shape (4,m).
I believe your error might be that you are including the Survived in the input data as well.
|
ValueError: shapes (1,6) and (5,5) not aligned: 6 (dim 1) != 5 (dim 0)
|
The NN must have 5 inputs, 4 hidden layers and 1 output. Learning rate 0.2, error threshold 0.2. Retrieves the data from an excel:
The error ValueError: shapes (1,6) and (5,5) not aligned: 6 (dim 1) != 5 (dim 0) is being displayed. I think I have something wrong with multiplying of weights and matrices the error line: hidden_in = np.dot(inputs, w1). I can't seem to solve it. Can someone help?
def train(inputs_list, w1, w2, w3, targets_list, lr, error):
....
while global_error > error:
# local error
local_error = np.array([])
for i, inputs in enumerate(inputs_list):
# translates the inputs sheet into a two-dimensional view (to enable the transposition operation)
inputs = np.array(inputs, ndmin=2)
print("Inputs", inputs)
# targets - contains the local target for this input
targets = np.array(targets_list[i], ndmin=2)
print("Target should be 1", targets)
# forward propagation
# scalar product of string and weight matrix
hidden_in = np.dot(inputs, w1)
# apply an activation function to a vector
hidden_out = f(hidden_in)
# adding an imaginary unit to the beginning of the vector to train the network
hidden_out = np.array(np.insert(hidden_out, 0, [1]), ndmin=2)
# scalar product of string and weight matrix
hidden_in2 = np.dot(hidden_out, w2)
# apply an activation function to a vector
hidden_out2 = f(hidden_in2)
# adding an imaginary one to the beginning of the vector
hidden_out2 = np.array(np.insert(hidden_out2, 0, [1]), ndmin=2)
# scalar product of string and weight matrix
final_in = np.dot(hidden_out2, w3)
# the activation function of the output layer is a straight line y = x, so
# here the value of "out" is equal to the value of "in"
final_out = final_in
# output layer error calculation
output_error = targets - final_out
# calculating the error of the second hidden layer
hidden_error2 = np.dot(output_error, w3.T)
# calculating the error of the first hidden layer
hidden_error = np.dot(hidden_error2[:, 1:], w2.T)
# adding the current error to the list of local errors
local_error = np.append(local_error, output_error)
# error backpropagation
# changing the weight matrix 3 because derivative of the activation function (y = x)
# y` = 1 in dW = lr*output_error*hidden_out2.T is not multiplied by this derivative
w3 += lr * output_error * hidden_out2.T
# in the backpropagation method, the imaginary one is excluded for the coincidence of dimensions
# hidden_error2[:,1:] - means the whole vector except for the first element
w2 += lr * hidden_error2[:, 1:] * f1(hidden_out2[:, 1:]) * hidden_out.T
w1 += lr * hidden_error[:, 1:] * f1(hidden_out[:, 1:]) * inputs.T
# global error is the module average of all local errors
global_error = abs(np.mean(local_error))
# global_error = np.sqrt(((local_error) ** 2).mean())
last_gl_e = global_error
# epoch incremented by 1
era += 1
# output to the console the current global error
# print('era=',era, 'global_error=', global_error, 'k_sup=', k_sup)
# a global error is added to the list of errors
list_error.append(global_error)
# if during training the number of epochs exceeds the threshold of 10000, then training will stop
if era > 1000:
print('gl=', global_error)
break
# returns the modified weights, number of epochs, and list of errors
print(global_error)
return w1, w2, w3, era, list_error
# function to test the trained network and output the result
def query(inputs_list, w1, w2, w3):
# create a list in which we will store "outs" for the test set
final_out = np.array([])
for i, inputs in enumerate(inputs_list):
# forward propagation just like training for "out"
inputs = np.array(inputs, ndmin=2)
hidden_in = np.dot(inputs, w1)
hidden_out = f(hidden_in)
hidden_out = np.array(np.insert(hidden_out, 0, [1]), ndmin=2)
hidden_in2 = np.dot(hidden_out, w2)
hidden_out2 = f(hidden_in2)
hidden_out2 = np.array(np.insert(hidden_out2, 0, [1]), ndmin=2)
final_in = np.dot(hidden_out2, w3)
final_out = np.append(final_out, final_in)
# return the value of the vector "out" rounded to an integer
return np.around(final_out)
# read data from csv using pandas library
# Titanic Passenger Data
# Set the column that will be indexed index_col='PassengerId'
data_titanic = "titanic_dataset.csv"
data = pd.read_csv(data_titanic)
# column Survived from data
# .values means that the data from the dataframe is converted to a numpy array
target_data = data['Survived'].values
# remove the Survived column from the dataset and convert it to an array
# data = data.drop(columns=['Survived']).values
data = data.drop('Survived', 1).values
# compose a sample of the training set from the first 600 rows of the dataset
inputs = data[0:600]
# add a column of imaginary ones for the set
inputs = np.c_[np.ones(600), inputs]
# compose the target set
targets = target_data[0:600]
# from the remaining 114 lines we make a test set
test = data[600:714]
test = np.c_[np.ones(114), test]
targets_test = target_data[600:714]
# learning rate
lr = 0.2
# allowable learning error (** is the degree)
eps = 0.2
# number of nodes in the input layer, taking into account one
# i.e. number of dataset columns +1 imaginary one
input_layer = 5
hidden_layer = 4
hidden_layer2 = 2
output_layer = 1
# initialization of weights depending on the number of nodes in the network layers
w1, w2, w3 = init_weight(input_layer, hidden_layer, hidden_layer2, output_layer)
w1, w2, w3, era, lst = train(inputs, w1, w2, w3, targets, lr, eps)
|
[
"Going by the convention that of weights are (n_neurons, n_inputs), I think the shape of your first hidden layer (W1) should be -> number of neurons in that layer, number of attributes/features in the sample.\nAssuming you are outputing the Survived column, your features should be 5.\nIf there are 4 neurons in that layer, then the shape is (4,5) and your input's shapes will be (n_features, number_of_samples in a batch = m) or (5,m).\nIn this case the hidden_in = np.dot(inputs, w1) should be of shape (4,m).\nI believe your error might be that you are including the Survived in the input data as well.\n"
] |
[
1
] |
[] |
[] |
[
"backpropagation",
"mlp",
"neural_network",
"python"
] |
stackoverflow_0074521083_backpropagation_mlp_neural_network_python.txt
|
Q:
How can I install pyplot?
I tried to install pyplot using 'pip install pyplot' in command prompt while it was installing by mistake i closed command prompt then again i am trying to install pyplot using the same command but it was not installing.Can anyone guide me how to install pyplotKindly find the error in this image
error rectification in installing pyplot
A:
pyplot is part of a matplotlib.
In order to install pyplot you should install matplotlib
pip install matplotlib
So you can "import matplotlib.pyplot"
A:
You can go to https://pypi.org/project/matplotlib to see and install the version you want.
Then you can import the pylot
from matplotlib import pyplot
|
How can I install pyplot?
|
I tried to install pyplot using 'pip install pyplot' in command prompt while it was installing by mistake i closed command prompt then again i am trying to install pyplot using the same command but it was not installing.Can anyone guide me how to install pyplotKindly find the error in this image
error rectification in installing pyplot
|
[
"pyplot is part of a matplotlib.\nIn order to install pyplot you should install matplotlib\n\npip install matplotlib\n\nSo you can \"import matplotlib.pyplot\"\n",
"You can go to https://pypi.org/project/matplotlib to see and install the version you want.\nThen you can import the pylot\nfrom matplotlib import pyplot\n\n"
] |
[
1,
0
] |
[] |
[] |
[
"data_science",
"graph_data_science",
"matplotlib",
"pandas",
"python"
] |
stackoverflow_0074527084_data_science_graph_data_science_matplotlib_pandas_python.txt
|
Q:
Add a whitespace to every second line and merge every second line in a text file Python
I have a text file of lets say this content
a
b
c
d
e
f
I want python to read the textfile and edit it to this, add whitespace to the start of every second line then merge with first line above, this is what it should look like
a b
c d
e f
How can I achieve this?
I written gotten this together but it only prints and doesn't save the contents to existing file, doesn't add white space
with open("text.txt", encoding='utf-8') as f:
content = f.readlines()
str = ""
for i in range(1,len(content)+1):
str += content[i-1].strip()
if i % 2 == 0:
print(str)
str = ""
A:
I would suggest differnt approch this also may works.
with open("text.txt") as file_in:
lines = []
for line in file_in:
lines.append(line)
#lines ['a\n', 'b\n', 'c\n', 'd']
lines = [x.replace('\n', '') for x in lines]
for x in range(0,len(lines),2):
print (lines[x], lines[x+1])
should give
a b
c d
e f
or else you can simply append spaces to list as follows and print accordingly.
for b in range (0,len(lines)-1):
lines.insert(b*3,' ')
lines.pop(0) # ['a', 'b', ' ', 'c', 'd', ' ']
lines= ''.join(lines)
for word in lines.split():
print(word)
Gives
ab
cd
|
Add a whitespace to every second line and merge every second line in a text file Python
|
I have a text file of lets say this content
a
b
c
d
e
f
I want python to read the textfile and edit it to this, add whitespace to the start of every second line then merge with first line above, this is what it should look like
a b
c d
e f
How can I achieve this?
I written gotten this together but it only prints and doesn't save the contents to existing file, doesn't add white space
with open("text.txt", encoding='utf-8') as f:
content = f.readlines()
str = ""
for i in range(1,len(content)+1):
str += content[i-1].strip()
if i % 2 == 0:
print(str)
str = ""
|
[
"I would suggest differnt approch this also may works.\nwith open(\"text.txt\") as file_in:\nlines = []\nfor line in file_in:\n lines.append(line)\n\n#lines ['a\\n', 'b\\n', 'c\\n', 'd']\n\nlines = [x.replace('\\n', '') for x in lines]\nfor x in range(0,len(lines),2):\n print (lines[x], lines[x+1])\n\nshould give\na b\nc d\ne f\n\nor else you can simply append spaces to list as follows and print accordingly.\nfor b in range (0,len(lines)-1):\n \n lines.insert(b*3,' ') \n\nlines.pop(0) # ['a', 'b', ' ', 'c', 'd', ' ']\nlines= ''.join(lines)\nfor word in lines.split():\n print(word)\n\nGives\nab\ncd\n\n"
] |
[
0
] |
[] |
[] |
[
"python",
"python_3.x"
] |
stackoverflow_0074527537_python_python_3.x.txt
|
Q:
conda uninstall quits without removing anything
I've tried to remove packages using conda uninstall. The command runs for a long time, takes up a large amount of memory (but doesn't run out I believe) and then quits with no indication of having completed the 'Solving environment' step. When I check, the package is still there. For example:
(base) pm@pm:~/Software/anaconda3/bin$ conda uninstall -n base pytorch
Collecting package metadata (repodata.json): done
Solving environment: - (base) pm@pm:~/Software/anaconda3/bin$ conda list -n base -f pytorch
# packages in environment at /home/pm/Software/anaconda3:
#
# Name Version Build Channel
pytorch 1.7.1 py3.7_cuda10.1.243_cudnn7.6.3_0 pytorch
I've also tried remove, which does exactly the same thing. Suggestions welcome!
A:
If you're here because you're trying to install a pre or beta package that isn't available via conda, I was able to do an upgrade via pip.
I had installed h3-py via conda, which installed v3.7.
$ conda install h3-py
...
The following NEW packages will be INSTALLED:
h3-py conda-forge/linux-64::h3-py-3.7.4-py311ha362b79_1 None
They then released v4, which drastically changed the API and I wanted to update. Anaconda was hanging and eventually killed on an uninstall or remove:
$ conda uninstall h3-py
Collecting package metadata (repodata.json): \ Killed
But pip saved the day (the --update will just get the latest, the --pre was for me to get the pre-release):
$ pip install h3 --upgrade --pre
...
Successfully built h3
Installing collected packages: h3
Attempting uninstall: h3
Found existing installation: h3 3.7.4
Uninstalling h3-3.7.4:
Successfully uninstalled h3-3.7.4
Successfully installed h3-4.0.0b1
Still, would be great if conda uninstall worked.
|
conda uninstall quits without removing anything
|
I've tried to remove packages using conda uninstall. The command runs for a long time, takes up a large amount of memory (but doesn't run out I believe) and then quits with no indication of having completed the 'Solving environment' step. When I check, the package is still there. For example:
(base) pm@pm:~/Software/anaconda3/bin$ conda uninstall -n base pytorch
Collecting package metadata (repodata.json): done
Solving environment: - (base) pm@pm:~/Software/anaconda3/bin$ conda list -n base -f pytorch
# packages in environment at /home/pm/Software/anaconda3:
#
# Name Version Build Channel
pytorch 1.7.1 py3.7_cuda10.1.243_cudnn7.6.3_0 pytorch
I've also tried remove, which does exactly the same thing. Suggestions welcome!
|
[
"If you're here because you're trying to install a pre or beta package that isn't available via conda, I was able to do an upgrade via pip.\nI had installed h3-py via conda, which installed v3.7.\n$ conda install h3-py\n\n...\nThe following NEW packages will be INSTALLED:\n\n h3-py conda-forge/linux-64::h3-py-3.7.4-py311ha362b79_1 None\n\nThey then released v4, which drastically changed the API and I wanted to update. Anaconda was hanging and eventually killed on an uninstall or remove:\n$ conda uninstall h3-py \nCollecting package metadata (repodata.json): \\ Killed\n\nBut pip saved the day (the --update will just get the latest, the --pre was for me to get the pre-release):\n$ pip install h3 --upgrade --pre\n\n...\nSuccessfully built h3\nInstalling collected packages: h3\n Attempting uninstall: h3\n Found existing installation: h3 3.7.4\n Uninstalling h3-3.7.4:\n Successfully uninstalled h3-3.7.4\nSuccessfully installed h3-4.0.0b1\n\nStill, would be great if conda uninstall worked.\n"
] |
[
0
] |
[] |
[] |
[
"conda",
"python"
] |
stackoverflow_0071330613_conda_python.txt
|
Q:
Raspberry pi pico with MPU6050 reading zeros
So I am working on a step counter using a raspberry pi pico and a MPU6050 when last night I had the code working fine so I unplugged the pico, then I went to plug the pico back in this morning and now it's displaying zeros. I configured the code accordingly to these hookups:
VCC to 3v3
GND to GND
SCL to GP1
SDA to GP0
Here is the code:
#import PIN and I2C from machine library
from machine import Pin, I2C
import time
#Define I2C bus
i2c = I2C(0, sda=machine.Pin(0), scl=machine.Pin(1))
#Device address on the I2C bus
MPU6050_ADDR = 0x68
#PWR_MGMT_1 memory address
MPU6050_PWR_MGMT_1 = 0x6B
#Accelerometer's high and low register for each axis
MPU6050_ACCEL_XOUT_H = 0x3B
MPU6050_ACCEL_XOUT_L = 0x3C
MPU6050_ACCEL_YOUT_H = 0x3D
MPU6050_ACCEL_YOUT_L = 0x3E
MPU6050_ACCEL_ZOUT_H = 0x3F
MPU6050_ACCEL_ZOUT_L = 0x40
#Accelerometer's LSB/g (least significant bits per gravitational force) sensitivity
MPU6050_LSBG = 16384.0
#Set all bits in the PWR_MGMT_1 register to 0
def mpu6050_init(i2c):
i2c.writeto_mem(MPU6050_ADDR, MPU6050_PWR_MGMT_1, bytes([0])) #needs to be 0 to have device in 'awake' mode change to 1 for 'sleep' mode
#define x, y, and z values
def accel_x_value(h, l):
if not h[0] & 0x80:
return h[0] << 8 | l[0]
return -((h[0] ^ 255) << 8) | (l[0] ^ 255) + 1
def accel_y_value(h, l):
if not h[0] & 0x80:
return h[0] << 8 | l[0]
return -((h[0] ^ 255) << 8) | (l[0] ^ 255) + 1
def accel_z_value(h, l):
if not h[0] & 0x80:
return h[0] << 8 | l[0]
return -((h[0] ^ 255) << 8) | (l[0] ^ 255) + 1
#Get Accelerometer values
def get_accel_x(i2c):
accel_x_h = i2c.readfrom_mem(MPU6050_ADDR, MPU6050_ACCEL_XOUT_H, 1)
accel_x_l = i2c.readfrom_mem(MPU6050_ADDR, MPU6050_ACCEL_XOUT_L, 1)
return accel_x_value(accel_x_h, accel_x_l) / MPU6050_LSBG
def get_accel_y(i2c):
accel_y_h = i2c.readfrom_mem(MPU6050_ADDR, MPU6050_ACCEL_YOUT_H, 1)
accel_y_l = i2c.readfrom_mem(MPU6050_ADDR, MPU6050_ACCEL_YOUT_L, 1)
return accel_y_value(accel_y_h, accel_y_l) / MPU6050_LSBG
def get_accel_z(i2c):
accel_z_h = i2c.readfrom_mem(MPU6050_ADDR, MPU6050_ACCEL_ZOUT_H, 1)
accel_z_l = i2c.readfrom_mem(MPU6050_ADDR, MPU6050_ACCEL_ZOUT_L, 1)
return accel_z_value(accel_z_h, accel_z_l) / MPU6050_LSBG
steps = 0 #step counter
while True:
if get_accel_x(i2c) > 0.6: #minimum x value for counter
steps += 1
elif get_accel_y(i2c) > 3: #minimum y value for counter
steps += 1
elif get_accel_z(i2c) > 3: #minimum z value for counter
steps += 1
print("\nsteps:", steps)
print("Accelerometer:\t", get_accel_x(i2c), get_accel_y(i2c), get_accel_z(i2c), "g")
#Print Accelerometer values (X,Y,Z)
time.sleep(0.75) #Delay between values in seconds
First I replaced the hardware, I tried a different MPU6050 and new wires (I only have one pico so I can't try a different one) yet I still get the same zero error. Next I tried testing the MPU6050 with some test code I found (from this website: https://www.hackster.io/mr-alam/how-to-use-i2c-pins-in-raspberry-pi-pico-i2c-scanner-code-8f489f) and it came back working on both MPU6050s, yet still the same zero error. Next I changed the pins and the code to reflect that, yet still the same zero error. Lastly I looked online for help and couldn't find anything useful except for someone mentioning 'tie the SLEEP bit low in the PWR_MGMT_1 register' (from: MPU6050 only outputs 0x00 on I2C with MicroPython) however I have no clue what that means and I don't have enough mentions to comment on that question, so I can't ask.
A:
I added this code to initialize the MPU6050: mpu6050_init(i2c) to the end of my code (right before the 'steps = 0 #step counter' bit). This is calling a function near the top of the code to initialize the board to get out of sleep mode, which is what causes 'sleep mode' on the device.
|
Raspberry pi pico with MPU6050 reading zeros
|
So I am working on a step counter using a raspberry pi pico and a MPU6050 when last night I had the code working fine so I unplugged the pico, then I went to plug the pico back in this morning and now it's displaying zeros. I configured the code accordingly to these hookups:
VCC to 3v3
GND to GND
SCL to GP1
SDA to GP0
Here is the code:
#import PIN and I2C from machine library
from machine import Pin, I2C
import time
#Define I2C bus
i2c = I2C(0, sda=machine.Pin(0), scl=machine.Pin(1))
#Device address on the I2C bus
MPU6050_ADDR = 0x68
#PWR_MGMT_1 memory address
MPU6050_PWR_MGMT_1 = 0x6B
#Accelerometer's high and low register for each axis
MPU6050_ACCEL_XOUT_H = 0x3B
MPU6050_ACCEL_XOUT_L = 0x3C
MPU6050_ACCEL_YOUT_H = 0x3D
MPU6050_ACCEL_YOUT_L = 0x3E
MPU6050_ACCEL_ZOUT_H = 0x3F
MPU6050_ACCEL_ZOUT_L = 0x40
#Accelerometer's LSB/g (least significant bits per gravitational force) sensitivity
MPU6050_LSBG = 16384.0
#Set all bits in the PWR_MGMT_1 register to 0
def mpu6050_init(i2c):
i2c.writeto_mem(MPU6050_ADDR, MPU6050_PWR_MGMT_1, bytes([0])) #needs to be 0 to have device in 'awake' mode change to 1 for 'sleep' mode
#define x, y, and z values
def accel_x_value(h, l):
if not h[0] & 0x80:
return h[0] << 8 | l[0]
return -((h[0] ^ 255) << 8) | (l[0] ^ 255) + 1
def accel_y_value(h, l):
if not h[0] & 0x80:
return h[0] << 8 | l[0]
return -((h[0] ^ 255) << 8) | (l[0] ^ 255) + 1
def accel_z_value(h, l):
if not h[0] & 0x80:
return h[0] << 8 | l[0]
return -((h[0] ^ 255) << 8) | (l[0] ^ 255) + 1
#Get Accelerometer values
def get_accel_x(i2c):
accel_x_h = i2c.readfrom_mem(MPU6050_ADDR, MPU6050_ACCEL_XOUT_H, 1)
accel_x_l = i2c.readfrom_mem(MPU6050_ADDR, MPU6050_ACCEL_XOUT_L, 1)
return accel_x_value(accel_x_h, accel_x_l) / MPU6050_LSBG
def get_accel_y(i2c):
accel_y_h = i2c.readfrom_mem(MPU6050_ADDR, MPU6050_ACCEL_YOUT_H, 1)
accel_y_l = i2c.readfrom_mem(MPU6050_ADDR, MPU6050_ACCEL_YOUT_L, 1)
return accel_y_value(accel_y_h, accel_y_l) / MPU6050_LSBG
def get_accel_z(i2c):
accel_z_h = i2c.readfrom_mem(MPU6050_ADDR, MPU6050_ACCEL_ZOUT_H, 1)
accel_z_l = i2c.readfrom_mem(MPU6050_ADDR, MPU6050_ACCEL_ZOUT_L, 1)
return accel_z_value(accel_z_h, accel_z_l) / MPU6050_LSBG
steps = 0 #step counter
while True:
if get_accel_x(i2c) > 0.6: #minimum x value for counter
steps += 1
elif get_accel_y(i2c) > 3: #minimum y value for counter
steps += 1
elif get_accel_z(i2c) > 3: #minimum z value for counter
steps += 1
print("\nsteps:", steps)
print("Accelerometer:\t", get_accel_x(i2c), get_accel_y(i2c), get_accel_z(i2c), "g")
#Print Accelerometer values (X,Y,Z)
time.sleep(0.75) #Delay between values in seconds
First I replaced the hardware, I tried a different MPU6050 and new wires (I only have one pico so I can't try a different one) yet I still get the same zero error. Next I tried testing the MPU6050 with some test code I found (from this website: https://www.hackster.io/mr-alam/how-to-use-i2c-pins-in-raspberry-pi-pico-i2c-scanner-code-8f489f) and it came back working on both MPU6050s, yet still the same zero error. Next I changed the pins and the code to reflect that, yet still the same zero error. Lastly I looked online for help and couldn't find anything useful except for someone mentioning 'tie the SLEEP bit low in the PWR_MGMT_1 register' (from: MPU6050 only outputs 0x00 on I2C with MicroPython) however I have no clue what that means and I don't have enough mentions to comment on that question, so I can't ask.
|
[
"I added this code to initialize the MPU6050: mpu6050_init(i2c) to the end of my code (right before the 'steps = 0 #step counter' bit). This is calling a function near the top of the code to initialize the board to get out of sleep mode, which is what causes 'sleep mode' on the device.\n"
] |
[
0
] |
[] |
[] |
[
"micropython",
"mpu6050",
"python",
"raspberry_pi_pico"
] |
stackoverflow_0074518571_micropython_mpu6050_python_raspberry_pi_pico.txt
|
Q:
return self._engine.get_loc(casted_key) 3622 except KeyError as err
I have the following code
df = pd.DataFrame(columns=['col1', 'col2', 'col3', 'col4',
'col5', 'col6'])
vec = [a,b,c,d,...]
for v in vec:
name = 'name'
df.loc[name]['col1'] = v
....
And I got error that:
How to solve such error?
A:
Solved it, using df.at[name] = v
|
return self._engine.get_loc(casted_key) 3622 except KeyError as err
|
I have the following code
df = pd.DataFrame(columns=['col1', 'col2', 'col3', 'col4',
'col5', 'col6'])
vec = [a,b,c,d,...]
for v in vec:
name = 'name'
df.loc[name]['col1'] = v
....
And I got error that:
How to solve such error?
|
[
"Solved it, using df.at[name] = v\n"
] |
[
0
] |
[] |
[] |
[
"pandas",
"python"
] |
stackoverflow_0074527207_pandas_python.txt
|
Q:
VTK retrieve a specific actor from a renderer
I have the following code:
my_renderer = vtkRenderer()
my_actor = vtkActor()
my_renderer.AddActor(my_actor)
Is there a way to recover a specific actor from the renderer? VtkRenderer has the following function GetActors() which returns a collection of actors but I cannot see how to identify any specific one, if say I only wanted to change the property of one of them.
A:
How do you specific the wanted actor?
One possible solution is: implement a selfActor which inherits from vtkActor. Then, record a name in selfActor. Then, you can use actor->GetName() to obtain the name. You can identify the actor by the name.
|
VTK retrieve a specific actor from a renderer
|
I have the following code:
my_renderer = vtkRenderer()
my_actor = vtkActor()
my_renderer.AddActor(my_actor)
Is there a way to recover a specific actor from the renderer? VtkRenderer has the following function GetActors() which returns a collection of actors but I cannot see how to identify any specific one, if say I only wanted to change the property of one of them.
|
[
"How do you specific the wanted actor?\nOne possible solution is: implement a selfActor which inherits from vtkActor. Then, record a name in selfActor. Then, you can use actor->GetName() to obtain the name. You can identify the actor by the name.\n"
] |
[
0
] |
[] |
[] |
[
"3d",
"python",
"vtk"
] |
stackoverflow_0074140486_3d_python_vtk.txt
|
Q:
PyAutoGUI random click within area in a radial-like pattern
pretty new to python, but I'm trying to have the mouse click on a point within an image using PyAutoGUI. However the project requires I simulate a "human pattern". So what I'm going for is an "accurate-like" accuracy, where most of the points are in the middle and it gets more sparse the further away the click is, simulating missclicks or room for error. So that not every click is exactly on the point in the centre. Check the simulated clickmap below:
(where red is the most clicked area and green is the least - each click is represented by a pixel)
import pyautogui
pyautogui.click(pos.x,pos.y)
Given that I have the x and y position, what's the best way to achieve this kind of somewhat random pattern the most efficient way?
A:
Generate a random number and add into your x & y positions
import random
from PIL import Image
object = Image.open('Screenshot.png')
theWidth = object.width
theHeight = object.height
X = pos.x + random.randint(pos.x - theWidth/2,pos.x + theWidth/2)
Y = pos.y + random.randint(pos.y - theHeight/2,pos.y + theHeight/2)
A:
I would use np.random.normal() to generate clicks within a normal distribution (vertically and horizontally). I also randomise the interval between clicks to generate a more "human" click rate.
import pyautogui as p
import numpy as np
import random
def clicker(x, y, sigma, n_clicks):
s = np.random.normal(x, sigma, n_clicks)
t = np.random.normal(y, sigma, n_clicks)
for i in range(n_clicks):
p.moveTo(s[i],t[i],0.2)
p.click(s[i],t[i])
p.sleep(random.random())
#Set the number of clicks
number_of_clicks = 100
# Set the centre of the image
centreX = 500
centreY = 500
# Set the standard deviation (1SD in pixels)
sd = 100
# Sleep for 5 seconds before starting
p.sleep(5)
clicker(centreX, centreY, sd, number_of_clicks)
CLICK OUTPUT using 100 clicks:
|
PyAutoGUI random click within area in a radial-like pattern
|
pretty new to python, but I'm trying to have the mouse click on a point within an image using PyAutoGUI. However the project requires I simulate a "human pattern". So what I'm going for is an "accurate-like" accuracy, where most of the points are in the middle and it gets more sparse the further away the click is, simulating missclicks or room for error. So that not every click is exactly on the point in the centre. Check the simulated clickmap below:
(where red is the most clicked area and green is the least - each click is represented by a pixel)
import pyautogui
pyautogui.click(pos.x,pos.y)
Given that I have the x and y position, what's the best way to achieve this kind of somewhat random pattern the most efficient way?
|
[
"Generate a random number and add into your x & y positions\nimport random\nfrom PIL import Image\n\nobject = Image.open('Screenshot.png')\ntheWidth = object.width\ntheHeight = object.height\nX = pos.x + random.randint(pos.x - theWidth/2,pos.x + theWidth/2)\nY = pos.y + random.randint(pos.y - theHeight/2,pos.y + theHeight/2)\n\n",
"I would use np.random.normal() to generate clicks within a normal distribution (vertically and horizontally). I also randomise the interval between clicks to generate a more \"human\" click rate.\nimport pyautogui as p\nimport numpy as np\nimport random\n\ndef clicker(x, y, sigma, n_clicks):\n s = np.random.normal(x, sigma, n_clicks)\n t = np.random.normal(y, sigma, n_clicks)\n \n for i in range(n_clicks):\n p.moveTo(s[i],t[i],0.2)\n p.click(s[i],t[i])\n p.sleep(random.random())\n\n#Set the number of clicks\nnumber_of_clicks = 100\n\n# Set the centre of the image\ncentreX = 500\ncentreY = 500\n\n# Set the standard deviation (1SD in pixels)\nsd = 100\n\n# Sleep for 5 seconds before starting\np.sleep(5) \nclicker(centreX, centreY, sd, number_of_clicks)\n\nCLICK OUTPUT using 100 clicks:\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"arrays",
"pyautogui",
"python"
] |
stackoverflow_0074525304_arrays_pyautogui_python.txt
|
Q:
What is the best method of plotting the average line/data of multiple CSV files?
I am currently working with 9 different csv files all testing similar samples of a material. The output of data looks similar to this:
Time,Displacement,Force,Flexure stress,Flexure strain (Displacement)
(s),(mm),(N),(MPa),(%)
"0.0000","0.0000","0.0007","0.0000","0.0000"
"0.0200","0.0000","0.0069","0.0004","0.0000"
"0.0400","0.0001","-0.0024","-0.0001","0.0003"
"0.0600","0.0005","0.0040","0.0002","0.0014"
"0.0800","0.0014","0.0106","0.0006","0.0041"
I was able to plot each file on the same plot using this code I have put together from several sources:
import os
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
### Set path to the folder containing the .csv files
PATH = 'my path'
### Fetch all files in path
fileNames = os.listdir(PATH)
### Filter file name list for files ending with .csv
fileNames = [file for file in fileNames if '.csv' in file]
### Loop over all files
for file in fileNames:
### Read .csv file and append to list
df = pd.read_csv(PATH + file, usecols = [3, 4], skiprows=2, names=['Stress', 'Strain'], header=None)
strain_df = df['Strain']*0.01
side = 6.2 #mm
stress_df = (df['Stress'])/(side**2) # N/mm**2
### Create line for every file
plt.plot(strain_df, stress_df)
### Generate the plot
plt.xlabel(r'Strain $\epsilon$ (mm/mm)')
plt.ylabel(r'Stress $\sigma$ (N/mm$^2$)')
plt.title(r'Stress Strain Curve - 4$^\circ$C/min ')
plt.show()
This code block then gives a plot like this:
I am fine with how that ended up but I would really like to add a average line which I can add to this plot and also to compare to other materials tested in a similar way instead of having 40+ lines on the same plot. I'm not sure if the best way of doing this would be to create a new csv file that takes the average value of each row and column or if there is a way I can find the average in the loop I created. Any Tips would be greatly appreciated!
This is something similar to what I am looking for (the black line in the bottom plot):
A:
Here is my solution and image result.
import os
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
### Set path to the folder containing the .csv files
PATH = './'
### Fetch all files in path
fileNames = os.listdir(PATH)
### Filter file name list for files ending with .csv
fileNames = [file for file in fileNames if '.csv' in file]
count_fileNames = len(fileNames)
list_strain = []
list_stress = []
### Loop over all files
for file in fileNames:
print("file: ", file)
### Read .csv file and append to list
df = pd.read_csv(PATH + file, usecols = [3, 4], skiprows=2, names=['Stress', 'Strain'], header=None, encoding= 'unicode_escape')
strain_df = df['Strain']*0.01
side = 6.2 #mm
stress_df = (df['Stress'])/(side**2) # N/mm**2
list_strain.append(strain_df)
list_stress.append(stress_df)
### Create line for every file
plt.plot(strain_df, stress_df)
mean_strain = sum(list_strain) / count_fileNames
mean_stress = sum(list_stress) / count_fileNames
plt.plot(mean_strain, mean_stress, 'k')
### Generate the plot
plt.xlabel(r'Strain $\epsilon$ (mm/mm)')
plt.ylabel(r'Stress $\sigma$ (N/mm$^2$)')
plt.title(r'Stress Strain Curve - 4$^\circ$C/min ')
plt.show()
result
|
What is the best method of plotting the average line/data of multiple CSV files?
|
I am currently working with 9 different csv files all testing similar samples of a material. The output of data looks similar to this:
Time,Displacement,Force,Flexure stress,Flexure strain (Displacement)
(s),(mm),(N),(MPa),(%)
"0.0000","0.0000","0.0007","0.0000","0.0000"
"0.0200","0.0000","0.0069","0.0004","0.0000"
"0.0400","0.0001","-0.0024","-0.0001","0.0003"
"0.0600","0.0005","0.0040","0.0002","0.0014"
"0.0800","0.0014","0.0106","0.0006","0.0041"
I was able to plot each file on the same plot using this code I have put together from several sources:
import os
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
### Set path to the folder containing the .csv files
PATH = 'my path'
### Fetch all files in path
fileNames = os.listdir(PATH)
### Filter file name list for files ending with .csv
fileNames = [file for file in fileNames if '.csv' in file]
### Loop over all files
for file in fileNames:
### Read .csv file and append to list
df = pd.read_csv(PATH + file, usecols = [3, 4], skiprows=2, names=['Stress', 'Strain'], header=None)
strain_df = df['Strain']*0.01
side = 6.2 #mm
stress_df = (df['Stress'])/(side**2) # N/mm**2
### Create line for every file
plt.plot(strain_df, stress_df)
### Generate the plot
plt.xlabel(r'Strain $\epsilon$ (mm/mm)')
plt.ylabel(r'Stress $\sigma$ (N/mm$^2$)')
plt.title(r'Stress Strain Curve - 4$^\circ$C/min ')
plt.show()
This code block then gives a plot like this:
I am fine with how that ended up but I would really like to add a average line which I can add to this plot and also to compare to other materials tested in a similar way instead of having 40+ lines on the same plot. I'm not sure if the best way of doing this would be to create a new csv file that takes the average value of each row and column or if there is a way I can find the average in the loop I created. Any Tips would be greatly appreciated!
This is something similar to what I am looking for (the black line in the bottom plot):
|
[
"Here is my solution and image result.\nimport os\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n### Set path to the folder containing the .csv files\nPATH = './' \n\n### Fetch all files in path\nfileNames = os.listdir(PATH)\n\n### Filter file name list for files ending with .csv\nfileNames = [file for file in fileNames if '.csv' in file]\ncount_fileNames = len(fileNames)\nlist_strain = []\nlist_stress = []\n### Loop over all files\nfor file in fileNames:\n print(\"file: \", file)\n\n ### Read .csv file and append to list\n df = pd.read_csv(PATH + file, usecols = [3, 4], skiprows=2, names=['Stress', 'Strain'], header=None, encoding= 'unicode_escape')\n \n strain_df = df['Strain']*0.01\n side = 6.2 #mm\n stress_df = (df['Stress'])/(side**2) # N/mm**2\n\n list_strain.append(strain_df)\n list_stress.append(stress_df)\n ### Create line for every file\n plt.plot(strain_df, stress_df)\n\nmean_strain = sum(list_strain) / count_fileNames\nmean_stress = sum(list_stress) / count_fileNames\nplt.plot(mean_strain, mean_stress, 'k')\n\n### Generate the plot\n\nplt.xlabel(r'Strain $\\epsilon$ (mm/mm)')\nplt.ylabel(r'Stress $\\sigma$ (N/mm$^2$)')\nplt.title(r'Stress Strain Curve - 4$^\\circ$C/min ')\nplt.show()\n\nresult\n"
] |
[
0
] |
[] |
[] |
[
"csv",
"dataframe",
"matplotlib",
"pandas",
"python"
] |
stackoverflow_0074527271_csv_dataframe_matplotlib_pandas_python.txt
|
Q:
Blank page when removing all mentions of grid()
I've switched from .grid() to .place() in my program, so I decided to remove a frame that contained the grid widgets:
BackButtonR = Button(registerPage, text="Back", command=lambda: show_frame(Menu))
BackButtonR.grid(row=0, column=0, sticky=W)
Button2F3 = Button(registerPage, text="Find")
Button2F3.grid(row=1, column=1)
Button3F3 = Button(registerPage, text="Calculate").grid(row=6, column=1)
LabelTitleF3 = Label(registerPage, text="Calculate Buy Price").grid(row=0, column=3)
label1F3 = Label(registerPage, text="Enter Ticker Symbol:").grid(row=1, column=0)
label2F3 = Label(registerPage, text="Expected CAGR").grid(row=2, column=0)
label3F3 = Label(registerPage, text="Years of Analysis").grid(row=3, column=0)
label4F3 = Label(registerPage, text="Expected PE Ratio").grid(row=4, column=0)
label5F3 = Label(registerPage, text="Desired Annual Return").grid(row=5, column=0)
entry1F3 = Entry(registerPage, width=7).grid(row=1, column=1, padx=0)
entry2F3 = Entry(registerPage).grid(row=2, column=1, pady=10, padx=0)
entry3F3 = Entry(registerPage).grid(row=3, column=1, pady=10, padx=0)
entry4F3 = Entry(registerPage).grid(row=4, column=1, pady=10, padx=0)
entry5F3 = Entry(registerPage).grid(row=, column=1, pady=10, padx=0)
But weirdly, when I rerun my program everything turns blank. This shouldn't happen, since I've removed any reference to .grid(), so the program should be working fine with .place(). Here is my full code:
print(220+135)
from tkinter import *
root = Tk()
root.title("Account Signup")
DarkBlue = "#2460A7"
LightBlue = "#B3C7D6"
root.geometry('350x230')
Menu = Frame(root)
loginPage = Frame(root)
registerPage = Frame(root)
for AllFrames in (Menu, loginPage, registerPage):
AllFrames.grid(row=0, column=0, sticky='nsew')
AllFrames.configure(bg=LightBlue)
def show_frame(frame):
frame.tkraise()
show_frame(Menu)
# ============= Menu Page =========
Menu.grid_columnconfigure(0, weight=1)
menuTitle = Label(Menu, text="Menu", font=("Arial", 25), bg=LightBlue)
menuTitle.place(x=130, y=25)
loginButton1 = Button(Menu, width=25, text="Login", command=lambda: show_frame(loginPage))
loginButton1.place(x=85, y=85)
registerButton1 = Button(Menu, width=25, text="Register", command=lambda: show_frame(registerPage))
registerButton1.place(x=85, y=115)
# ======== Login Page ===========
loginUsernameL = Label(loginPage, text='Username').place(x=30, y=60)
loginUsernameE = Entry(loginPage).place(x=120, y=60)
loginPasswordL = Label(loginPage, text='Password').place(x=30, y=90)
loginPasswordE = Entry(loginPage).place(x=120, y=90)
backButton = Button(loginPage, text='Back', command=lambda: show_frame(Menu)).place(x=0, y=0)
loginButton = Button(loginPage, text='Login', width=20).place(x=100, y=150)
# ======== Register Page ===========
root.mainloop()
Why is my program turning blank?
A:
When you use pack and grid, these functions will normally adjust the size of a widget's parent to fit all of its children. It's one of the most compelling reasons to use these geometry managers.
When you use place this doesn't happen. If you use place to put a widget in a frame, the frame will not grow or shrink to fit the widget.
In your case you're creating Menu, loginPage and registerPage and not giving them a size so they default to 1x1 pixels. When you use place to add a widget to the frame, the frame will remain at 1x1 pixels, rendering it virtually invisible.
The solution is to either give these frames an explicit size, or add the frames to the window with options that cause them to fill the window.
For illustrative purposes I've changed the background color of the window to pink, and set the size of Menu to 200x200. As you can see in the following screenshot, the frame with the widgets is there, and becomes visible when you give it a larger size. Of course, one problem with place is it's up to you to calculate the appropriate size.
The better solution in this specific case would be to use the appropriate grid options to have the frames fill the window. You can do that by giving a weight to the row and column that the frames are in. Unused space in the parent frame will be allocated to the row and column with the widget.
root.grid_rowconfigure(0, weight=1)
root.grid_columnconfigure(0, weight=1)
Generally speaking, grid and pack are superior to place for implementing most layouts because they are able to automatically make all widgets fit into a window with very little work. With place it's up to you to do calculations for position and size, and to make sure that all ancestors are appropriately sized and are visible.
A:
You need to call root.grid_rowconfigure(0, weight=1) and root.grid_columnconfigure(0, weight=1) so that the shown frame use all the space of root window, otherwise the size of those frames are 1x1.
Also Menu.grid_columnconfigure(0, weight=1) is useless because widgets inside Menu are using .place().
|
Blank page when removing all mentions of grid()
|
I've switched from .grid() to .place() in my program, so I decided to remove a frame that contained the grid widgets:
BackButtonR = Button(registerPage, text="Back", command=lambda: show_frame(Menu))
BackButtonR.grid(row=0, column=0, sticky=W)
Button2F3 = Button(registerPage, text="Find")
Button2F3.grid(row=1, column=1)
Button3F3 = Button(registerPage, text="Calculate").grid(row=6, column=1)
LabelTitleF3 = Label(registerPage, text="Calculate Buy Price").grid(row=0, column=3)
label1F3 = Label(registerPage, text="Enter Ticker Symbol:").grid(row=1, column=0)
label2F3 = Label(registerPage, text="Expected CAGR").grid(row=2, column=0)
label3F3 = Label(registerPage, text="Years of Analysis").grid(row=3, column=0)
label4F3 = Label(registerPage, text="Expected PE Ratio").grid(row=4, column=0)
label5F3 = Label(registerPage, text="Desired Annual Return").grid(row=5, column=0)
entry1F3 = Entry(registerPage, width=7).grid(row=1, column=1, padx=0)
entry2F3 = Entry(registerPage).grid(row=2, column=1, pady=10, padx=0)
entry3F3 = Entry(registerPage).grid(row=3, column=1, pady=10, padx=0)
entry4F3 = Entry(registerPage).grid(row=4, column=1, pady=10, padx=0)
entry5F3 = Entry(registerPage).grid(row=, column=1, pady=10, padx=0)
But weirdly, when I rerun my program everything turns blank. This shouldn't happen, since I've removed any reference to .grid(), so the program should be working fine with .place(). Here is my full code:
print(220+135)
from tkinter import *
root = Tk()
root.title("Account Signup")
DarkBlue = "#2460A7"
LightBlue = "#B3C7D6"
root.geometry('350x230')
Menu = Frame(root)
loginPage = Frame(root)
registerPage = Frame(root)
for AllFrames in (Menu, loginPage, registerPage):
AllFrames.grid(row=0, column=0, sticky='nsew')
AllFrames.configure(bg=LightBlue)
def show_frame(frame):
frame.tkraise()
show_frame(Menu)
# ============= Menu Page =========
Menu.grid_columnconfigure(0, weight=1)
menuTitle = Label(Menu, text="Menu", font=("Arial", 25), bg=LightBlue)
menuTitle.place(x=130, y=25)
loginButton1 = Button(Menu, width=25, text="Login", command=lambda: show_frame(loginPage))
loginButton1.place(x=85, y=85)
registerButton1 = Button(Menu, width=25, text="Register", command=lambda: show_frame(registerPage))
registerButton1.place(x=85, y=115)
# ======== Login Page ===========
loginUsernameL = Label(loginPage, text='Username').place(x=30, y=60)
loginUsernameE = Entry(loginPage).place(x=120, y=60)
loginPasswordL = Label(loginPage, text='Password').place(x=30, y=90)
loginPasswordE = Entry(loginPage).place(x=120, y=90)
backButton = Button(loginPage, text='Back', command=lambda: show_frame(Menu)).place(x=0, y=0)
loginButton = Button(loginPage, text='Login', width=20).place(x=100, y=150)
# ======== Register Page ===========
root.mainloop()
Why is my program turning blank?
|
[
"When you use pack and grid, these functions will normally adjust the size of a widget's parent to fit all of its children. It's one of the most compelling reasons to use these geometry managers.\nWhen you use place this doesn't happen. If you use place to put a widget in a frame, the frame will not grow or shrink to fit the widget.\nIn your case you're creating Menu, loginPage and registerPage and not giving them a size so they default to 1x1 pixels. When you use place to add a widget to the frame, the frame will remain at 1x1 pixels, rendering it virtually invisible.\nThe solution is to either give these frames an explicit size, or add the frames to the window with options that cause them to fill the window.\nFor illustrative purposes I've changed the background color of the window to pink, and set the size of Menu to 200x200. As you can see in the following screenshot, the frame with the widgets is there, and becomes visible when you give it a larger size. Of course, one problem with place is it's up to you to calculate the appropriate size.\n\nThe better solution in this specific case would be to use the appropriate grid options to have the frames fill the window. You can do that by giving a weight to the row and column that the frames are in. Unused space in the parent frame will be allocated to the row and column with the widget.\nroot.grid_rowconfigure(0, weight=1)\nroot.grid_columnconfigure(0, weight=1)\n\n\n\nGenerally speaking, grid and pack are superior to place for implementing most layouts because they are able to automatically make all widgets fit into a window with very little work. With place it's up to you to do calculations for position and size, and to make sure that all ancestors are appropriately sized and are visible.\n",
"You need to call root.grid_rowconfigure(0, weight=1) and root.grid_columnconfigure(0, weight=1) so that the shown frame use all the space of root window, otherwise the size of those frames are 1x1.\nAlso Menu.grid_columnconfigure(0, weight=1) is useless because widgets inside Menu are using .place().\n"
] |
[
1,
0
] |
[] |
[] |
[
"grid",
"python",
"tkinter"
] |
stackoverflow_0074524438_grid_python_tkinter.txt
|
Q:
Python [WinError 3] The system cannot find the path specified
At first this script run fine but after it show this error "[WinError 3] The system cannot find the path specified" without changing anything in the script
import os
paths = os.listdir(r'C:\Users\Film\OneDrive\Documents\WORK\Blockfint\Richy_csv_files\Recovery_as_compu_11_14_2022_14_9_32\Tables')
def files_with_word(word:str, paths:list) -> str:
for path in paths:
with open(path, "r") as f:
if word in f.read():
yield path
for filepath in files_with_word("Admin", paths):
print(filepath)
I try uninstall all python and reinstall with python 3.11 64 bit it still not working
A:
The issue you are having looks like it is with not using absolute paths. paths = os.listdir(r'C:\Users\Film\OneDrive\Documents\WORK\Blockfint\Richy_csv_files\Recovery_as_compu_11_14_2022_14_9_32\Tables') will just get a list of filenames with no path info. So if you are not actually running the python file while in the same directory it will produce that file not found error.
In the for loop I just ocncantenated the source directory and filename together to get the full path to open.
You will also want to filter out directories since the current code would also try to open a directory as a file and cause an error.
import os
src = r'C:\Users\Film\OneDrive\Documents\WORK\Blockfint\Richy_csv_files\Recovery_as_compu_11_14_2022_14_9_32\Tables'
files = os.listdir(src)
# only get files. filter out directories
files = [f for f in files if os.path.isfile(src+'/'+f)]
def files_with_word(word:str, files:list) -> str:
for file in files:
# create full path to file
full_path = src + "\\" + file
#open using full path
print(full_path)
with open(full_path, "r") as f:
if word in f.read():
yield file
for filepath in files_with_word("Admin", files):
print(filepath)
|
Python [WinError 3] The system cannot find the path specified
|
At first this script run fine but after it show this error "[WinError 3] The system cannot find the path specified" without changing anything in the script
import os
paths = os.listdir(r'C:\Users\Film\OneDrive\Documents\WORK\Blockfint\Richy_csv_files\Recovery_as_compu_11_14_2022_14_9_32\Tables')
def files_with_word(word:str, paths:list) -> str:
for path in paths:
with open(path, "r") as f:
if word in f.read():
yield path
for filepath in files_with_word("Admin", paths):
print(filepath)
I try uninstall all python and reinstall with python 3.11 64 bit it still not working
|
[
"The issue you are having looks like it is with not using absolute paths. paths = os.listdir(r'C:\\Users\\Film\\OneDrive\\Documents\\WORK\\Blockfint\\Richy_csv_files\\Recovery_as_compu_11_14_2022_14_9_32\\Tables') will just get a list of filenames with no path info. So if you are not actually running the python file while in the same directory it will produce that file not found error.\nIn the for loop I just ocncantenated the source directory and filename together to get the full path to open.\nYou will also want to filter out directories since the current code would also try to open a directory as a file and cause an error.\nimport os\n\nsrc = r'C:\\Users\\Film\\OneDrive\\Documents\\WORK\\Blockfint\\Richy_csv_files\\Recovery_as_compu_11_14_2022_14_9_32\\Tables'\nfiles = os.listdir(src)\n\n\n# only get files. filter out directories \nfiles = [f for f in files if os.path.isfile(src+'/'+f)] \n\n\ndef files_with_word(word:str, files:list) -> str:\n for file in files:\n # create full path to file\n full_path = src + \"\\\\\" + file\n \n #open using full path\n print(full_path)\n with open(full_path, \"r\") as f:\n if word in f.read():\n yield file\n\n\nfor filepath in files_with_word(\"Admin\", files):\n print(filepath)\n\n \n\n"
] |
[
0
] |
[] |
[] |
[
"python",
"visual_studio_code",
"window"
] |
stackoverflow_0074521325_python_visual_studio_code_window.txt
|
Q:
How to convert AVIF To PNG with Python?
I have an image file in avif format
How can I convert this file to png format?
I found some code to convert jpg files to avif, but I didn't find any code to reconvert them.
A:
You need to install this modules: pip install pillow-avif-plugin Pillow
Then:
from PIL import Image
import pillow_avif
img = Image.open('input.avif')
img.save('output.png')
|
How to convert AVIF To PNG with Python?
|
I have an image file in avif format
How can I convert this file to png format?
I found some code to convert jpg files to avif, but I didn't find any code to reconvert them.
|
[
"You need to install this modules: pip install pillow-avif-plugin Pillow\nThen:\nfrom PIL import Image\nimport pillow_avif\n\nimg = Image.open('input.avif')\nimg.save('output.png')\n\n"
] |
[
0
] |
[] |
[] |
[
"image",
"python"
] |
stackoverflow_0074527775_image_python.txt
|
Q:
VS Code / python importing issue when running a script for the first time
I am running a python script on VS Code and I am getting a package importing error but only the first time I run it after opening VS Code. If I run the same script again I don't get any errors, which makes me think there is something important being loaded only after I run it the first time. Any ideas of what might be causing this? I am running a python script imports numpy (or pandas, which uses numpy). The error is shown below.
Exception has occurred: ImportError
Unable to import required dependencies:
numpy:
IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE!
Importing the numpy C-extensions failed. This error can happen for
many reasons, often due to issues with your setup or how NumPy was
installed.
Importing the numpy C-extensions failed. This error can happen for many
reasons, often due to issues with your setup or how NumPy was installed.
We have compiled some common reasons and troubleshooting tips at:
https://numpy.org/devdocs/user/troubleshooting-importerror.html
Please note and check the following:
The Python version is: Python3.8 from
"C:\Users\gcampos.conda\envs<env name>\python.exe"
The NumPy version is: "1.23.3"
and make sure that they are the versions you expect. Please carefully
study the documentation linked above for further help.
Original error was: DLL load failed while importing _multiarray_umath:
The specified module could not be found.
To be clear, what is baffling to me is that the same script runs on the second try. Any thoughts on why?
Thank you.
A:
This seems to be a solved problem. You can refer to this answer.
Add the following path to the system environment variable PATH (Note that this needs to be adjusted according to your actual path. The comment supplied that adding...\Scripts and... \Library\bin solves this problem):
C:\Users\<myusername>\AppData\Local\Continuum\Anaconda3\Scripts\
C:\Users\<myusername>\AppData\Local\Continuum\Anaconda3\Library\
C:\Users\<myusername>\AppData\Local\Continuum\Anaconda3\Library\bin\
C:\Users\<myusername>\AppData\Local\Continuum\Anaconda3\Library\mingw-w64\bin\
|
VS Code / python importing issue when running a script for the first time
|
I am running a python script on VS Code and I am getting a package importing error but only the first time I run it after opening VS Code. If I run the same script again I don't get any errors, which makes me think there is something important being loaded only after I run it the first time. Any ideas of what might be causing this? I am running a python script imports numpy (or pandas, which uses numpy). The error is shown below.
Exception has occurred: ImportError
Unable to import required dependencies:
numpy:
IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE!
Importing the numpy C-extensions failed. This error can happen for
many reasons, often due to issues with your setup or how NumPy was
installed.
Importing the numpy C-extensions failed. This error can happen for many
reasons, often due to issues with your setup or how NumPy was installed.
We have compiled some common reasons and troubleshooting tips at:
https://numpy.org/devdocs/user/troubleshooting-importerror.html
Please note and check the following:
The Python version is: Python3.8 from
"C:\Users\gcampos.conda\envs<env name>\python.exe"
The NumPy version is: "1.23.3"
and make sure that they are the versions you expect. Please carefully
study the documentation linked above for further help.
Original error was: DLL load failed while importing _multiarray_umath:
The specified module could not be found.
To be clear, what is baffling to me is that the same script runs on the second try. Any thoughts on why?
Thank you.
|
[
"This seems to be a solved problem. You can refer to this answer.\nAdd the following path to the system environment variable PATH (Note that this needs to be adjusted according to your actual path. The comment supplied that adding...\\Scripts and... \\Library\\bin solves this problem):\nC:\\Users\\<myusername>\\AppData\\Local\\Continuum\\Anaconda3\\Scripts\\\nC:\\Users\\<myusername>\\AppData\\Local\\Continuum\\Anaconda3\\Library\\\nC:\\Users\\<myusername>\\AppData\\Local\\Continuum\\Anaconda3\\Library\\bin\\\nC:\\Users\\<myusername>\\AppData\\Local\\Continuum\\Anaconda3\\Library\\mingw-w64\\bin\\\n\n"
] |
[
0
] |
[] |
[] |
[
"numpy",
"python",
"visual_studio_code"
] |
stackoverflow_0074526548_numpy_python_visual_studio_code.txt
|
Q:
Python stable_baselines3 - AssertionError: The observation returned by `reset()` method must be an int
I am trying to learn reinforcement learning to train ai on custom games in python, and decided to use gym for the environment and stable-baselines3 for the training. I decided to start off with a basic tic tac toe environment. Here's my code
import gym
from gym import spaces
import numpy as np
from stable_baselines3.common.env_checker import check_env
class tictactoe(gym.Env):
def __init__(self):
#creating grid, action and obervation space
self.box = [0,0,0,0,0,0,0,0,0]
self.done=False
self.turn = 1
self.action_space = spaces.Discrete(9)
self.observation_space = spaces.Discrete(9)
def _get_obs(self):
#returns the observation (the grid)
return np.array(self.box)
def iswinner(self, b, l):
#function to check if a side has won
return (b[1] == l and b[2] == l and b[3] == l) or (b[4] == l and b[5] == l and b[6] == l) or (b[7] == l and b[8] == l and b[9] == l) or (b[1] == l and b[4] == l and b[7] == l) or (b[7] == l and b[5] == l and b[3] == l) or (b[1] == l and b[5] == l and b[9] == l) or (b[8] == l and b[5] == l and b[2] == l) or (b[9] == l and b[6] == l and b[3] == l)
def reset(self):
#resets the env (grid, turn and done variable) and returns the observation
self.box = [0,0,0,0,0,0,0,0,0]
self.turn = 1
self.done=False
return self._get_obs()
def step(self, action):
#gives negative reward for illegal move (square occupied)
if self.box[action] != 0:
return self._get_obs(), -10, True, {}
#enters a value (1 or 2) in the grid and flips the turn
self.box[action] = self.turn
self.turn = (1 if self.turn == 2 else 2)
reward = 0
#checks if the game is over and sets a reward (+5 win, 0 draw)
if self.iswinner([0]+self.box,1) and self.turn == 1: reward,self.done = 5,True
elif 0 not in self.box: reward,self.done = 0,True
#returns the observation (grid), reward, if the game is finished and extra information (empty dict for me)
return self._get_obs(), reward, self.done, {}
def render(self):
#renders the board so it looks like a grid
print(self.box[:3],self.box[3:6],self.box[6:],sep='\n')
#checking the env
env = tictactoe()
print(check_env(env))
Trying this code, I got the error AssertionError: The observation returned by 'reset()' method must be an int. I completely do not understand how this is supposed to work. Since my reset function returns the obervation from _get_obs. Is it trying to say that my observation must be an integer? That makes even less sense as now I have no idea how I'm supposed to do that.
A:
When you do
self.observation_space = spaces.Discrete(9)
you're actually defining your observation space as a single value that can take in all values of {0, 1, 2, 3, 4, 5, 6, 7, 8} since you defined it as a discrete single-dimension space (aka an integer).
As you said you were trying to make a tic-tac-toe environment, I presume what you were actually trying to do was something like
self.observation_space = spaces.MultiDiscrete([3, 3, 3, 3, 3, 3, 3, 3, 3])
# or self.observation_space = spaces.MultiDiscrete(9 * [3]), which would be cleaner
which means you have 9 tiles in total and each tile can be in three different states (empty, X or O).
|
Python stable_baselines3 - AssertionError: The observation returned by `reset()` method must be an int
|
I am trying to learn reinforcement learning to train ai on custom games in python, and decided to use gym for the environment and stable-baselines3 for the training. I decided to start off with a basic tic tac toe environment. Here's my code
import gym
from gym import spaces
import numpy as np
from stable_baselines3.common.env_checker import check_env
class tictactoe(gym.Env):
def __init__(self):
#creating grid, action and obervation space
self.box = [0,0,0,0,0,0,0,0,0]
self.done=False
self.turn = 1
self.action_space = spaces.Discrete(9)
self.observation_space = spaces.Discrete(9)
def _get_obs(self):
#returns the observation (the grid)
return np.array(self.box)
def iswinner(self, b, l):
#function to check if a side has won
return (b[1] == l and b[2] == l and b[3] == l) or (b[4] == l and b[5] == l and b[6] == l) or (b[7] == l and b[8] == l and b[9] == l) or (b[1] == l and b[4] == l and b[7] == l) or (b[7] == l and b[5] == l and b[3] == l) or (b[1] == l and b[5] == l and b[9] == l) or (b[8] == l and b[5] == l and b[2] == l) or (b[9] == l and b[6] == l and b[3] == l)
def reset(self):
#resets the env (grid, turn and done variable) and returns the observation
self.box = [0,0,0,0,0,0,0,0,0]
self.turn = 1
self.done=False
return self._get_obs()
def step(self, action):
#gives negative reward for illegal move (square occupied)
if self.box[action] != 0:
return self._get_obs(), -10, True, {}
#enters a value (1 or 2) in the grid and flips the turn
self.box[action] = self.turn
self.turn = (1 if self.turn == 2 else 2)
reward = 0
#checks if the game is over and sets a reward (+5 win, 0 draw)
if self.iswinner([0]+self.box,1) and self.turn == 1: reward,self.done = 5,True
elif 0 not in self.box: reward,self.done = 0,True
#returns the observation (grid), reward, if the game is finished and extra information (empty dict for me)
return self._get_obs(), reward, self.done, {}
def render(self):
#renders the board so it looks like a grid
print(self.box[:3],self.box[3:6],self.box[6:],sep='\n')
#checking the env
env = tictactoe()
print(check_env(env))
Trying this code, I got the error AssertionError: The observation returned by 'reset()' method must be an int. I completely do not understand how this is supposed to work. Since my reset function returns the obervation from _get_obs. Is it trying to say that my observation must be an integer? That makes even less sense as now I have no idea how I'm supposed to do that.
|
[
"When you do\nself.observation_space = spaces.Discrete(9)\n\nyou're actually defining your observation space as a single value that can take in all values of {0, 1, 2, 3, 4, 5, 6, 7, 8} since you defined it as a discrete single-dimension space (aka an integer).\nAs you said you were trying to make a tic-tac-toe environment, I presume what you were actually trying to do was something like\nself.observation_space = spaces.MultiDiscrete([3, 3, 3, 3, 3, 3, 3, 3, 3])\n# or self.observation_space = spaces.MultiDiscrete(9 * [3]), which would be cleaner\n\nwhich means you have 9 tiles in total and each tile can be in three different states (empty, X or O).\n"
] |
[
0
] |
[] |
[] |
[
"openai_gym",
"python",
"reinforcement_learning",
"stable_baselines"
] |
stackoverflow_0073201176_openai_gym_python_reinforcement_learning_stable_baselines.txt
|
Q:
Text recognition and detection using TensorFlow
I a working on a text recognition project.
I have built a classifier using TensorFlow to predict digits but I would like to implement a more complex algorithm of text recognition by using text localization and text segmentation (separating each character) but I didn't find an implementation for those parts of the algorithms.
So, do you know some algorithms/implementation/tips I, using TensorFlow, to localize text and do text segmentation in natural scenes pictures (actually localize and segmentation of text in the scoreboard for sports pictures)?
Thank you very much for any help.
A:
To group elements on a page, like paragraphs of text and images, you can use some clustering algo, and/or blob detection with some tresholds.
You can use Radon transform to recognize lines and detect skew of a scanned page.
I think that for character separation you will have to mess with fonts. Some polynomial matching/fitting or something. (this is a very wild guess for now, don't take it seriously).
But similar aproach would allow you to get the character out of the line and recognize it in same step.
As for recognition, once you have a character, there is a nice trigonometric trick of comparing angles of the character to the angles stored in a database.
Works great on handwriting too.
I am not an expert on how page segmentation exactly works, but it seems that I am on my way to become one. Just working on a project including it.
So give me a month and I'll be able to tell you more. :D
Anyway, you should go and read Tesseract code to see how HP and Google did it there. It should give you pretty good ideas.
Good luck!
A:
After you are done with Object Detection, you can perform text detection which can be passed on to tesseract. There can multiple variation to enhance image before passing it to detector function.
Reference Papers
https://arxiv.org/abs/1704.03155v2
https://arxiv.org/pdf/2002.07662.pdf
def text_detector(image):
#hasFrame, image = cap.read()
orig = image
(H, W) = image.shape[:2]
(newW, newH) = (640, 320)
rW = W / float(newW)
rH = H / float(newH)
image = cv2.resize(image, (newW, newH))
(H, W) = image.shape[:2]
layerNames = [
"feature_fusion/Conv_7/Sigmoid",
"feature_fusion/concat_3"]
blob = cv2.dnn.blobFromImage(image, 1.0, (W, H),
(123.68, 116.78, 103.94), swapRB=True, crop=False)
net.setInput(blob)
(scores, geometry) = net.forward(layerNames)
(numRows, numCols) = scores.shape[2:4]
rects = []
confidences = []
for y in range(0, numRows):
scoresData = scores[0, 0, y]
xData0 = geometry[0, 0, y]
xData1 = geometry[0, 1, y]
xData2 = geometry[0, 2, y]
xData3 = geometry[0, 3, y]
anglesData = geometry[0, 4, y]
# loop over the number of columns
for x in range(0, numCols):
# if our score does not have sufficient probability, ignore it
if scoresData[x] < 0.5:
continue
# compute the offset factor as our resulting feature maps will
# be 4x smaller than the input image
(offsetX, offsetY) = (x * 4.0, y * 4.0)
# extract the rotation angle for the prediction and then
# compute the sin and cosine
angle = anglesData[x]
cos = np.cos(angle)
sin = np.sin(angle)
# use the geometry volume to derive the width and height of
# the bounding box
h = xData0[x] + xData2[x]
w = xData1[x] + xData3[x]
# compute both the starting and ending (x, y)-coordinates for
# the text prediction bounding box
endX = int(offsetX + (cos * xData1[x]) + (sin * xData2[x]))
endY = int(offsetY - (sin * xData1[x]) + (cos * xData2[x]))
startX = int(endX - w)
startY = int(endY - h)
# add the bounding box coordinates and probability score to
# our respective lists
rects.append((startX, startY, endX, endY))
confidences.append(scoresData[x])
boxes = non_max_suppression(np.array(rects), probs=confidences)
for (startX, startY, endX, endY) in boxes:
startX = int(startX * rW)
startY = int(startY * rH)
endX = int(endX * rW)
endY = int(endY * rH)
# draw the bounding box on the image
cv2.rectangle(orig, (startX, startY), (endX, endY), (0, 255, 0), 3)
return orig
|
Text recognition and detection using TensorFlow
|
I a working on a text recognition project.
I have built a classifier using TensorFlow to predict digits but I would like to implement a more complex algorithm of text recognition by using text localization and text segmentation (separating each character) but I didn't find an implementation for those parts of the algorithms.
So, do you know some algorithms/implementation/tips I, using TensorFlow, to localize text and do text segmentation in natural scenes pictures (actually localize and segmentation of text in the scoreboard for sports pictures)?
Thank you very much for any help.
|
[
"To group elements on a page, like paragraphs of text and images, you can use some clustering algo, and/or blob detection with some tresholds.\nYou can use Radon transform to recognize lines and detect skew of a scanned page.\nI think that for character separation you will have to mess with fonts. Some polynomial matching/fitting or something. (this is a very wild guess for now, don't take it seriously).\nBut similar aproach would allow you to get the character out of the line and recognize it in same step.\nAs for recognition, once you have a character, there is a nice trigonometric trick of comparing angles of the character to the angles stored in a database.\nWorks great on handwriting too.\nI am not an expert on how page segmentation exactly works, but it seems that I am on my way to become one. Just working on a project including it.\nSo give me a month and I'll be able to tell you more. :D\nAnyway, you should go and read Tesseract code to see how HP and Google did it there. It should give you pretty good ideas.\nGood luck!\n",
"After you are done with Object Detection, you can perform text detection which can be passed on to tesseract. There can multiple variation to enhance image before passing it to detector function.\nReference Papers\nhttps://arxiv.org/abs/1704.03155v2\nhttps://arxiv.org/pdf/2002.07662.pdf\ndef text_detector(image):\n#hasFrame, image = cap.read()\norig = image\n(H, W) = image.shape[:2]\n\n(newW, newH) = (640, 320)\nrW = W / float(newW)\nrH = H / float(newH)\n\nimage = cv2.resize(image, (newW, newH))\n(H, W) = image.shape[:2]\n\nlayerNames = [\n \"feature_fusion/Conv_7/Sigmoid\",\n \"feature_fusion/concat_3\"]\n\n\nblob = cv2.dnn.blobFromImage(image, 1.0, (W, H),\n (123.68, 116.78, 103.94), swapRB=True, crop=False)\n\nnet.setInput(blob)\n(scores, geometry) = net.forward(layerNames)\n\n(numRows, numCols) = scores.shape[2:4]\nrects = []\nconfidences = []\n\nfor y in range(0, numRows):\n\n scoresData = scores[0, 0, y]\n xData0 = geometry[0, 0, y]\n xData1 = geometry[0, 1, y]\n xData2 = geometry[0, 2, y]\n xData3 = geometry[0, 3, y]\n anglesData = geometry[0, 4, y]\n\n # loop over the number of columns\n for x in range(0, numCols):\n # if our score does not have sufficient probability, ignore it\n if scoresData[x] < 0.5:\n continue\n\n # compute the offset factor as our resulting feature maps will\n # be 4x smaller than the input image\n (offsetX, offsetY) = (x * 4.0, y * 4.0)\n\n # extract the rotation angle for the prediction and then\n # compute the sin and cosine\n angle = anglesData[x]\n cos = np.cos(angle)\n sin = np.sin(angle)\n\n # use the geometry volume to derive the width and height of\n # the bounding box\n h = xData0[x] + xData2[x]\n w = xData1[x] + xData3[x]\n\n # compute both the starting and ending (x, y)-coordinates for\n # the text prediction bounding box\n endX = int(offsetX + (cos * xData1[x]) + (sin * xData2[x]))\n endY = int(offsetY - (sin * xData1[x]) + (cos * xData2[x]))\n startX = int(endX - w)\n startY = int(endY - h)\n\n # add the bounding box coordinates and probability score to\n # our respective lists\n rects.append((startX, startY, endX, endY))\n confidences.append(scoresData[x])\n\nboxes = non_max_suppression(np.array(rects), probs=confidences)\n\nfor (startX, startY, endX, endY) in boxes:\n\n startX = int(startX * rW)\n startY = int(startY * rH)\n endX = int(endX * rW)\n endY = int(endY * rH)\n\n # draw the bounding box on the image\n cv2.rectangle(orig, (startX, startY), (endX, endY), (0, 255, 0), 3)\nreturn orig\n\n"
] |
[
1,
0
] |
[] |
[] |
[
"deep_learning",
"python",
"tensorflow",
"text_classification",
"text_recognition"
] |
stackoverflow_0042868546_deep_learning_python_tensorflow_text_classification_text_recognition.txt
|
Q:
How to train custom model for Tensorflow Lite and have the output be a .TFLITE file
I'm new to tensorflow and object detetion, and any help would be greatly appreciated! I got a database of 50 photos, used this video to get me started, and it DID work with Google's Sample Model (I'm using a RPi4B with 8 GB of RAM), then I wanted to create my own model. I tried a couple of options, but ultimately failed since the type of files I needed were a .TFLITE and a .txt one with the labels. I only managed to get a .LITE file which from what I tested didn't work
I tried his google collab sheet but the terminal got stuck at step 5 when I pressed the button to train the model, so I tried Edge Impulse but the output models were all in a .LITE file, and didn't provide a labelmap.txt file for the code. I tried manually changing the extension from .LITE to .TFLITE since according to this thread it was supposed to work, but it didn't!
I need this to be ready in 3 days from now... Isn't there a more beginner-friendly way to do this? How can I get a valid .TFLITE model to work with my RPI4? If I have to, I will change the code for this to work. Here's the code the tutorial provided:
######## Webcam Object Detection Using Tensorflow-trained Classifier #########
#
# Author: Evan Juras
# Date: 10/27/19
# Description:
# This program uses a TensorFlow Lite model to perform object detection on a live webcam
# feed. It draws boxes and scores around the objects of interest in each frame from the
# webcam. To improve FPS, the webcam object runs in a separate thread from the main program.
# This script will work with either a Picamera or regular USB webcam.
#
# This code is based off the TensorFlow Lite image classification example at:
# https://github.com/tensorflow/tensorflow/blob/master/tensorflow/lite/examples/python/label_image.py
#
# I added my own method of drawing boxes and labels using OpenCV.
# Import packages
import os
import argparse
import cv2
import numpy as np
import sys
import time
from threading import Thread
import importlib.util
# Define VideoStream class to handle streaming of video from webcam in separate processing thread
# Source - Adrian Rosebrock, PyImageSearch: https://www.pyimagesearch.com/2015/12/28/increasing-raspberry-pi-fps-with-python-and-opencv/
class VideoStream:
"""Camera object that controls video streaming from the Picamera"""
def _init_(self,resolution=(640,480),framerate=30):
# Initialize the PiCamera and the camera image stream
self.stream = cv2.VideoCapture(0)
ret = self.stream.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc(*'MJPG'))
ret = self.stream.set(3,resolution[0])
ret = self.stream.set(4,resolution[1])
# Read first frame from the stream
(self.grabbed, self.frame) = self.stream.read()
# Variable to control when the camera is stopped
self.stopped = False
def start(self):
# Start the thread that reads frames from the video stream
Thread(target=self.update,args=()).start()
return self
def update(self):
# Keep looping indefinitely until the thread is stopped
while True:
# If the camera is stopped, stop the thread
if self.stopped:
# Close camera resources
self.stream.release()
return
# Otherwise, grab the next frame from the stream
(self.grabbed, self.frame) = self.stream.read()
def read(self):
# Return the most recent frame
return self.frame
def stop(self):
# Indicate that the camera and thread should be stopped
self.stopped = True
# Define and parse input arguments
parser = argparse.ArgumentParser()
parser.add_argument('--modeldir', help='Folder the .tflite file is located in',
required=True)
parser.add_argument('--graph', help='Name of the .tflite file, if different than detect.tflite',
default='detect.lite')
parser.add_argument('--labels', help='Name of the labelmap file, if different than labelmap.txt',
default='labelmap.txt')
parser.add_argument('--threshold', help='Minimum confidence threshold for displaying detected objects',
default=0.5)
parser.add_argument('--resolution', help='Desired webcam resolution in WxH. If the webcam does not support the resolution entered, errors may occur.',
default='1280x720')
parser.add_argument('--edgetpu', help='Use Coral Edge TPU Accelerator to speed up detection',
action='store_true')
args = parser.parse_args()
MODEL_NAME = args.modeldir
GRAPH_NAME = args.graph
LABELMAP_NAME = args.labels
min_conf_threshold = float(args.threshold)
resW, resH = args.resolution.split('x')
imW, imH = int(resW), int(resH)
use_TPU = args.edgetpu
# Import TensorFlow libraries
# If tflite_runtime is installed, import interpreter from tflite_runtime, else import from regular tensorflow
# If using Coral Edge TPU, import the load_delegate library
pkg = importlib.util.find_spec('tflite_runtime')
if pkg:
from tflite_runtime.interpreter import Interpreter
if use_TPU:
from tflite_runtime.interpreter import load_delegate
else:
from tensorflow.lite.python.interpreter import Interpreter
if use_TPU:
from tensorflow.lite.python.interpreter import load_delegate
# If using Edge TPU, assign filename for Edge TPU model
if use_TPU:
# If user has specified the name of the .tflite file, use that name, otherwise use default 'edgetpu.tflite'
if (GRAPH_NAME == 'detect.lite'):
GRAPH_NAME = 'edgetpu.tflite'
# Get path to current working directory
CWD_PATH = os.getcwd()
# Path to .tflite file, which contains the model that is used for object detection
PATH_TO_CKPT = os.path.join(CWD_PATH,MODEL_NAME,GRAPH_NAME)
# Path to label map file
PATH_TO_LABELS = os.path.join(CWD_PATH,MODEL_NAME,LABELMAP_NAME)
# Load the label map
with open(PATH_TO_LABELS, 'r') as f:
labels = [line.strip() for line in f.readlines()]
# Have to do a weird fix for label map if using the COCO "starter model" from
# https://www.tensorflow.org/lite/models/object_detection/overview
# First label is '???', which has to be removed.
if labels[0] == '???':
del(labels[0])
# Load the Tensorflow Lite model.
# If using Edge TPU, use special load_delegate argument
if use_TPU:
interpreter = Interpreter(model_path=PATH_TO_CKPT,
experimental_delegates=[load_delegate('libedgetpu.so.1.0')])
print(PATH_TO_CKPT)
else:
interpreter = Interpreter(model_path=PATH_TO_CKPT)
interpreter.allocate_tensors()
# Get model details
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
height = input_details[0]['shape'][1]
width = input_details[0]['shape'][2]
floating_model = (input_details[0]['dtype'] == np.float32)
input_mean = 127.5
input_std = 127.5
# Check output layer name to determine if this model was created with TF2 or TF1,
# because outputs are ordered differently for TF2 and TF1 models
outname = output_details[0]['name']
if ('StatefulPartitionedCall' in outname): # This is a TF2 model
boxes_idx, classes_idx, scores_idx = 1, 3, 0
else: # This is a TF1 model
boxes_idx, classes_idx, scores_idx = 0, 1, 2
# Initialize frame rate calculation
frame_rate_calc = 1
freq = cv2.getTickFrequency()
# Initialize video stream
videostream = VideoStream(resolution=(imW,imH),framerate=30).start()
time.sleep(1)
#for frame1 in camera.capture_continuous(rawCapture, format="bgr",use_video_port=True):
while True:
# Start timer (for calculating frame rate)
t1 = cv2.getTickCount()
# Grab frame from video stream
frame1 = videostream.read()
# Acquire frame and resize to expected shape [1xHxWx3]
frame = frame1.copy()
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
frame_resized = cv2.resize(frame_rgb, (width, height))
input_data = np.expand_dims(frame_resized, axis=0)
# Normalize pixel values if using a floating model (i.e. if model is non-quantized)
if floating_model:
input_data = (np.float32(input_data) - input_mean) / input_std
# Perform the actual detection by running the model with the image as input
interpreter.set_tensor(input_details[0]['index'],input_data)
interpreter.invoke()
# Retrieve detection results
boxes = interpreter.get_tensor(output_details[boxes_idx]['index'])[0] # Bounding box coordinates of detected objects
classes = interpreter.get_tensor(output_details[classes_idx]['index'])[0] # Class index of detected objects
scores = interpreter.get_tensor(output_details[scores_idx]['index'])[0] # Confidence of detected objects
# Loop over all detections and draw detection box if confidence is above minimum threshold
for i in range(len(scores)):
if ((scores[i] > min_conf_threshold) and (scores[i] <= 1.0)):
# Get bounding box coordinates and draw box
# Interpreter can return coordinates that are outside of image dimensions, need to force them to be within image using max() and min()
ymin = int(max(1,(boxes[i][0] * imH)))
xmin = int(max(1,(boxes[i][1] * imW)))
ymax = int(min(imH,(boxes[i][2] * imH)))
xmax = int(min(imW,(boxes[i][3] * imW)))
cv2.rectangle(frame, (xmin,ymin), (xmax,ymax), (10, 255, 0), 2)
# Draw label
object_name = labels[int(classes[i])] # Look up object name from "labels" array using class index
label = '%s: %d%%' % (object_name, int(scores[i]*100)) # Example: 'person: 72%'
if object_name=='person' and int(scores[i]*100)>65:
print("YES")
else:
print("NO")
labelSize, baseLine = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.7, 2) # Get font size
label_ymin = max(ymin, labelSize[1] + 10) # Make sure not to draw label too close to top of window
cv2.rectangle(frame, (xmin, label_ymin-labelSize[1]-10), (xmin+labelSize[0], label_ymin+baseLine-10), (255, 255, 255), cv2.FILLED) # Draw white box to put label text in
cv2.putText(frame, label, (xmin, label_ymin-7), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 0), 2) # Draw label text
# Draw framerate in corner of frame
cv2.putText(frame,'FPS: {0:.2f}'.format(frame_rate_calc),(30,50),cv2.FONT_HERSHEY_SIMPLEX,1,(255,255,0),2,cv2.LINE_AA)
# All the results have been drawn on the frame, so it's time to display it.
cv2.imshow('Object detector', frame)
# Calculate framerate
t2 = cv2.getTickCount()
time1 = (t2-t1)/freq
frame_rate_calc= 1/time1
# Press 'q' to quit
if cv2.waitKey(1) == ord('q'):
break
# Clean up
cv2.destroyAllWindows()
videostream.stop()
```
A:
Easy, just downgrade to OpenCV version 3.4.16, and use Tensorflow 1.0 instead of 2.0 and that should solve all your problems. That will allow the use of .LITE files, as well that of .TFLITE
Also, try increasing the resolution to a 720x1280, most likely that can cause a ton of errors as well when working with tensorflow
A:
Take a look here: https://www.tensorflow.org/tutorials/images/classification
This notebook sets up a new classification model, and ends with "Convert the Keras Sequential model to a TensorFlow Lite model"
https://www.tensorflow.org/tutorials/images/classification#convert_the_keras_sequential_model_to_a_tensorflow_lite_model
# Convert the model.
converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()
# Save the model.
with open('model.tflite', 'wb') as f:
f.write(tflite_model)
This reliably produces a tflite model from a standard tf model.
|
How to train custom model for Tensorflow Lite and have the output be a .TFLITE file
|
I'm new to tensorflow and object detetion, and any help would be greatly appreciated! I got a database of 50 photos, used this video to get me started, and it DID work with Google's Sample Model (I'm using a RPi4B with 8 GB of RAM), then I wanted to create my own model. I tried a couple of options, but ultimately failed since the type of files I needed were a .TFLITE and a .txt one with the labels. I only managed to get a .LITE file which from what I tested didn't work
I tried his google collab sheet but the terminal got stuck at step 5 when I pressed the button to train the model, so I tried Edge Impulse but the output models were all in a .LITE file, and didn't provide a labelmap.txt file for the code. I tried manually changing the extension from .LITE to .TFLITE since according to this thread it was supposed to work, but it didn't!
I need this to be ready in 3 days from now... Isn't there a more beginner-friendly way to do this? How can I get a valid .TFLITE model to work with my RPI4? If I have to, I will change the code for this to work. Here's the code the tutorial provided:
######## Webcam Object Detection Using Tensorflow-trained Classifier #########
#
# Author: Evan Juras
# Date: 10/27/19
# Description:
# This program uses a TensorFlow Lite model to perform object detection on a live webcam
# feed. It draws boxes and scores around the objects of interest in each frame from the
# webcam. To improve FPS, the webcam object runs in a separate thread from the main program.
# This script will work with either a Picamera or regular USB webcam.
#
# This code is based off the TensorFlow Lite image classification example at:
# https://github.com/tensorflow/tensorflow/blob/master/tensorflow/lite/examples/python/label_image.py
#
# I added my own method of drawing boxes and labels using OpenCV.
# Import packages
import os
import argparse
import cv2
import numpy as np
import sys
import time
from threading import Thread
import importlib.util
# Define VideoStream class to handle streaming of video from webcam in separate processing thread
# Source - Adrian Rosebrock, PyImageSearch: https://www.pyimagesearch.com/2015/12/28/increasing-raspberry-pi-fps-with-python-and-opencv/
class VideoStream:
"""Camera object that controls video streaming from the Picamera"""
def _init_(self,resolution=(640,480),framerate=30):
# Initialize the PiCamera and the camera image stream
self.stream = cv2.VideoCapture(0)
ret = self.stream.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc(*'MJPG'))
ret = self.stream.set(3,resolution[0])
ret = self.stream.set(4,resolution[1])
# Read first frame from the stream
(self.grabbed, self.frame) = self.stream.read()
# Variable to control when the camera is stopped
self.stopped = False
def start(self):
# Start the thread that reads frames from the video stream
Thread(target=self.update,args=()).start()
return self
def update(self):
# Keep looping indefinitely until the thread is stopped
while True:
# If the camera is stopped, stop the thread
if self.stopped:
# Close camera resources
self.stream.release()
return
# Otherwise, grab the next frame from the stream
(self.grabbed, self.frame) = self.stream.read()
def read(self):
# Return the most recent frame
return self.frame
def stop(self):
# Indicate that the camera and thread should be stopped
self.stopped = True
# Define and parse input arguments
parser = argparse.ArgumentParser()
parser.add_argument('--modeldir', help='Folder the .tflite file is located in',
required=True)
parser.add_argument('--graph', help='Name of the .tflite file, if different than detect.tflite',
default='detect.lite')
parser.add_argument('--labels', help='Name of the labelmap file, if different than labelmap.txt',
default='labelmap.txt')
parser.add_argument('--threshold', help='Minimum confidence threshold for displaying detected objects',
default=0.5)
parser.add_argument('--resolution', help='Desired webcam resolution in WxH. If the webcam does not support the resolution entered, errors may occur.',
default='1280x720')
parser.add_argument('--edgetpu', help='Use Coral Edge TPU Accelerator to speed up detection',
action='store_true')
args = parser.parse_args()
MODEL_NAME = args.modeldir
GRAPH_NAME = args.graph
LABELMAP_NAME = args.labels
min_conf_threshold = float(args.threshold)
resW, resH = args.resolution.split('x')
imW, imH = int(resW), int(resH)
use_TPU = args.edgetpu
# Import TensorFlow libraries
# If tflite_runtime is installed, import interpreter from tflite_runtime, else import from regular tensorflow
# If using Coral Edge TPU, import the load_delegate library
pkg = importlib.util.find_spec('tflite_runtime')
if pkg:
from tflite_runtime.interpreter import Interpreter
if use_TPU:
from tflite_runtime.interpreter import load_delegate
else:
from tensorflow.lite.python.interpreter import Interpreter
if use_TPU:
from tensorflow.lite.python.interpreter import load_delegate
# If using Edge TPU, assign filename for Edge TPU model
if use_TPU:
# If user has specified the name of the .tflite file, use that name, otherwise use default 'edgetpu.tflite'
if (GRAPH_NAME == 'detect.lite'):
GRAPH_NAME = 'edgetpu.tflite'
# Get path to current working directory
CWD_PATH = os.getcwd()
# Path to .tflite file, which contains the model that is used for object detection
PATH_TO_CKPT = os.path.join(CWD_PATH,MODEL_NAME,GRAPH_NAME)
# Path to label map file
PATH_TO_LABELS = os.path.join(CWD_PATH,MODEL_NAME,LABELMAP_NAME)
# Load the label map
with open(PATH_TO_LABELS, 'r') as f:
labels = [line.strip() for line in f.readlines()]
# Have to do a weird fix for label map if using the COCO "starter model" from
# https://www.tensorflow.org/lite/models/object_detection/overview
# First label is '???', which has to be removed.
if labels[0] == '???':
del(labels[0])
# Load the Tensorflow Lite model.
# If using Edge TPU, use special load_delegate argument
if use_TPU:
interpreter = Interpreter(model_path=PATH_TO_CKPT,
experimental_delegates=[load_delegate('libedgetpu.so.1.0')])
print(PATH_TO_CKPT)
else:
interpreter = Interpreter(model_path=PATH_TO_CKPT)
interpreter.allocate_tensors()
# Get model details
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
height = input_details[0]['shape'][1]
width = input_details[0]['shape'][2]
floating_model = (input_details[0]['dtype'] == np.float32)
input_mean = 127.5
input_std = 127.5
# Check output layer name to determine if this model was created with TF2 or TF1,
# because outputs are ordered differently for TF2 and TF1 models
outname = output_details[0]['name']
if ('StatefulPartitionedCall' in outname): # This is a TF2 model
boxes_idx, classes_idx, scores_idx = 1, 3, 0
else: # This is a TF1 model
boxes_idx, classes_idx, scores_idx = 0, 1, 2
# Initialize frame rate calculation
frame_rate_calc = 1
freq = cv2.getTickFrequency()
# Initialize video stream
videostream = VideoStream(resolution=(imW,imH),framerate=30).start()
time.sleep(1)
#for frame1 in camera.capture_continuous(rawCapture, format="bgr",use_video_port=True):
while True:
# Start timer (for calculating frame rate)
t1 = cv2.getTickCount()
# Grab frame from video stream
frame1 = videostream.read()
# Acquire frame and resize to expected shape [1xHxWx3]
frame = frame1.copy()
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
frame_resized = cv2.resize(frame_rgb, (width, height))
input_data = np.expand_dims(frame_resized, axis=0)
# Normalize pixel values if using a floating model (i.e. if model is non-quantized)
if floating_model:
input_data = (np.float32(input_data) - input_mean) / input_std
# Perform the actual detection by running the model with the image as input
interpreter.set_tensor(input_details[0]['index'],input_data)
interpreter.invoke()
# Retrieve detection results
boxes = interpreter.get_tensor(output_details[boxes_idx]['index'])[0] # Bounding box coordinates of detected objects
classes = interpreter.get_tensor(output_details[classes_idx]['index'])[0] # Class index of detected objects
scores = interpreter.get_tensor(output_details[scores_idx]['index'])[0] # Confidence of detected objects
# Loop over all detections and draw detection box if confidence is above minimum threshold
for i in range(len(scores)):
if ((scores[i] > min_conf_threshold) and (scores[i] <= 1.0)):
# Get bounding box coordinates and draw box
# Interpreter can return coordinates that are outside of image dimensions, need to force them to be within image using max() and min()
ymin = int(max(1,(boxes[i][0] * imH)))
xmin = int(max(1,(boxes[i][1] * imW)))
ymax = int(min(imH,(boxes[i][2] * imH)))
xmax = int(min(imW,(boxes[i][3] * imW)))
cv2.rectangle(frame, (xmin,ymin), (xmax,ymax), (10, 255, 0), 2)
# Draw label
object_name = labels[int(classes[i])] # Look up object name from "labels" array using class index
label = '%s: %d%%' % (object_name, int(scores[i]*100)) # Example: 'person: 72%'
if object_name=='person' and int(scores[i]*100)>65:
print("YES")
else:
print("NO")
labelSize, baseLine = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.7, 2) # Get font size
label_ymin = max(ymin, labelSize[1] + 10) # Make sure not to draw label too close to top of window
cv2.rectangle(frame, (xmin, label_ymin-labelSize[1]-10), (xmin+labelSize[0], label_ymin+baseLine-10), (255, 255, 255), cv2.FILLED) # Draw white box to put label text in
cv2.putText(frame, label, (xmin, label_ymin-7), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 0), 2) # Draw label text
# Draw framerate in corner of frame
cv2.putText(frame,'FPS: {0:.2f}'.format(frame_rate_calc),(30,50),cv2.FONT_HERSHEY_SIMPLEX,1,(255,255,0),2,cv2.LINE_AA)
# All the results have been drawn on the frame, so it's time to display it.
cv2.imshow('Object detector', frame)
# Calculate framerate
t2 = cv2.getTickCount()
time1 = (t2-t1)/freq
frame_rate_calc= 1/time1
# Press 'q' to quit
if cv2.waitKey(1) == ord('q'):
break
# Clean up
cv2.destroyAllWindows()
videostream.stop()
```
|
[
"Easy, just downgrade to OpenCV version 3.4.16, and use Tensorflow 1.0 instead of 2.0 and that should solve all your problems. That will allow the use of .LITE files, as well that of .TFLITE\nAlso, try increasing the resolution to a 720x1280, most likely that can cause a ton of errors as well when working with tensorflow\n",
"Take a look here: https://www.tensorflow.org/tutorials/images/classification\nThis notebook sets up a new classification model, and ends with \"Convert the Keras Sequential model to a TensorFlow Lite model\"\nhttps://www.tensorflow.org/tutorials/images/classification#convert_the_keras_sequential_model_to_a_tensorflow_lite_model\n# Convert the model.\nconverter = tf.lite.TFLiteConverter.from_keras_model(model)\ntflite_model = converter.convert()\n\n# Save the model.\nwith open('model.tflite', 'wb') as f:\n f.write(tflite_model)\n\nThis reliably produces a tflite model from a standard tf model.\n"
] |
[
0,
0
] |
[] |
[] |
[
"object_detection",
"python",
"raspberry_pi",
"tensorflow",
"tensorflow_lite"
] |
stackoverflow_0074247205_object_detection_python_raspberry_pi_tensorflow_tensorflow_lite.txt
|
Q:
Groupby and get just top 50% record based on one column pyspark
I have a dataframe like this:
id item_id score
1 6 1.1
2 6 1
3 6 1.4
7 6 1.3
8 2 1.2
9 2 1.8
1 4 2
10 4 1.1
2 4 1.9
8 4 1.2
. . .
Where combination of column id and item_id is primary key, but both will have duplicates as well.
Total unique id: 67689
Total unique item_id: 123123
Total records: 8334072747 (67689*123123)
Now I want to drop 50% of the data based on score but keeping all unique values from column item_id. For eg:
Let's say if I have 10 records with same item_id, so I want to drop 50% records with lowest score. So my unique item_id will still remain the same but I'll lose some id's. So basically for each item_id I'll have 50% of the original record.
Expected Output:
id item_id score
3 6 1.4
7 6 1.3
9 2 1.8
1 4 2
2 4 1.9
. . .
Try:
I can use window function over item column but I'm not sure how can I filter later based on percentage instead of value.
window = Window.partitionBy(df['item_id']).orderBy(df['score'].desc())
df.select('*', row_number().over(window).alias('rank'))
.filter(col('rank') <= 2)
A:
this should working using the row_number() and count() window functions. take the count() and divide by 2.
updated filter to handle case where there's only one record.
there's a case of how do you want to handle odd record counts.
for instance 50% of 3 records is 1.5..you can set row_num_val as a whole number by taking the ceiling or the floor of the decimal
from pyspark.sql import functions as F
from pyspark.sql.types import *
from pyspark.sql import Window
df = spark.createDataFrame(
[
(1, 6, 1.1),
(2, 6, 1.0),
(3, 6, 1.4),
(7, 6, 1.3),
(8, 2, 1.2),
(9, 2, 1.8),
(1, 4, 2.0),
(10, 4, 1.1),
(2, 4, 1.9),
(8, 4, 1.2),
],
["id", "item_id", "score"],
)
df_cnt_window = Window.partitionBy(
"item_id",
)
df_row_window = Window.partitionBy(
"item_id",
).orderBy(F.col("score").desc())
df = (
df
.withColumn(
"cnt",
F.count("*").over(df_cnt_window),
)
.withColumn(
"row_num",
F.row_number().over(df_row_window),
)
.withColumn(
"row_num_val", (F.col("cnt") / 2).cast(IntegerType())
)
.filter( (F.col("row_num") <= F.col("row_num_val")) | (F.col("row_num_val") == 0) )
.drop(F.col("row_num"))
.drop(F.col("row_num_val"))
.drop(F.col("cnt"))
)
df.show()
output:
+---+-------+-----+
| id|item_id|score|
+---+-------+-----+
| 3| 6| 1.4|
| 7| 6| 1.3|
| 9| 2| 1.8|
| 1| 4| 2.0|
| 2| 4| 1.9|
+---+-------+-----+
|
Groupby and get just top 50% record based on one column pyspark
|
I have a dataframe like this:
id item_id score
1 6 1.1
2 6 1
3 6 1.4
7 6 1.3
8 2 1.2
9 2 1.8
1 4 2
10 4 1.1
2 4 1.9
8 4 1.2
. . .
Where combination of column id and item_id is primary key, but both will have duplicates as well.
Total unique id: 67689
Total unique item_id: 123123
Total records: 8334072747 (67689*123123)
Now I want to drop 50% of the data based on score but keeping all unique values from column item_id. For eg:
Let's say if I have 10 records with same item_id, so I want to drop 50% records with lowest score. So my unique item_id will still remain the same but I'll lose some id's. So basically for each item_id I'll have 50% of the original record.
Expected Output:
id item_id score
3 6 1.4
7 6 1.3
9 2 1.8
1 4 2
2 4 1.9
. . .
Try:
I can use window function over item column but I'm not sure how can I filter later based on percentage instead of value.
window = Window.partitionBy(df['item_id']).orderBy(df['score'].desc())
df.select('*', row_number().over(window).alias('rank'))
.filter(col('rank') <= 2)
|
[
"this should working using the row_number() and count() window functions. take the count() and divide by 2.\nupdated filter to handle case where there's only one record.\nthere's a case of how do you want to handle odd record counts.\nfor instance 50% of 3 records is 1.5..you can set row_num_val as a whole number by taking the ceiling or the floor of the decimal\nfrom pyspark.sql import functions as F\nfrom pyspark.sql.types import *\nfrom pyspark.sql import Window\n\ndf = spark.createDataFrame(\n [\n (1, 6, 1.1),\n (2, 6, 1.0),\n (3, 6, 1.4),\n (7, 6, 1.3),\n (8, 2, 1.2),\n (9, 2, 1.8),\n (1, 4, 2.0),\n (10, 4, 1.1),\n (2, 4, 1.9),\n (8, 4, 1.2),\n \n \n ],\n [\"id\", \"item_id\", \"score\"],\n)\n\ndf_cnt_window = Window.partitionBy(\n \"item_id\",\n)\n\ndf_row_window = Window.partitionBy(\n \"item_id\",\n).orderBy(F.col(\"score\").desc())\n\ndf = (\n df\n .withColumn(\n \"cnt\",\n F.count(\"*\").over(df_cnt_window),\n )\n .withColumn(\n \"row_num\",\n F.row_number().over(df_row_window),\n )\n .withColumn(\n \"row_num_val\", (F.col(\"cnt\") / 2).cast(IntegerType())\n )\n .filter( (F.col(\"row_num\") <= F.col(\"row_num_val\")) | (F.col(\"row_num_val\") == 0) )\n .drop(F.col(\"row_num\"))\n .drop(F.col(\"row_num_val\"))\n .drop(F.col(\"cnt\"))\n \n)\n\ndf.show()\n\noutput:\n+---+-------+-----+\n| id|item_id|score|\n+---+-------+-----+\n| 3| 6| 1.4|\n| 7| 6| 1.3|\n| 9| 2| 1.8|\n| 1| 4| 2.0|\n| 2| 4| 1.9|\n+---+-------+-----+\n\n"
] |
[
3
] |
[] |
[] |
[
"apache_spark",
"apache_spark_sql",
"pyspark",
"python",
"sql"
] |
stackoverflow_0074527148_apache_spark_apache_spark_sql_pyspark_python_sql.txt
|
Q:
Convert arrays inside a list into a single array and append zeros
The objective of this code snippet was to create a 2D array of shape (10,10) with
array[0,0]=1;
array[0,9]=100; and
array[9,0]=50.
Complications arose when the interval between these elements had to be equal as shown in the expected output. Rows had to increment with equal intervals up-to 100 and columns had to increment with equal intervals up-to 50.
I know that my code has a logical error in list-comprehension for "matrix_list". But I'm not sure what the error is.
The code I wrote:
`import numpy as np`
`matrix_list = np.zeros((10,10), dtype = int)`
`matrix_list =
[(np.arange(column, 101, (100-1)/9).astype(int)) for column in np.arange(1, 51, (50-1)/9).astype(int)]`
`print(np.array(matrix_list))`
Expected Output:
[ 1, 12, 23, 34, 45, 56, 67, 78, 89, 100]
[ 6, 17, 28, 39, 50, 61, 72, 83, 94, 0]
[11, 22, 33, 44, 55, 66, 77, 88, 0, 0]
[17, 28, 39, 50, 61, 72, 83, 0, 0, 0]
[22, 33, 44, 55, 66, 77, 0, 0, 0, 0]
[28, 39, 50, 61, 72, 0, 0, 0, 0, 0]
[33, 44, 55, 66, 0, 0, 0, 0, 0, 0]
[39, 50, 61, 0, 0, 0, 0, 0, 0, 0]
[44, 55, 0, 0, 0, 0, 0, 0, 0, 0]
[50, 0, 0, 0, 0, 0, 0, 0, 0, 0]
The output I am getting:
[array([ 1, 12, 23, 34, 45, 56, 67, 78, 89, 100])
array([ 6, 17, 28, 39, 50, 61, 72, 83, 94])
array([11, 22, 33, 44, 55, 66, 77, 88, 99])
array([17, 28, 39, 50, 61, 72, 83, 94])
array([22, 33, 44, 55, 66, 77, 88, 99])
array([28, 39, 50, 61, 72, 83, 94]) array([33, 44, 55, 66, 77, 88, 99])
array([39, 50, 61, 72, 83, 94]) array([44, 55, 66, 77, 88, 99])
array([50, 61, 72, 83, 94])]
"""
A:
The main problem is that you're overwriting your pre-allocated array matrix_list with the result of the list comprehension, which is just a series of lists. Thus, you lose all of the structure that you defined to begin with. To make things simpler (since you also have an issue with making the numpy range up to the same amount each time, rather than decrementing sequentially like your desired output shows), see if you can get the zero-padding working on an individual array first, or even as part of a for loop.
If you want to create padded numpy arrays, you can use np.pad(X, pad_width=(before,after)), where the second argument allows you to specify how many padded values you will add before and after the array, X. The default behavior of the function is to add zeros wherever you want to pad, which is what you want.
As for getting everything to work in list comprehension, you can consider using enumerate(x) to help you figure out how many padding digits you'll need and where to stop your counting.
A:
The issue is that you create a numpy array and you immediately overwrite your variable with a list of list.
Anyway, you should handle this with numpy broadcasting and linspace, then mask the lower right triangle with boolean indexing:
matrix = (
np.linspace(1, 100, 10, dtype=int)
+np.linspace(0, 50-1, 10, dtype=int)[:,None]
)
n = np.arange(10)
matrix[(n >= (10-n)[:,None])] = 0
print(matrix)
Output:
[[ 1 12 23 34 45 56 67 78 89 100]
[ 6 17 28 39 50 61 72 83 94 0]
[ 11 22 33 44 55 66 77 88 0 0]
[ 17 28 39 50 61 72 83 0 0 0]
[ 22 33 44 55 66 77 0 0 0 0]
[ 28 39 50 61 72 0 0 0 0 0]
[ 33 44 55 66 0 0 0 0 0 0]
[ 39 50 61 0 0 0 0 0 0 0]
[ 44 55 0 0 0 0 0 0 0 0]
[ 50 0 0 0 0 0 0 0 0 0]]
|
Convert arrays inside a list into a single array and append zeros
|
The objective of this code snippet was to create a 2D array of shape (10,10) with
array[0,0]=1;
array[0,9]=100; and
array[9,0]=50.
Complications arose when the interval between these elements had to be equal as shown in the expected output. Rows had to increment with equal intervals up-to 100 and columns had to increment with equal intervals up-to 50.
I know that my code has a logical error in list-comprehension for "matrix_list". But I'm not sure what the error is.
The code I wrote:
`import numpy as np`
`matrix_list = np.zeros((10,10), dtype = int)`
`matrix_list =
[(np.arange(column, 101, (100-1)/9).astype(int)) for column in np.arange(1, 51, (50-1)/9).astype(int)]`
`print(np.array(matrix_list))`
Expected Output:
[ 1, 12, 23, 34, 45, 56, 67, 78, 89, 100]
[ 6, 17, 28, 39, 50, 61, 72, 83, 94, 0]
[11, 22, 33, 44, 55, 66, 77, 88, 0, 0]
[17, 28, 39, 50, 61, 72, 83, 0, 0, 0]
[22, 33, 44, 55, 66, 77, 0, 0, 0, 0]
[28, 39, 50, 61, 72, 0, 0, 0, 0, 0]
[33, 44, 55, 66, 0, 0, 0, 0, 0, 0]
[39, 50, 61, 0, 0, 0, 0, 0, 0, 0]
[44, 55, 0, 0, 0, 0, 0, 0, 0, 0]
[50, 0, 0, 0, 0, 0, 0, 0, 0, 0]
The output I am getting:
[array([ 1, 12, 23, 34, 45, 56, 67, 78, 89, 100])
array([ 6, 17, 28, 39, 50, 61, 72, 83, 94])
array([11, 22, 33, 44, 55, 66, 77, 88, 99])
array([17, 28, 39, 50, 61, 72, 83, 94])
array([22, 33, 44, 55, 66, 77, 88, 99])
array([28, 39, 50, 61, 72, 83, 94]) array([33, 44, 55, 66, 77, 88, 99])
array([39, 50, 61, 72, 83, 94]) array([44, 55, 66, 77, 88, 99])
array([50, 61, 72, 83, 94])]
"""
|
[
"The main problem is that you're overwriting your pre-allocated array matrix_list with the result of the list comprehension, which is just a series of lists. Thus, you lose all of the structure that you defined to begin with. To make things simpler (since you also have an issue with making the numpy range up to the same amount each time, rather than decrementing sequentially like your desired output shows), see if you can get the zero-padding working on an individual array first, or even as part of a for loop.\nIf you want to create padded numpy arrays, you can use np.pad(X, pad_width=(before,after)), where the second argument allows you to specify how many padded values you will add before and after the array, X. The default behavior of the function is to add zeros wherever you want to pad, which is what you want.\nAs for getting everything to work in list comprehension, you can consider using enumerate(x) to help you figure out how many padding digits you'll need and where to stop your counting.\n",
"The issue is that you create a numpy array and you immediately overwrite your variable with a list of list.\nAnyway, you should handle this with numpy broadcasting and linspace, then mask the lower right triangle with boolean indexing:\nmatrix = (\n np.linspace(1, 100, 10, dtype=int)\n +np.linspace(0, 50-1, 10, dtype=int)[:,None]\n)\n\nn = np.arange(10)\nmatrix[(n >= (10-n)[:,None])] = 0\n\nprint(matrix)\n\nOutput:\n[[ 1 12 23 34 45 56 67 78 89 100]\n [ 6 17 28 39 50 61 72 83 94 0]\n [ 11 22 33 44 55 66 77 88 0 0]\n [ 17 28 39 50 61 72 83 0 0 0]\n [ 22 33 44 55 66 77 0 0 0 0]\n [ 28 39 50 61 72 0 0 0 0 0]\n [ 33 44 55 66 0 0 0 0 0 0]\n [ 39 50 61 0 0 0 0 0 0 0]\n [ 44 55 0 0 0 0 0 0 0 0]\n [ 50 0 0 0 0 0 0 0 0 0]]\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"arrays",
"numpy",
"python",
"python_3.x"
] |
stackoverflow_0074527685_arrays_numpy_python_python_3.x.txt
|
Q:
selecting where in multiple columns on ANSI SQL (IMPALA SQL)
It worked normally in Oracle SQL, but it does not work in ANSI SQL.
SELECT whatever WHERE (col1,col2) IN ((val1, val2), (val1, val2), ...)
How do I write code in ANSI SQL (IMPALA SQL)?
I don't want the following code because there are many lists.
WHERE (col1 = val1a AND col2 = val2a)
OR (col1 = val1b AND col2 = val2b)
...
thank you!
(ex)
https://dba.stackexchange.com/questions/34266/selecting-where-two-columns-are-in-a-set
We can do smooth operation in ANSI sql.
A:
This isnt possible in hive or impala. Only 'other' workaround is concat().
You can use below sql-
...
where concat(col1,'~',col2) IN (concat(val1,'~',val2),concat(val3,'~',val4)...)
Pls note if col1/col2 is null, it wont be matched.
EDIT : this can have severe performance problem. So, you can store val1,val2 in a static/lookup table and then use it to join with main table like this -
select ...
from table1 t1
join table2 t2 on t1.col1=t2.val1 and t1.col2=t2.val2
You also have flexibility to change values as per future need and not change the sql.
|
selecting where in multiple columns on ANSI SQL (IMPALA SQL)
|
It worked normally in Oracle SQL, but it does not work in ANSI SQL.
SELECT whatever WHERE (col1,col2) IN ((val1, val2), (val1, val2), ...)
How do I write code in ANSI SQL (IMPALA SQL)?
I don't want the following code because there are many lists.
WHERE (col1 = val1a AND col2 = val2a)
OR (col1 = val1b AND col2 = val2b)
...
thank you!
(ex)
https://dba.stackexchange.com/questions/34266/selecting-where-two-columns-are-in-a-set
We can do smooth operation in ANSI sql.
|
[
"This isnt possible in hive or impala. Only 'other' workaround is concat().\nYou can use below sql-\n...\nwhere concat(col1,'~',col2) IN (concat(val1,'~',val2),concat(val3,'~',val4)...)\n\nPls note if col1/col2 is null, it wont be matched.\nEDIT : this can have severe performance problem. So, you can store val1,val2 in a static/lookup table and then use it to join with main table like this -\nselect ...\nfrom table1 t1\njoin table2 t2 on t1.col1=t2.val1 and t1.col2=t2.val2\n\nYou also have flexibility to change values as per future need and not change the sql.\n"
] |
[
0
] |
[] |
[] |
[
"ansi",
"impala",
"python",
"sql",
"where_clause"
] |
stackoverflow_0074527754_ansi_impala_python_sql_where_clause.txt
|
Q:
Running python in VS code such that I can test functions on the REPL
I am trying to run a Python file in VS code. I have a very simple function that takes in a number and returns the sum of its digits. However, when I actually run the Python file on VS Code, it does nothing and does not open a REPL so I can manually test the function on n.
For example, I tried python3 on the terminal, and it opened the REPL, but with none of the functions in the actual file I was working on. When I run it as usual, it just goes over the file and does nothing. Is there any way I can open a REPL with all the functions in my file available so that I will be able to test the function at different numbers while the repl is running? I know this may seem like a dumb question but it will be really useful to me.
A:
Right-click in the code editor window and select Run Current File in Interactive Window, or select Jupyter: Create Interactive Window in the command palette to open an interactive window.
There is another way you can open the REPL and select the entire content of the script and use the shortcut key Shift+Enter, or right-click to run the code in the REPL.
|
Running python in VS code such that I can test functions on the REPL
|
I am trying to run a Python file in VS code. I have a very simple function that takes in a number and returns the sum of its digits. However, when I actually run the Python file on VS Code, it does nothing and does not open a REPL so I can manually test the function on n.
For example, I tried python3 on the terminal, and it opened the REPL, but with none of the functions in the actual file I was working on. When I run it as usual, it just goes over the file and does nothing. Is there any way I can open a REPL with all the functions in my file available so that I will be able to test the function at different numbers while the repl is running? I know this may seem like a dumb question but it will be really useful to me.
|
[
"Right-click in the code editor window and select Run Current File in Interactive Window, or select Jupyter: Create Interactive Window in the command palette to open an interactive window.\n\n\nThere is another way you can open the REPL and select the entire content of the script and use the shortcut key Shift+Enter, or right-click to run the code in the REPL.\n\n\n"
] |
[
1
] |
[] |
[] |
[
"python",
"visual_studio_code"
] |
stackoverflow_0074515198_python_visual_studio_code.txt
|
Q:
How do I go skip an element in a list if all the keys in a dictionary which has a value of a set already has that element?
As the title suggests, if I had a dictionary with keys and values (in which these values are sets) where all of the key's values already have an element from a list, they move on to see if they could add the next element into the set.
For instance,
lst = ['a', 'b', 'v']
lst = ['a', 'b', 'v']
sample_dct = {'test': {'a'}, 'letter': {'a'}, 'other': {'a'}}
other_dct = {'test': {'a'}, 'letter': {'a'}, 'other': {'g'}}
test_dct = {'test': {'a', 'b'}, 'letter': {'a', 'b'}, 'other': {'a'}}
Which these dictionaries would become:
sample_dct = {'test': {'a', 'b'}, 'letter': {'a', 'b'}, 'other': {'a', 'b'}}
other_dct = {'test': {'a'}, 'letter': {'a'}, 'other': {'g', 'a'}}
test_dct = {'test': {'a', 'b'}, 'letter': {'a', 'b'}, 'other': {'a', 'b'}}
Here's what I tried:
lst = ['a', 'b', 'v']
other_dct = {'test': {'a'}, 'letter': {'a'}, 'other': {'g'}}
j = 0
for i in other_dct:
while not j == len(lst) - 1:
if not lst[j] in other_dct[i]:
x = other_dct[i]
x.add(lst[j])
other_dct[i] = x
break
else:
j += 1
j = 0
print(other_dct)
which prints {'test': {'b', 'a'}, 'letter': {'b', 'a'}, 'other': {'a', 'g'}}
I figured out how to only add an element once to the set but I'm still confused on how to only add 'b' if the third key already has 'a'
I'm considerting turning the list into a dictionary similar to the dictionaries it is being added to by turning the keys into values where they're added onto a set like this:
new_dct = {'a': {'test', 'letter', 'other}, 'b': : {'test', 'letter'}, 'v': set()}
but I'm not sure if that will only complicate matters.
A:
You can use python's all function to test that all values contain the list item. If they don't, then the item can be added to all values (as it's a set duplication doesn't really matter) and then return, otherwise move to the next letter in the list.
lst = ['a', 'b', 'v']
sample_dct = {'test': {'a'}, 'letter': {'a'}, 'other': {'a'}}
other_dct = {'test': {'a'}, 'letter': {'a'}, 'other': {'g'}}
test_dct = {'test': {'a', 'b'}, 'letter': {'a', 'b'}, 'other': {'a'}}
def add_items(items, dicts_set):
for item in items:
if not all((item in val for val in dicts_set.values())):
for k in dicts_set:
dicts_set[k].add(item)
return dicts_set
return dicts_set
print(add_items(lst, sample_dct))
print(add_items(lst, other_dct))
print(add_items(lst, test_dct))
# output:
#{'test': {'a', 'b'}, 'letter': {'a', 'b'}, 'other': {'a', 'b'}}
#{'test': {'a'}, 'letter': {'a'}, 'other': {'g', 'a'}}
#{'test': {'a', 'b'}, 'letter': {'a', 'b'}, 'other': {'a', 'b'}}
|
How do I go skip an element in a list if all the keys in a dictionary which has a value of a set already has that element?
|
As the title suggests, if I had a dictionary with keys and values (in which these values are sets) where all of the key's values already have an element from a list, they move on to see if they could add the next element into the set.
For instance,
lst = ['a', 'b', 'v']
lst = ['a', 'b', 'v']
sample_dct = {'test': {'a'}, 'letter': {'a'}, 'other': {'a'}}
other_dct = {'test': {'a'}, 'letter': {'a'}, 'other': {'g'}}
test_dct = {'test': {'a', 'b'}, 'letter': {'a', 'b'}, 'other': {'a'}}
Which these dictionaries would become:
sample_dct = {'test': {'a', 'b'}, 'letter': {'a', 'b'}, 'other': {'a', 'b'}}
other_dct = {'test': {'a'}, 'letter': {'a'}, 'other': {'g', 'a'}}
test_dct = {'test': {'a', 'b'}, 'letter': {'a', 'b'}, 'other': {'a', 'b'}}
Here's what I tried:
lst = ['a', 'b', 'v']
other_dct = {'test': {'a'}, 'letter': {'a'}, 'other': {'g'}}
j = 0
for i in other_dct:
while not j == len(lst) - 1:
if not lst[j] in other_dct[i]:
x = other_dct[i]
x.add(lst[j])
other_dct[i] = x
break
else:
j += 1
j = 0
print(other_dct)
which prints {'test': {'b', 'a'}, 'letter': {'b', 'a'}, 'other': {'a', 'g'}}
I figured out how to only add an element once to the set but I'm still confused on how to only add 'b' if the third key already has 'a'
I'm considerting turning the list into a dictionary similar to the dictionaries it is being added to by turning the keys into values where they're added onto a set like this:
new_dct = {'a': {'test', 'letter', 'other}, 'b': : {'test', 'letter'}, 'v': set()}
but I'm not sure if that will only complicate matters.
|
[
"You can use python's all function to test that all values contain the list item. If they don't, then the item can be added to all values (as it's a set duplication doesn't really matter) and then return, otherwise move to the next letter in the list.\nlst = ['a', 'b', 'v']\nsample_dct = {'test': {'a'}, 'letter': {'a'}, 'other': {'a'}}\nother_dct = {'test': {'a'}, 'letter': {'a'}, 'other': {'g'}}\ntest_dct = {'test': {'a', 'b'}, 'letter': {'a', 'b'}, 'other': {'a'}}\n\ndef add_items(items, dicts_set):\n for item in items:\n if not all((item in val for val in dicts_set.values())):\n for k in dicts_set:\n dicts_set[k].add(item)\n return dicts_set\n return dicts_set\n \nprint(add_items(lst, sample_dct))\nprint(add_items(lst, other_dct))\nprint(add_items(lst, test_dct))\n# output:\n#{'test': {'a', 'b'}, 'letter': {'a', 'b'}, 'other': {'a', 'b'}}\n#{'test': {'a'}, 'letter': {'a'}, 'other': {'g', 'a'}}\n#{'test': {'a', 'b'}, 'letter': {'a', 'b'}, 'other': {'a', 'b'}}\n\n"
] |
[
0
] |
[] |
[] |
[
"list",
"python",
"python_3.x",
"set"
] |
stackoverflow_0074527396_list_python_python_3.x_set.txt
|
Q:
Python jupyter: can't send request to website
I'm learning python and trying the below code on Jupyter, but is shown error.
import requests
response = requests.get("https://en.wikipedia.org/wiki/main_page")
ConnectionError: HTTPSConnectionPool(host='en.wikipedia.org', port=443): Max
retries exceeded with url: /wiki/main_page (Caused by
NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at
0x7f0237dc1e80>: Failed to establish a new connection: [Errno -3] Temporary
failure in name resolution',))`
I tried to find answer, but is not sure. Is it because I need to handle the proxy or there is something wrong with my computer operating system? Please help.
A:
I got problem sovlved with using parameter verify=False
https://www.w3schools.com/python/ref_requests_get.asp
For reference,
I found the answer at here:
https://community.nexthink.com/s/question/0D52p0000ARmsbgCQB/below-code-in-python-tried-on-jupyter-nb-then-it-throws-following-error-sslerror-httpsconnectionpoolhostukfil0083vaukfidintlcom-port1671-max-retries-exceeded-with-url-2queryplatformwindowsplatformmacosqueryselect20i
I'm not sure this is the right solution for your issue. But it worked for me.
|
Python jupyter: can't send request to website
|
I'm learning python and trying the below code on Jupyter, but is shown error.
import requests
response = requests.get("https://en.wikipedia.org/wiki/main_page")
ConnectionError: HTTPSConnectionPool(host='en.wikipedia.org', port=443): Max
retries exceeded with url: /wiki/main_page (Caused by
NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at
0x7f0237dc1e80>: Failed to establish a new connection: [Errno -3] Temporary
failure in name resolution',))`
I tried to find answer, but is not sure. Is it because I need to handle the proxy or there is something wrong with my computer operating system? Please help.
|
[
"I got problem sovlved with using parameter verify=False\nhttps://www.w3schools.com/python/ref_requests_get.asp\nFor reference,\nI found the answer at here:\nhttps://community.nexthink.com/s/question/0D52p0000ARmsbgCQB/below-code-in-python-tried-on-jupyter-nb-then-it-throws-following-error-sslerror-httpsconnectionpoolhostukfil0083vaukfidintlcom-port1671-max-retries-exceeded-with-url-2queryplatformwindowsplatformmacosqueryselect20i\nI'm not sure this is the right solution for your issue. But it worked for me.\n"
] |
[
0
] |
[] |
[] |
[
"jupyter_notebook",
"python",
"python_requests",
"web_scraping"
] |
stackoverflow_0046036784_jupyter_notebook_python_python_requests_web_scraping.txt
|
Q:
How to create a fixture for test functions
I am trying to create a fixture for those functions but I keep getting no tests were found an empty suite.
Maybe I'm doing something wrong but see the code below and what I have tried.
import pytest
import time
from selenium import webdriver
from selenium.common import NoSuchElementException
from selenium.webdriver.common.by import By
class TestExample:
def test_open_browser(self):
driver = webdriver.Chrome()
driver.maximize_window()
driver.get("https://www.amazon.com/")
driver.implicitly_wait(10)
driver.find_element(By.ID, "nav-hamburger-menu").click()
driver.implicitly_wait(10)
driver.find_element(By.XPATH, "//div[@id='hmenu-content']/ul/li[10]/a/div").click()
driver.implicitly_wait(10)
driver.find_element(By.LINK_TEXT, "Beading & Jewelry Making").click()
driver.find_element(By.XPATH, "//li[@id='n/12896151']/span/a/span").click()
driver.implicitly_wait(10)
driver.find_element(By.ID, "a-autoid-0-announce").click()
driver.implicitly_wait(10)
driver.find_element(By.ID, "s-result-sort-select_2").click()
driver.implicitly_wait(10)
driver.find_element(By.XPATH,
"//div[@id='search']/div/div/div/span/div/div[4]/div/div/div/div/div[2]/div/h2/a/span").click()
def test_simple_customer_review(driver, expected_min_score=4):
try:
review_score = driver.find_element(By.ID, "acrCustomerReviewText")
assert review_score >= expected_min_score
except NoSuchElementException:
assert False
except ValueError:
assert False
def test_price(driver, expected_price_limit=3500):
try:
price = driver.find_element(By.ID, "corePriceDisplay_desktop_feature_div")
assert price <= expected_price_limit
except NoSuchElementException:
assert False
except ValueError:
assert False
# driver.close()
# if review_score >= "4"
# assert True
# if price <= "4000"
# assert True
I know to access the fixture function the test has to mention the fixture name as input parameters.
Maybe I need more explanation on how to do that the code is above.
Please don't be offended guys I am just in a weird and lost situation.
@pytest.fixture()
def test_open_browser(self):
return
@pytest.fixture()
def expected_min_score=4()
return
@pytest.fixture()
def expected_price_limit=3500
return
A:
A fixture is just a regular python function, a basic one would have no parameters and return an object or data that you want to use in your test.
for example if you wanted to test your selenium driver...
import pytest
from selenium import webdriver
@pytest.fixture
def driver():
wd = webdriver.Chrome()
return wd
def test_google_com(driver):
driver.get('https://www.google.com/')
assert driver.current_url == 'https://www.google.com/'
an even simpler example would be
import pytest
@pytest.fixture
def hello_world_string():
return 'Hello World!'
def test_hello_world_string(hello_world_string):
assert 'Hello World!' == hello_world_string
assert isinstance(hello_world_string, str)
|
How to create a fixture for test functions
|
I am trying to create a fixture for those functions but I keep getting no tests were found an empty suite.
Maybe I'm doing something wrong but see the code below and what I have tried.
import pytest
import time
from selenium import webdriver
from selenium.common import NoSuchElementException
from selenium.webdriver.common.by import By
class TestExample:
def test_open_browser(self):
driver = webdriver.Chrome()
driver.maximize_window()
driver.get("https://www.amazon.com/")
driver.implicitly_wait(10)
driver.find_element(By.ID, "nav-hamburger-menu").click()
driver.implicitly_wait(10)
driver.find_element(By.XPATH, "//div[@id='hmenu-content']/ul/li[10]/a/div").click()
driver.implicitly_wait(10)
driver.find_element(By.LINK_TEXT, "Beading & Jewelry Making").click()
driver.find_element(By.XPATH, "//li[@id='n/12896151']/span/a/span").click()
driver.implicitly_wait(10)
driver.find_element(By.ID, "a-autoid-0-announce").click()
driver.implicitly_wait(10)
driver.find_element(By.ID, "s-result-sort-select_2").click()
driver.implicitly_wait(10)
driver.find_element(By.XPATH,
"//div[@id='search']/div/div/div/span/div/div[4]/div/div/div/div/div[2]/div/h2/a/span").click()
def test_simple_customer_review(driver, expected_min_score=4):
try:
review_score = driver.find_element(By.ID, "acrCustomerReviewText")
assert review_score >= expected_min_score
except NoSuchElementException:
assert False
except ValueError:
assert False
def test_price(driver, expected_price_limit=3500):
try:
price = driver.find_element(By.ID, "corePriceDisplay_desktop_feature_div")
assert price <= expected_price_limit
except NoSuchElementException:
assert False
except ValueError:
assert False
# driver.close()
# if review_score >= "4"
# assert True
# if price <= "4000"
# assert True
I know to access the fixture function the test has to mention the fixture name as input parameters.
Maybe I need more explanation on how to do that the code is above.
Please don't be offended guys I am just in a weird and lost situation.
@pytest.fixture()
def test_open_browser(self):
return
@pytest.fixture()
def expected_min_score=4()
return
@pytest.fixture()
def expected_price_limit=3500
return
|
[
"A fixture is just a regular python function, a basic one would have no parameters and return an object or data that you want to use in your test.\nfor example if you wanted to test your selenium driver...\nimport pytest\nfrom selenium import webdriver\n\n@pytest.fixture\ndef driver():\n wd = webdriver.Chrome()\n return wd\n\ndef test_google_com(driver):\n driver.get('https://www.google.com/')\n assert driver.current_url == 'https://www.google.com/'\n\nan even simpler example would be\nimport pytest\n\n@pytest.fixture\ndef hello_world_string():\n return 'Hello World!'\n\ndef test_hello_world_string(hello_world_string):\n assert 'Hello World!' == hello_world_string\n assert isinstance(hello_world_string, str)\n\n"
] |
[
0
] |
[] |
[] |
[
"automated_tests",
"pytest",
"python",
"python_3.x"
] |
stackoverflow_0074527840_automated_tests_pytest_python_python_3.x.txt
|
Q:
Global variable in python with image processing
how can i make vehicle_count as a global variable so i can call it on the file class it has a use of car counting with opencv
class Vehicle_Counting:
def __init__(self, window):
self.window = window
self.window.geometry('1366x768')
self.window.resizable(0, 0)
self.window.state('zoomed')
self.window.title('Page2')
self.window.config(background='yellow')
B1 = Button(self.window, text="Count first lane", bg="dark orange", font=("Arial", 15), command=self.Counter)
B1.place(x=450, y=20)
B2 = Button(self.window, text="Count second lane", bg="dark orange", font=("Arial", 15), command=self.Counter2)
B2.place(x=650, y=20)
B2 = Button(self.window, text="Proceed to Stop Light Timer", bg="dark orange", font=("Arial", 15),
command=self.Countdown_Timer)
B2.place(x=850, y=20)
def Counter(self):
vd = VehicleDetector()
img = cv2.imread("images/car-6810885__340.jpg")
vehicle_boxes = vd.detect_vehicles(img)
vehicle_count = len(vehicle_boxes)
for box in vehicle_boxes:
x, y, w, h = box
cv2.rectangle(img, (x, y), (x + w, y + h), (25, 0, 180), 3)
cv2.putText(img, "Vehicles:" + str(vehicle_count), (20, 50), 0, 2, (100, 200, 0), 3)
cv2.imshow("Cars", img)
cv2.waitKey(0)
i need to call the vehicle_count in this class in order to make a decision
class Countdown_Timer(Vehicle_Counting):
def __init__(self, window):
self.window = window
self.window.geometry('1366x768')
self.window.resizable(0, 0)
self.window.state('zoomed')
self.window.title('Page2')
B1 = Button(self.window, text="Computer for the Timer", bg="dark orange", font=("Arial", 15), command=self.RG_timer)
B1.place(x=450, y=20)
def RG_timer(self):
if Vehicle_Counting.vehicle_count == 0:
messagebox.showinfo("")
im expecting to call it in a class on other file so i can create a if else statement.
A:
You don't need to use global variable, use instance variable of Vehicle_Counting and pass it to instance of Countdown_Timer.
Below is the modified code:
from tkinter import *
from tkinter import messagebox
class Vehicle_Counting:
def __init__(self, window):
self.window = window
self.window.geometry('1366x768')
self.window.resizable(0, 0)
#self.window.state('zoomed')
self.window.title('Page2')
self.window.config(background='yellow')
B1 = Button(self.window, text="Count first lane", bg="dark orange", font=("Arial", 15), command=self.Counter)
B1.place(x=450, y=20)
B2 = Button(self.window, text="Count second lane", bg="dark orange", font=("Arial", 15), command=self.Counter2)
B2.place(x=650, y=20)
B2 = Button(self.window, text="Proceed to Stop Light Timer", bg="dark orange", font=("Arial", 15),
command=self.open_countdown_timer)
B2.place(x=850, y=20)
def Counter(self):
'''
vd = VehicleDetector()
img = cv2.imread("images/car-6810885__340.jpg")
vehicle_boxes = vd.detect_vehicles(img)
self.vehicle_count = len(vehicle_boxes) # use instance variable instead of local variable
for box in vehicle_boxes:
x, y, w, h = box
cv2.rectangle(img, (x, y), (x + w, y + h), (25, 0, 180), 3)
cv2.putText(img, "Vehicles:" + str(self.vehicle_count), (20, 50), 0, 2, (100, 200, 0), 3)
cv2.imshow("Cars", img)
cv2.waitKey(0)
'''
self.vehicle_count = 0 # just simulate result of OpenCV detection
def Counter2(self):
self.vehicle_count = 10 # just simulate result of OpenCV detection
def open_countdown_timer(self):
win = Toplevel(self.window)
win.transient(self.window)
Countdown_Timer(win, self.vehicle_count) # pass to Countdown_Timer
class Countdown_Timer:
def __init__(self, window, vehicle_count):
self.window = window
self.window.geometry('1366x768')
self.window.resizable(0, 0)
#self.window.state('zoomed')
self.window.title('Page2')
self.vehicle_count = vehicle_count # save to an instance variable
B1 = Button(self.window, text="Computer for the Timer", bg="dark orange", font=("Arial", 15), command=self.RG_timer)
B1.place(x=450, y=20)
def RG_timer(self):
if self.vehicle_count == 0:
messagebox.showinfo("Error", "No vehicle found")
else:
messagebox.showinfo("Info", f"Total {self.vehicle_count} vehicles found")
root = Tk()
Vehicle_Counting(root)
root.mainloop()
Note that I have comment out the OpenCV stuff to make the code runs without OpenCV.
|
Global variable in python with image processing
|
how can i make vehicle_count as a global variable so i can call it on the file class it has a use of car counting with opencv
class Vehicle_Counting:
def __init__(self, window):
self.window = window
self.window.geometry('1366x768')
self.window.resizable(0, 0)
self.window.state('zoomed')
self.window.title('Page2')
self.window.config(background='yellow')
B1 = Button(self.window, text="Count first lane", bg="dark orange", font=("Arial", 15), command=self.Counter)
B1.place(x=450, y=20)
B2 = Button(self.window, text="Count second lane", bg="dark orange", font=("Arial", 15), command=self.Counter2)
B2.place(x=650, y=20)
B2 = Button(self.window, text="Proceed to Stop Light Timer", bg="dark orange", font=("Arial", 15),
command=self.Countdown_Timer)
B2.place(x=850, y=20)
def Counter(self):
vd = VehicleDetector()
img = cv2.imread("images/car-6810885__340.jpg")
vehicle_boxes = vd.detect_vehicles(img)
vehicle_count = len(vehicle_boxes)
for box in vehicle_boxes:
x, y, w, h = box
cv2.rectangle(img, (x, y), (x + w, y + h), (25, 0, 180), 3)
cv2.putText(img, "Vehicles:" + str(vehicle_count), (20, 50), 0, 2, (100, 200, 0), 3)
cv2.imshow("Cars", img)
cv2.waitKey(0)
i need to call the vehicle_count in this class in order to make a decision
class Countdown_Timer(Vehicle_Counting):
def __init__(self, window):
self.window = window
self.window.geometry('1366x768')
self.window.resizable(0, 0)
self.window.state('zoomed')
self.window.title('Page2')
B1 = Button(self.window, text="Computer for the Timer", bg="dark orange", font=("Arial", 15), command=self.RG_timer)
B1.place(x=450, y=20)
def RG_timer(self):
if Vehicle_Counting.vehicle_count == 0:
messagebox.showinfo("")
im expecting to call it in a class on other file so i can create a if else statement.
|
[
"You don't need to use global variable, use instance variable of Vehicle_Counting and pass it to instance of Countdown_Timer.\nBelow is the modified code:\nfrom tkinter import *\nfrom tkinter import messagebox\n\nclass Vehicle_Counting:\n\n def __init__(self, window):\n self.window = window\n self.window.geometry('1366x768')\n self.window.resizable(0, 0)\n #self.window.state('zoomed')\n self.window.title('Page2')\n\n self.window.config(background='yellow')\n\n B1 = Button(self.window, text=\"Count first lane\", bg=\"dark orange\", font=(\"Arial\", 15), command=self.Counter)\n B1.place(x=450, y=20)\n\n B2 = Button(self.window, text=\"Count second lane\", bg=\"dark orange\", font=(\"Arial\", 15), command=self.Counter2)\n B2.place(x=650, y=20)\n\n B2 = Button(self.window, text=\"Proceed to Stop Light Timer\", bg=\"dark orange\", font=(\"Arial\", 15),\n command=self.open_countdown_timer)\n B2.place(x=850, y=20)\n\n def Counter(self):\n '''\n vd = VehicleDetector()\n img = cv2.imread(\"images/car-6810885__340.jpg\")\n vehicle_boxes = vd.detect_vehicles(img)\n self.vehicle_count = len(vehicle_boxes) # use instance variable instead of local variable\n for box in vehicle_boxes:\n x, y, w, h = box\n cv2.rectangle(img, (x, y), (x + w, y + h), (25, 0, 180), 3)\n cv2.putText(img, \"Vehicles:\" + str(self.vehicle_count), (20, 50), 0, 2, (100, 200, 0), 3)\n\n cv2.imshow(\"Cars\", img)\n cv2.waitKey(0)\n '''\n self.vehicle_count = 0 # just simulate result of OpenCV detection\n\n def Counter2(self):\n self.vehicle_count = 10 # just simulate result of OpenCV detection\n\n def open_countdown_timer(self):\n win = Toplevel(self.window)\n win.transient(self.window)\n Countdown_Timer(win, self.vehicle_count) # pass to Countdown_Timer\n\nclass Countdown_Timer:\n def __init__(self, window, vehicle_count):\n self.window = window\n self.window.geometry('1366x768')\n self.window.resizable(0, 0)\n #self.window.state('zoomed')\n self.window.title('Page2')\n\n self.vehicle_count = vehicle_count # save to an instance variable\n\n B1 = Button(self.window, text=\"Computer for the Timer\", bg=\"dark orange\", font=(\"Arial\", 15), command=self.RG_timer)\n B1.place(x=450, y=20)\n\n def RG_timer(self):\n if self.vehicle_count == 0:\n messagebox.showinfo(\"Error\", \"No vehicle found\")\n else:\n messagebox.showinfo(\"Info\", f\"Total {self.vehicle_count} vehicles found\")\n\nroot = Tk()\nVehicle_Counting(root)\nroot.mainloop()\n\nNote that I have comment out the OpenCV stuff to make the code runs without OpenCV.\n"
] |
[
0
] |
[] |
[] |
[
"class",
"global",
"python",
"tkinter"
] |
stackoverflow_0074527974_class_global_python_tkinter.txt
|
Q:
Scraped Python results have changed from numbers to NaN
the last time I ran this code in February, it gave me proper results like this.
Sales Income
AAPL 365.82B 94.68B
MSFT 184.90B 71.19B
TSLA 53.82B 5.52B
FB 112.33B 40.30B
Now I get this with NaN instead of the numbers. The Finviz website looks to be using the exact same table as back in February. Can anyone figure out what has changed? Thanks.
Sales Income
AAPL 365.82B 94.68B
MSFT NaN NaN
TSLA NaN NaN
FB NaN NaN
import pandas as pd
from bs4 import BeautifulSoup as bs
import requests
import numpy as np
# For custom list of stocks, edit this list below, otherwise leave commented out
v1 = ['AAPL','MSFT','TSLA','FB','BRK-B','TSM','NVDA','V','JNJ','JPM','WMT','PG','BAC','HD','BABA','TM','XOM','PFE','DIS','KO']
# Header required to scrape from Finviz
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36',
'Upgrade-Insecure-Requests': '1', 'Cookie': 'v2=1495343816.182.19.234.142', 'Accept-Encoding': 'gzip, deflate, sdch',
'Referer': "http://finviz.com/quote.ashx?t="}
# This function is what is used to find the metric of interest and return it
def fundamental_metric(soup, metric):
return soup.find(text=metric).find_next(class_='snapshot-td2').text
# This function iterates through the index of the data frame (stock_list) and uses the fundemental_metric functinon to find the metric on Finviz for that stock
# Any stock in the list that cannot be scraped will return an error before moving on to the next stock
def get_fundamental_data(df):
for symbol in df.index:
try:
#url = ("http://finviz.com/quote.ashx?t=" + symbol.lower())
r = requests.get("http://finviz.com/quote.ashx?t="+ symbol.lower(),headers=headers)
soup = bs(r.content,'html.parser')
for m in df.columns:
output = fundamental_metric(soup,m)
df.loc[symbol,m] = output
df.replace(['-'], np.NaN)
except Exception as e:
print (symbol, 'Not Found')
print(e)
return df
# List of metrics to scrape
# Before adding any metrics, ensure the metric being added is available on Finviz and the name is matched identically
metric = ['Sales','Income']
df = pd.DataFrame(index = v1, columns = metric)
df = get_fundamental_data(df)
print(df)
A:
Your code was running for the first symbol only
def get_fundamental_data(df):
for symbol in df.index:
try:
# url = ("http://finviz.com/quote.ashx?t=" + symbol.lower())
r = requests.get("http://finviz.com/quote.ashx?t=" + symbol.lower(), headers=headers)
soup = bs(r.content, 'html.parser')
for m in df.columns:
output = fundamental_metric(soup, m)
df.loc[symbol, m] = output
df.replace(['-'], np.NaN)
except Exception as e:
print(symbol, 'Not Found')
print(e)
return df #removed One tab space
|
Scraped Python results have changed from numbers to NaN
|
the last time I ran this code in February, it gave me proper results like this.
Sales Income
AAPL 365.82B 94.68B
MSFT 184.90B 71.19B
TSLA 53.82B 5.52B
FB 112.33B 40.30B
Now I get this with NaN instead of the numbers. The Finviz website looks to be using the exact same table as back in February. Can anyone figure out what has changed? Thanks.
Sales Income
AAPL 365.82B 94.68B
MSFT NaN NaN
TSLA NaN NaN
FB NaN NaN
import pandas as pd
from bs4 import BeautifulSoup as bs
import requests
import numpy as np
# For custom list of stocks, edit this list below, otherwise leave commented out
v1 = ['AAPL','MSFT','TSLA','FB','BRK-B','TSM','NVDA','V','JNJ','JPM','WMT','PG','BAC','HD','BABA','TM','XOM','PFE','DIS','KO']
# Header required to scrape from Finviz
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36',
'Upgrade-Insecure-Requests': '1', 'Cookie': 'v2=1495343816.182.19.234.142', 'Accept-Encoding': 'gzip, deflate, sdch',
'Referer': "http://finviz.com/quote.ashx?t="}
# This function is what is used to find the metric of interest and return it
def fundamental_metric(soup, metric):
return soup.find(text=metric).find_next(class_='snapshot-td2').text
# This function iterates through the index of the data frame (stock_list) and uses the fundemental_metric functinon to find the metric on Finviz for that stock
# Any stock in the list that cannot be scraped will return an error before moving on to the next stock
def get_fundamental_data(df):
for symbol in df.index:
try:
#url = ("http://finviz.com/quote.ashx?t=" + symbol.lower())
r = requests.get("http://finviz.com/quote.ashx?t="+ symbol.lower(),headers=headers)
soup = bs(r.content,'html.parser')
for m in df.columns:
output = fundamental_metric(soup,m)
df.loc[symbol,m] = output
df.replace(['-'], np.NaN)
except Exception as e:
print (symbol, 'Not Found')
print(e)
return df
# List of metrics to scrape
# Before adding any metrics, ensure the metric being added is available on Finviz and the name is matched identically
metric = ['Sales','Income']
df = pd.DataFrame(index = v1, columns = metric)
df = get_fundamental_data(df)
print(df)
|
[
"Your code was running for the first symbol only\ndef get_fundamental_data(df):\n for symbol in df.index:\n try:\n # url = (\"http://finviz.com/quote.ashx?t=\" + symbol.lower())\n r = requests.get(\"http://finviz.com/quote.ashx?t=\" + symbol.lower(), headers=headers)\n soup = bs(r.content, 'html.parser')\n for m in df.columns:\n output = fundamental_metric(soup, m)\n df.loc[symbol, m] = output\n df.replace(['-'], np.NaN)\n except Exception as e:\n print(symbol, 'Not Found')\n print(e)\n return df #removed One tab space\n\n"
] |
[
0
] |
[] |
[] |
[
"python",
"web_scraping"
] |
stackoverflow_0074526586_python_web_scraping.txt
|
Q:
ValueError: invalid literal for int() with base 16: 'Interstitial'
I want to convert the below string into categorical form or one hot encoded.
string1 = "Interstitial markings are diffusely prominent throughout both lungs. Heart size is normal. Pulmonary XXXX normal."
st1 = string1.split()
I am using below code but it generates error.
from numpy import array
from numpy import argmax
from keras.utils import to_categorical
# define example
data = array(st1)
print(data)
encoded = to_categorical(data)
print(encoded)
# invert encoding
inverted = argmax(encoded[0])
print(inverted)
error
['Interstitial' 'markings' 'are' 'diffusely' 'prominent' 'throughout' 'both' 'lungs.' 'Heart' 'size' 'is' 'normal.' 'Pulmonary' 'XXXX''normal.']
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-15-b034d9393342> in <module>
5 data = array(st1)
6 print(data)
----> 7 encoded = to_categorical(data)
8 print(encoded)
9 # invert encoding
/usr/local/lib/python3.7/dist-packages/keras/utils/np_utils.py in to_categorical(y, num_classes, dtype)
60 [0. 0. 0. 0.]
61 """
---> 62 y = np.array(y, dtype='int')
63 input_shape = y.shape
64 if input_shape and input_shape[-1] == 1 and len(input_shape) > 1:
ValueError: invalid literal for int() with base 10: 'Interstitial'
A:
Tensorflow has clearly mentioned it here that the tf.keras.utils.to_categorical is for converting a class vector (integers) to binary class matrix.
Your data variable contains string type elements, which is not same as integer, hence the error.
A:
Logically error wise says you typecasting str to int.
Like int('20') = 20 - Correct
Like
int('Interstitial') - ValueError: invalid literal for int() with base 16: 'Interstitial'
This is because
keras only supports one-hot-encoding for data that has already been
integer-encoded.
In such cases you can do so use LabelEncoder as follows.
string1 = "Interstitial markings are diffusely prominent throughout both lungs. Heart size is normal. Pulmonary XXXX normal."
st1 = string1.split()
from sklearn.preprocessing import LabelEncoder
import numpy as np
data = np.array(st1)
label_encoder = LabelEncoder()
data = label_encoder.fit_transform(data)
print(data)
##
##
##From here encode according next part of your code using to_categorical(data)
Gives #
array([ 1, 9, 4, 6, 11, 13, 5, 8, 0, 12, 7, 10, 2, 3, 10],
dtype=int64)
|
ValueError: invalid literal for int() with base 16: 'Interstitial'
|
I want to convert the below string into categorical form or one hot encoded.
string1 = "Interstitial markings are diffusely prominent throughout both lungs. Heart size is normal. Pulmonary XXXX normal."
st1 = string1.split()
I am using below code but it generates error.
from numpy import array
from numpy import argmax
from keras.utils import to_categorical
# define example
data = array(st1)
print(data)
encoded = to_categorical(data)
print(encoded)
# invert encoding
inverted = argmax(encoded[0])
print(inverted)
error
['Interstitial' 'markings' 'are' 'diffusely' 'prominent' 'throughout' 'both' 'lungs.' 'Heart' 'size' 'is' 'normal.' 'Pulmonary' 'XXXX''normal.']
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-15-b034d9393342> in <module>
5 data = array(st1)
6 print(data)
----> 7 encoded = to_categorical(data)
8 print(encoded)
9 # invert encoding
/usr/local/lib/python3.7/dist-packages/keras/utils/np_utils.py in to_categorical(y, num_classes, dtype)
60 [0. 0. 0. 0.]
61 """
---> 62 y = np.array(y, dtype='int')
63 input_shape = y.shape
64 if input_shape and input_shape[-1] == 1 and len(input_shape) > 1:
ValueError: invalid literal for int() with base 10: 'Interstitial'
|
[
"Tensorflow has clearly mentioned it here that the tf.keras.utils.to_categorical is for converting a class vector (integers) to binary class matrix.\nYour data variable contains string type elements, which is not same as integer, hence the error.\n",
"Logically error wise says you typecasting str to int.\nLike int('20') = 20 - Correct\n\nLike\nint('Interstitial') - ValueError: invalid literal for int() with base 16: 'Interstitial'\n\nThis is because\n\nkeras only supports one-hot-encoding for data that has already been\ninteger-encoded.\n\nIn such cases you can do so use LabelEncoder as follows.\nstring1 = \"Interstitial markings are diffusely prominent throughout both lungs. Heart size is normal. Pulmonary XXXX normal.\"\nst1 = string1.split()\nfrom sklearn.preprocessing import LabelEncoder\nimport numpy as np\n\ndata = np.array(st1)\n\nlabel_encoder = LabelEncoder()\ndata = label_encoder.fit_transform(data)\nprint(data)\n##\n##\n##From here encode according next part of your code using to_categorical(data)\n\nGives #\narray([ 1, 9, 4, 6, 11, 13, 5, 8, 0, 12, 7, 10, 2, 3, 10],\n dtype=int64)\n\n"
] |
[
2,
2
] |
[] |
[] |
[
"keras",
"python",
"tensorflow"
] |
stackoverflow_0074528000_keras_python_tensorflow.txt
|
Q:
Can't install scrapy with Python 3?
I am using Python 3.6.3 and Pip 9.0.1 but still can't install scrapy? I am doing this on windows. When executing the following command
pip3 install scrapy
I am greeted with this error first..
----------------------------------------
Failed building wheel for Twisted
Running setup.py clean for Twisted
Failed to build Twisted
Installing collected packages: Twisted, scrapy
Running setup.py install for Twisted ... error
Then it continues, the second error stops it completly and seems a lot more fatal...
Command "c:\users\admin\appdata\local\programs\python\python36-32\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\admin\\AppData\\Local\\Temp\\pip-build-zxkenzjd\\Twisted\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\admin\AppData\Local\Temp\pip-tr72roue-record\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\admin\AppData\Local\Temp\pip-build-zxkenzjd\Twisted\
I have tried executing the following commands as suggested on this answer:
pip install -U setuptools
pip install -U wheel
A:
I had the same problem too but I solved it as follow:
Open the Anaconda Prompt as administrator (For Windows10: open cortana/search Anaconda Prompt/choose Run as Administrator)
You should go to the path of Anaconda, for me was like:
C:\WINDOWS\system32>cd ..
C:\WINDOWS>cd..
C:\>cd ProgramData
C:\ProgramData>cd Anaconda3
C:\ProgramData>Anaconda3>
Then you should run the following command
C:\ProgramData>Anaconda3>conda install -c anaconda twisted
At some point it asks
Proceed ([y]/n)?
type y. Now twisted is installed.
To install scrapy, you either install it in Anaconda Prompt (as administrator) by running the following command:
C:\ProgramData>Anaconda3>conda install -c conda-forge scrapy
(again y for Proceed ([y]/n)?)
or on jupyter notebook and run the command
!pip install scrapy
A:
for my env: Win11 x64 + Python 3.11 x64
Solution:
downloaded related whl
https://www.lfd.uci.edu/~gohlke/pythonlibs/#twisted
Click: twisted_iocpsupport‑1.0.2‑cp311‑cp311‑win_amd64.whl
note
cp311 = CPython 3.11
amd64 = x64
download: https://download.lfd.uci.edu/pythonlibs/archived/twisted_iocpsupport-1.0.2-cp311-cp311-win_amd64.whl
install whl
pip install twisted_iocpsupport-1.0.2-cp311-cp311-win_amd64.whl
|
Can't install scrapy with Python 3?
|
I am using Python 3.6.3 and Pip 9.0.1 but still can't install scrapy? I am doing this on windows. When executing the following command
pip3 install scrapy
I am greeted with this error first..
----------------------------------------
Failed building wheel for Twisted
Running setup.py clean for Twisted
Failed to build Twisted
Installing collected packages: Twisted, scrapy
Running setup.py install for Twisted ... error
Then it continues, the second error stops it completly and seems a lot more fatal...
Command "c:\users\admin\appdata\local\programs\python\python36-32\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\admin\\AppData\\Local\\Temp\\pip-build-zxkenzjd\\Twisted\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\admin\AppData\Local\Temp\pip-tr72roue-record\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\admin\AppData\Local\Temp\pip-build-zxkenzjd\Twisted\
I have tried executing the following commands as suggested on this answer:
pip install -U setuptools
pip install -U wheel
|
[
"I had the same problem too but I solved it as follow:\nOpen the Anaconda Prompt as administrator (For Windows10: open cortana/search Anaconda Prompt/choose Run as Administrator)\nYou should go to the path of Anaconda, for me was like:\nC:\\WINDOWS\\system32>cd ..\nC:\\WINDOWS>cd..\nC:\\>cd ProgramData\nC:\\ProgramData>cd Anaconda3\nC:\\ProgramData>Anaconda3>\n\nThen you should run the following command\nC:\\ProgramData>Anaconda3>conda install -c anaconda twisted\n\nAt some point it asks\nProceed ([y]/n)?\n\ntype y. Now twisted is installed. \nTo install scrapy, you either install it in Anaconda Prompt (as administrator) by running the following command:\nC:\\ProgramData>Anaconda3>conda install -c conda-forge scrapy\n\n(again y for Proceed ([y]/n)?)\nor on jupyter notebook and run the command\n!pip install scrapy\n\n",
"for my env: Win11 x64 + Python 3.11 x64\nSolution:\n\ndownloaded related whl\n\nhttps://www.lfd.uci.edu/~gohlke/pythonlibs/#twisted\n\nClick: twisted_iocpsupport‑1.0.2‑cp311‑cp311‑win_amd64.whl\n\nnote\n\ncp311 = CPython 3.11\namd64 = x64\n\n\ndownload: https://download.lfd.uci.edu/pythonlibs/archived/twisted_iocpsupport-1.0.2-cp311-cp311-win_amd64.whl\n\n\n\n\n\n\ninstall whl\n\npip install twisted_iocpsupport-1.0.2-cp311-cp311-win_amd64.whl\n\n\n\n"
] |
[
6,
0
] |
[] |
[] |
[
"python",
"scrapy"
] |
stackoverflow_0047877205_python_scrapy.txt
|
Q:
Threesum problem using python unable to satisfy all the cases
I am trying to solve the famous [Threesum][1] problem with the help of dictionaries. The overall idea is to add the element to the dictionary once visited in case of match or unmatch so that the same element is not used twice for adding up and comparison.
The code is as below:
def threeSum(nums):
nums.sort()
print(nums)
res = []
d = {}
counter = 1
for i in range(len(nums) - 1):
if i not in d.values() and nums[i] not in d.keys():
start = i + 1
end = len(nums) - 1
while start < end:
if (nums[i] + nums[start] + nums[end] == 0):
res.append([nums[i], nums[start], nums[end]])
print([nums[i], nums[start], nums[end]])
start += 1
end -= 1
i += 1
d[nums[i]] = i
d[nums[start]] = start
d[nums[end]] = end
elif (nums[i] + nums[start] + nums[end] > 0):
end -= 1
d[nums[end]] = end
i += 1
d[nums[i]] = i
d[start] = start
d[end] = end
return res
It works fine for below two cases when passed as an input:
list = [-1, 0, 1, 2, -1, -4]
list1 = [0, 0, 0]
It doesn't work for the below case:
list2 = [1, 2, -2, -1]
It returns the output as below:
[[-1, -1, 2]]
Which is incorrect. It should have returned a blank list. Where am I going wrong? I want to solve it with the help of dictionaries only and if possible in very layman's terms...
Any help is much appreciated...
A:
Dictionary implementation:
class Solution(object):
def threeSum(self, nums):
length=len(nums)
res=[]
dic=dict()
nums.sort() #Sorted the nums Time- O(NlogN)
for i in range(length):
dic[nums[i]]=i
#print(dic)
i=0
while i<length and nums[i]<=0: #Run the while loop till i<length and nums[i] is less than or equal to zero
target=-(nums[i])
end=length
j=i+1 # We have converted the question to 2-sum problem now just implement 2-sum.
while j<end:
reside=target-nums[j]
if reside in dic and dic[reside]>j:
res.append([nums[i],nums[j],reside])
end=dic[reside]
j=dic[nums[j]]+1
i=dic[nums[i]]+1
return res
|
Threesum problem using python unable to satisfy all the cases
|
I am trying to solve the famous [Threesum][1] problem with the help of dictionaries. The overall idea is to add the element to the dictionary once visited in case of match or unmatch so that the same element is not used twice for adding up and comparison.
The code is as below:
def threeSum(nums):
nums.sort()
print(nums)
res = []
d = {}
counter = 1
for i in range(len(nums) - 1):
if i not in d.values() and nums[i] not in d.keys():
start = i + 1
end = len(nums) - 1
while start < end:
if (nums[i] + nums[start] + nums[end] == 0):
res.append([nums[i], nums[start], nums[end]])
print([nums[i], nums[start], nums[end]])
start += 1
end -= 1
i += 1
d[nums[i]] = i
d[nums[start]] = start
d[nums[end]] = end
elif (nums[i] + nums[start] + nums[end] > 0):
end -= 1
d[nums[end]] = end
i += 1
d[nums[i]] = i
d[start] = start
d[end] = end
return res
It works fine for below two cases when passed as an input:
list = [-1, 0, 1, 2, -1, -4]
list1 = [0, 0, 0]
It doesn't work for the below case:
list2 = [1, 2, -2, -1]
It returns the output as below:
[[-1, -1, 2]]
Which is incorrect. It should have returned a blank list. Where am I going wrong? I want to solve it with the help of dictionaries only and if possible in very layman's terms...
Any help is much appreciated...
|
[
"Dictionary implementation:\nclass Solution(object):\n def threeSum(self, nums):\n length=len(nums) \n res=[] \n dic=dict()\n nums.sort() #Sorted the nums Time- O(NlogN)\n \n for i in range(length):\n dic[nums[i]]=i\n #print(dic)\n i=0\n while i<length and nums[i]<=0: #Run the while loop till i<length and nums[i] is less than or equal to zero \n target=-(nums[i]) \n end=length\n j=i+1 # We have converted the question to 2-sum problem now just implement 2-sum.\n while j<end:\n reside=target-nums[j]\n if reside in dic and dic[reside]>j: \n res.append([nums[i],nums[j],reside])\n end=dic[reside]\n j=dic[nums[j]]+1 \n i=dic[nums[i]]+1\n return res\n\n"
] |
[
0
] |
[] |
[] |
[
"algorithm",
"data_structures",
"python"
] |
stackoverflow_0072498929_algorithm_data_structures_python.txt
|
Q:
How to create a Plotly animation from a list of figure objects?
I have a list of Plotly figures and I want to create an animation that iterates over each figure on a button press. Similar the examples found on Intro to Animations in Python. I pretty much tried re-creating several of the examples on the page with no luck.
It seems like there should be a simple solution but I have not been able to find one. I should note that I do not want to animate the geocoded cities but rather the weather layout - i.e., mapbox_layers
Below is the code to create the list of figures:
import requests
from bs4 import BeautifulSoup
import pandas as pd
import plotly.express as px
# just some geocoded data from plotly
us_cities = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/us-cities-top-1k.csv")
# GET request to pull the datetime info
r = requests.get('https://geo.weather.gc.ca/geomet?service=WMS&version=1.3.0&request=GetCapabilities&layer=GDPS.DIAG_NW_PT1H')
# create the soup
soup = BeautifulSoup(r.text, 'xml')
# start and end dates in UTC
start, end = soup.findAll('Dimension')[0].text.split('/')[:2]
# create a date range
dates = pd.date_range(start, end, freq='1h').strftime('%Y-%m-%dT%H:%M:%SZ')[0::3]
# iterate over the dates to create the figures
figs = []
for date in dates:
fig = px.scatter_mapbox(us_cities, lat="lat", lon="lon", hover_name="City", hover_data=["State", "Population"],
color_discrete_sequence=["black"], zoom=3, height=600, center={'lat': 42.18845, 'lon':-87.81544},
title=date)
fig.update_layout(
mapbox_style="open-street-map",
mapbox_layers=[
{
"below": 'traces',
"sourcetype": "raster",
"sourceattribution": "Government of Canada",
"source": ["https://geo.weather.gc.ca/geomet/?"
"SERVICE=WMS&VERSION=1.3.0"
"&REQUEST=GetMap"
"&BBOX={bbox-epsg-3857}"
"&CRS=EPSG:3857"
"&WIDTH=1000"
"&HEIGHT=1000"
"&LAYERS=GDPS.DIAG_NW_PT1H"
"&TILED=true"
"&FORMAT=image/png"
f"&TIME={date}"
],
},
]
)
fig.update_layout(margin={"r":0,"t":50,"l":0,"b":0})
figs.append(fig)
figs[0]
figs[6]
figs[12]
A:
I think the most helpful example in the plotly documentation was on visualizing mri volume slices. Instead of creating a list of figure objects, we can store the data and layout of each figure in a list of go.Frame objects and then initialize our figure with these frames with something like fig = go.Figure(frames=[...])
The creation of the buttons and sliders follows the documentation exactly, and these can probably be tweaked to your liking.
Note: the slider will only work if we populate the name argument in each go.Frame object, as pointed out by @It_is_Chris
import requests
from bs4 import BeautifulSoup
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
# just some geocoded data from plotly
us_cities = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/us-cities-top-1k.csv")
# GET request to pull the datetime info
r = requests.get('https://geo.weather.gc.ca/geomet?service=WMS&version=1.3.0&request=GetCapabilities&layer=GDPS.DIAG_NW_PT1H')
# create the soup
soup = BeautifulSoup(r.text, 'xml')
# start and end dates in UTC
start, end = soup.findAll('Dimension')[0].text.split('/')[:2]
# create a date range
dates = pd.date_range(start, end, freq='1h').strftime('%Y-%m-%dT%H:%M:%SZ')[0::3]
# iterate over the dates to create the figures
# figs = []
frames = []
for i, date in enumerate(dates):
fig = px.scatter_mapbox(us_cities, lat="lat", lon="lon", hover_name="City", hover_data=["State", "Population"],
color_discrete_sequence=["black"], zoom=3, height=600, center={'lat': 42.18845, 'lon':-87.81544},
title=date)
fig.update_layout(
mapbox_style="open-street-map",
mapbox_layers=[
{
"below": 'traces',
"sourcetype": "raster",
"sourceattribution": "Government of Canada",
"source": ["https://geo.weather.gc.ca/geomet/?"
"SERVICE=WMS&VERSION=1.3.0"
"&REQUEST=GetMap"
"&BBOX={bbox-epsg-3857}"
"&CRS=EPSG:3857"
"&WIDTH=1000"
"&HEIGHT=1000"
"&LAYERS=GDPS.DIAG_NW_PT1H"
"&TILED=true"
"&FORMAT=image/png"
f"&TIME={date}"
],
},
]
)
fig.update_layout(margin={"r":0,"t":50,"l":0,"b":0})
frames += [go.Frame(data=fig.data[0], layout=fig.layout, name=date)]
## store the first frame to reuse later
if i == 0:
first_fig = fig
fig = go.Figure(frames=frames)
## add the first frame to the figure so it shows up initially
fig.add_trace(first_fig.data[0],)
fig.layout = first_fig.layout
## the rest is coped from the plotly documentation example on mri volume slices
def frame_args(duration):
return {
"frame": {"duration": duration},
"mode": "immediate",
"fromcurrent": True,
"transition": {"duration": duration, "easing": "linear"},
}
sliders = [
{
"pad": {"b": 10, "t": 60},
"len": 0.9,
"x": 0.1,
"y": 0,
"steps": [
{
"args": [[f.name], frame_args(0)],
"label": str(k),
"method": "animate",
}
for k, f in enumerate(fig.frames)
],
}
]
fig.update_layout(
title='Slices in volumetric data',
width=1200,
height=600,
scene=dict(
zaxis=dict(range=[-0.1, 6.8], autorange=False),
aspectratio=dict(x=1, y=1, z=1),
),
updatemenus = [
{
"buttons": [
{
"args": [None, frame_args(50)],
"label": "▶", # play symbol
"method": "animate",
},
{
"args": [[None], frame_args(0)],
"label": "◼", # pause symbol
"method": "animate",
},
],
"direction": "left",
"pad": {"r": 10, "t": 70},
"type": "buttons",
"x": 0.1,
"y": 0,
}
],
sliders=sliders
)
fig.show()
|
How to create a Plotly animation from a list of figure objects?
|
I have a list of Plotly figures and I want to create an animation that iterates over each figure on a button press. Similar the examples found on Intro to Animations in Python. I pretty much tried re-creating several of the examples on the page with no luck.
It seems like there should be a simple solution but I have not been able to find one. I should note that I do not want to animate the geocoded cities but rather the weather layout - i.e., mapbox_layers
Below is the code to create the list of figures:
import requests
from bs4 import BeautifulSoup
import pandas as pd
import plotly.express as px
# just some geocoded data from plotly
us_cities = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/us-cities-top-1k.csv")
# GET request to pull the datetime info
r = requests.get('https://geo.weather.gc.ca/geomet?service=WMS&version=1.3.0&request=GetCapabilities&layer=GDPS.DIAG_NW_PT1H')
# create the soup
soup = BeautifulSoup(r.text, 'xml')
# start and end dates in UTC
start, end = soup.findAll('Dimension')[0].text.split('/')[:2]
# create a date range
dates = pd.date_range(start, end, freq='1h').strftime('%Y-%m-%dT%H:%M:%SZ')[0::3]
# iterate over the dates to create the figures
figs = []
for date in dates:
fig = px.scatter_mapbox(us_cities, lat="lat", lon="lon", hover_name="City", hover_data=["State", "Population"],
color_discrete_sequence=["black"], zoom=3, height=600, center={'lat': 42.18845, 'lon':-87.81544},
title=date)
fig.update_layout(
mapbox_style="open-street-map",
mapbox_layers=[
{
"below": 'traces',
"sourcetype": "raster",
"sourceattribution": "Government of Canada",
"source": ["https://geo.weather.gc.ca/geomet/?"
"SERVICE=WMS&VERSION=1.3.0"
"&REQUEST=GetMap"
"&BBOX={bbox-epsg-3857}"
"&CRS=EPSG:3857"
"&WIDTH=1000"
"&HEIGHT=1000"
"&LAYERS=GDPS.DIAG_NW_PT1H"
"&TILED=true"
"&FORMAT=image/png"
f"&TIME={date}"
],
},
]
)
fig.update_layout(margin={"r":0,"t":50,"l":0,"b":0})
figs.append(fig)
figs[0]
figs[6]
figs[12]
|
[
"I think the most helpful example in the plotly documentation was on visualizing mri volume slices. Instead of creating a list of figure objects, we can store the data and layout of each figure in a list of go.Frame objects and then initialize our figure with these frames with something like fig = go.Figure(frames=[...])\nThe creation of the buttons and sliders follows the documentation exactly, and these can probably be tweaked to your liking.\nNote: the slider will only work if we populate the name argument in each go.Frame object, as pointed out by @It_is_Chris\nimport requests\nfrom bs4 import BeautifulSoup\nimport pandas as pd\nimport plotly.express as px\nimport plotly.graph_objects as go\n\n# just some geocoded data from plotly\nus_cities = pd.read_csv(\"https://raw.githubusercontent.com/plotly/datasets/master/us-cities-top-1k.csv\")\n# GET request to pull the datetime info\nr = requests.get('https://geo.weather.gc.ca/geomet?service=WMS&version=1.3.0&request=GetCapabilities&layer=GDPS.DIAG_NW_PT1H')\n# create the soup\nsoup = BeautifulSoup(r.text, 'xml')\n# start and end dates in UTC\nstart, end = soup.findAll('Dimension')[0].text.split('/')[:2]\n# create a date range\ndates = pd.date_range(start, end, freq='1h').strftime('%Y-%m-%dT%H:%M:%SZ')[0::3]\n# iterate over the dates to create the figures\n# figs = []\nframes = []\nfor i, date in enumerate(dates):\n fig = px.scatter_mapbox(us_cities, lat=\"lat\", lon=\"lon\", hover_name=\"City\", hover_data=[\"State\", \"Population\"],\n color_discrete_sequence=[\"black\"], zoom=3, height=600, center={'lat': 42.18845, 'lon':-87.81544}, \n title=date)\n \n fig.update_layout(\n mapbox_style=\"open-street-map\",\n mapbox_layers=[\n {\n \"below\": 'traces',\n \"sourcetype\": \"raster\",\n \"sourceattribution\": \"Government of Canada\",\n \"source\": [\"https://geo.weather.gc.ca/geomet/?\"\n \"SERVICE=WMS&VERSION=1.3.0\"\n \"&REQUEST=GetMap\"\n \"&BBOX={bbox-epsg-3857}\"\n \"&CRS=EPSG:3857\"\n \"&WIDTH=1000\"\n \"&HEIGHT=1000\"\n \"&LAYERS=GDPS.DIAG_NW_PT1H\"\n \"&TILED=true\"\n \"&FORMAT=image/png\"\n f\"&TIME={date}\"\n ],\n },\n ]\n )\n fig.update_layout(margin={\"r\":0,\"t\":50,\"l\":0,\"b\":0})\n frames += [go.Frame(data=fig.data[0], layout=fig.layout, name=date)]\n\n ## store the first frame to reuse later\n if i == 0:\n first_fig = fig\n\nfig = go.Figure(frames=frames)\n\n## add the first frame to the figure so it shows up initially\nfig.add_trace(first_fig.data[0],)\nfig.layout = first_fig.layout\n\n## the rest is coped from the plotly documentation example on mri volume slices\ndef frame_args(duration):\n return {\n \"frame\": {\"duration\": duration},\n \"mode\": \"immediate\",\n \"fromcurrent\": True,\n \"transition\": {\"duration\": duration, \"easing\": \"linear\"},\n }\n\nsliders = [\n {\n \"pad\": {\"b\": 10, \"t\": 60},\n \"len\": 0.9,\n \"x\": 0.1,\n \"y\": 0,\n \"steps\": [\n {\n \"args\": [[f.name], frame_args(0)],\n \"label\": str(k),\n \"method\": \"animate\",\n }\n for k, f in enumerate(fig.frames)\n ],\n }\n ]\n\nfig.update_layout(\n title='Slices in volumetric data',\n width=1200,\n height=600,\n scene=dict(\n zaxis=dict(range=[-0.1, 6.8], autorange=False),\n aspectratio=dict(x=1, y=1, z=1),\n ),\n updatemenus = [\n {\n \"buttons\": [\n {\n \"args\": [None, frame_args(50)],\n \"label\": \"▶\", # play symbol\n \"method\": \"animate\",\n },\n {\n \"args\": [[None], frame_args(0)],\n \"label\": \"◼\", # pause symbol\n \"method\": \"animate\",\n },\n ],\n \"direction\": \"left\",\n \"pad\": {\"r\": 10, \"t\": 70},\n \"type\": \"buttons\",\n \"x\": 0.1,\n \"y\": 0,\n }\n ],\n sliders=sliders\n)\n\nfig.show()\n\n\n"
] |
[
1
] |
[] |
[] |
[
"plotly",
"plotly_dash",
"python"
] |
stackoverflow_0074526203_plotly_plotly_dash_python.txt
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.