I am getting an error in dash app. The error: "You have already assigned a callback to the output with the ID "prediction" and property "children". An output can only have a single callback function. Try combining your inputs and callback functions together into one function."
I have only one callback function in my code.
How to resolve this?
My code below:
model_data = pd.read_csv("data.csv")
style = {'padding': '1.5em'}
app.layout = html.Div([
dcc.Markdown("""
### Predict
"""),
html.Div(id='prediction-content', style={'fontWeight': 'bold'}),
html.Div([
dcc.Markdown('###### Input1'),
dcc.Dropdown(
id='Input1',
options=[{'label': 1, 'value': 1}],
value= 1
),
], style=style),
html.Div([
dcc.Markdown('###### Input2'),
dcc.Slider(
id='Input2',
min=23,
max=27,
step=0.5,
value=23,
tooltip={'always_visible': True},
marks={
23: {'label': '23'},
24: {'label': '24'},
25: {'label': '25'},
26: {'label': '26'}
},
included=False
)
], style=style),
html.Div([
dcc.Markdown('###### Input3'),
dcc.Slider(
id='Input3',
min=10,
max=50,
step=1,
value=30,
tooltip={'always_visible': True},
marks={
10: {'label': '10'},
20: {'label': '20'},
30: {'label': '30'},
40: {'label': '40'},
50: {'label': '50'}
},
included=False
)
], style=style),
])
#app.callback(
Output('prediction-content', 'children'),
[Input('Input1', 'value'),
Input('Input2', 'value'),
Input('Input3', 'value')])
def predict(a, b, c):
data2 = pd.DataFrame(data = [[a, b, c,]],
columns = ['Input1', 'Input2','Input3']
, index = [36])
data3 = model_data.combine_first(data2)
#### full function hidden due to confidentiality
def calculate(df,i,j):
###
####
return(a1)
output = a1*2
results = f'Result is ${output:,.0f}.'
return results
if __name__ == '__main__':
app.run_server(debug=True)
i had the same issue using Jupiter notebook but solved it by killing the server and restarting my kernel, i assume that the callback assigns the function once and if you try to re-assign it again it will through that error. I guess this error will be thrown only when you are using hot reloading.
Related
Here is a snippet of function code in Python:
def restart_lab_server(aws_client):
response = aws_client.describe_instances()
###print(response)
for reservation in response["Reservations"]:
for instance in reservation["Instances"]:
# This sample print will output entire Dictionary object
# This will print will output the value of the Dictionary key 'InstanceId'
try:
print(instance["Tags"])
except:
print("This instance does not have any tags.")
print("Next Entry.")
return 0
The output that I am getting this the following:
[{'Key': 'Name', 'Value': 'EC2-Nessus-AmazonLinux2'}]
[{'Key': 'Name', 'Value': 'LCE Server'}]
[{'Key': 'Name', 'Value': 'Windows-2019-xxxxx'}]
[{'Key': 'Name', 'Value': 'SecurityCenter-Lab-5.19.1'}]
[{'Key': 'Name', 'Value': 'Nessus-Target-Lab'}]
[{'Key': 'Name', 'Value': 'Nessus-Agent-Lab'}]
[{'Key': 'Name', 'Value': 'NNM-Lab'}]
[{'Key': 'Name', 'Value': 'WindowsInstance'}]
This instance does not have any tags.
Next Entry.
[{'Key': 'CfStackId', 'Value': 'arn:aws:cloudformation:us-east-1:581987831513:stack/Nessus-Thomas-101-2/41d38410-5729-11ed-a52f-127af16651f7'}, {'Key': 'aws:cloudformation:stack-id', 'Value': 'arn:aws:cloudformation:us-east-1:581987831513:stack/Nessus-Thomas-101-2/41d38410-5729-11ed-a52f-127af16651f7'}, **{'Key': 'NessusScanner', 'Value': 'TRUE'},** {'Key': 'aws:cloudformation:logical-id', 'Value': 'NessusEC2Instance'}, {'Key': 'aws:cloudformation:stack-name', 'Value': 'Nessus-Thomas-101-2'}]
My main interest is to get "{'Key': 'NessusScanner', 'Value': 'TRUE'},"
I can't seem to extract this or not sure how to. I am not sure if I need to use a linescanner or something else.
I'm trying to restart all Nessus scanners in my and figured using key and value Nessus scanner True.
Please note, I'm using
describe_instances()
I have tried creating another for loop but keep getting an error message.
Found the answer or workaround:
def restart_lab_server(aws_client):
response = aws_client.describe_instances()
###print(response)
for reservation in response["Reservations"]:
for instance in reservation["Instances"]:
try:
x = instance["Tags"]
for y in x:
print(y["Value"])
except:
print("This instance does not have any tags. Next Entry.")
return 0
I have a df 'beersmerged' which contains a column 'state'. I am attempting to create a column 'region' which evaluates the value in 'state' and adds the appropriate value to 'region'.
This code runs without error and creates the 'region' column, but every row has the same value - None. I've tried several other approaches and they all have a similar result in that they put the same value in every row. Thanks in advance for any assistance you can provide!
def get_region(state, *region):
if state in region[0]:
return 'New_England'
elif state in region[1]:
return 'Mid_Atlantic'
elif state in region[2]:
return 'South'
elif state in region[3]:
return 'Midwest'
elif state in region[4]:
return 'Southwest'
elif state in region[5]:
return 'West'
else:
return None
New_England = ['CT', 'ME', 'MA', 'NH', 'RI', 'VT']
Mid_Atlantic = ['DC', 'DE', 'MD', 'NJ', 'NY', 'PA']
South = ['AL', 'AR', 'FL', 'GA', 'KY', 'LA', 'MS', 'MO', 'NC', 'SC', 'TN', 'VA', 'WV']
Mid_West = ['IL', 'IN', 'IA', 'KS', 'MI', 'MN', 'NE', 'ND', 'OH', 'SD', 'WI']
Southwest = ['AZ', 'NM','OK', 'TX']
West = ['AK', 'CA', 'CO', 'HI', 'ID', 'MT', 'NV', 'OR', 'UT', 'WA', 'WY']
region = [New_England, Mid_Atlantic, South, Midwest, Southwest, West]
beersmerged['region'] = beersmerged['state'].apply(get_region, args=(region))
beersmerged.head()
I've also tried this using the lists above and it runs without error but puts a 0 for 'region' in every row:
class_regions ={'New_England':New_England,'Mid_Atlantic':Mid_Atlantic,'South':South,'Midwest':Midwest,'Southwest':Southwest,'West':West}
dict_cond_values = {key:beersmerged['state'].isin(class_regions[key]) for key in class_regions}
beersmerged['region']=np.select(dict_cond_values.values(),dict_cond_values.keys())
beersmerged.head()
I was expecting something like this:
state region
OR West
IN Midwest
TX Southwest
NH New_England
VA Mid_Atlantic
But get this:
state region
OR None
IN None
TX None
NH None
VA None
In the original version, specify with a comma that the type of args is tuple as it's required and get rid of asterisk * in front of region parameter of the get_region.
get_region(state, region):
...
beersmerged['region'] = beersmerged['state'].apply(get_region, args=(region,))
But I think it's better to use dict instead of list.
def get_region(state, region):
if state in region['New_England']:
return 'New_England'
elif state in region['Mid_Atlantic']:
return 'Mid_Atlantic'
elif state in region['South']:
return 'South'
elif state in region['Midwest']:
return 'Midwest'
elif state in region['Southwest']:
return 'Southwest'
elif state in region['West']:
return 'West'
else:
return None
New_England = ['CT', 'ME', 'MA', 'NH', 'RI', 'VT']
Mid_Atlantic = ['DC', 'DE', 'MD', 'NJ', 'NY', 'PA']
South = ['AL', 'AR', 'FL', 'GA', 'KY', 'LA', 'MS', 'MO', 'NC', 'SC', 'TN', 'VA', 'WV']
Mid_West = ['IL', 'IN', 'IA', 'KS', 'MI', 'MN', 'NE', 'ND', 'OH', 'SD', 'WI']
Southwest = ['AZ', 'NM','OK', 'TX']
West = ['AK', 'CA', 'CO', 'HI', 'ID', 'MT', 'NV', 'OR', 'UT', 'WA', 'WY']
region = {'New_England': New_England, 'Mid_Atlantic': Mid_Atlantic, 'South': South, 'Midwest': Midwest, 'Southwest': Southwest, 'West': West}
beersmerged['region'] = beersmerged['state'].apply(get_region, args=(region,))
beersmerged.head()
I'm currently working on a dash_table in which I have already incorporated an add row button as well as delete. I would like the user to also be able to add rows by using a slider value. How would I be able to do that with making changes to current code?
html.Div(children=[
html.Label('# of Wells on Pad', style={'color':colors['text']}),
dcc.Slider(
id='well_slider',
min=0,
max=12,
step=1,
marks={i: f' {i}' if i == 1 else str(i) for i in range(13)},
value=0,
),
], style={'padding': 10, 'flex': 1, 'background-color':colors['background'],'margin':20})
], style={'display': 'flex', 'flex-direction': 'row',}),
# html.
html.Div(children=[
dash_table.DataTable(
id='projection_table',
columns=[{
'name': i,
'id': i,
} for i in table_outputs],
style_cell={'text-align':'center'},
data=[
{'column-{}'.format(i): (j + (i-1)*5) for i in range(1, 5)}
for j in range(5)
],
editable=True,
fill_width=True,
row_deletable=True,
export_format='xlsx',
export_headers='display',
style_table={'overflowX':'scroll'}
),
html.Button('Add Row', id='editing-rows-button', n_clicks=0, style={'margin':5}),
html.Div(id='testingSlider', style={"color":colors['text']})
],style={'margin':10})
#app.callback(
Output('projection_table', 'data'),
Input('editing-rows-button', 'n_clicks'),
State('projection_table', 'data'),
State('projection_table', 'columns')
)
def add_row(n_clicks, rows, table_outputs):
if n_clicks > 0:
rows.append({c['id']: '' for c in table_outputs})
return rows
#app.callback(
Output('testingSlider', 'children'),
Input('well_slider', 'value'),
State('projection_table', 'data'),
State('projection_table', 'columns')
)
def add_row_slider(value, rows, table_outputs):
if value > 0:
rows.append({c['id']: '' for c in table_outputs})
return rows
The Key:Value pairs from the following dictionary is as follows
result.items()
dict_items([('subjectArea', 'Work'), ('txn-timestamp', '2022-01-05 11:31:10'), ('foundation', {'schema': 'AZ_FH_ELLIPSE', 'table': 'AZ_FND_MSF620', 'keys': [{'key': 'DSTRCT_CODE', 'value': 'RTK1'}, {'key': 'WORKORDER', 'value': '11358186'}], 'dataMart': {'dependencies': [{'schema': 'AZ_DM_WORK', 'table': 'DIM_WORK_ORDER'}, {'schema': 'AZ_DM_WORK', 'table': 'FACT_WORK_ITEM'}]}})])
Can someone let me know if its possible to convert the above into a Spark DataFrame?
My apologies, I'mm not sure how to do a line break to make the code look neater
Here is the below pyspark code:
from pyspark.sql.types import *
items1 = [{'subjectArea': 'Work', 'txn-timestamp': '2022-01-05 11:31:10', 'foundation': {'schema': 'AZ_FH_ELLIPSE', 'table': 'AZ_FND_MSF620', 'keys': [{'key': 'DSTRCT_CODE', 'value': 'RTK1'}, {'key': 'WORKORDER', 'value': '11358186'}], 'dataMart': {'dependencies': [{'schema': 'AZ_DM_WORK', 'table': 'DIM_WORK_ORDER'}, {'schema': 'AZ_DM_WORK', 'table': 'FACT_WORK_ITEM'}]}}}]
schema1 = StructType([StructField('subjectArea',StringType()),StructField('txn-timestamp',StringType()),StructField('foundation',StructType([StructField('schema',StringType()),StructField('table',StringType()),StructField('keys',StructType([StructField('key',StringType()),StructField('value',StringType())])),StructField('dataMart',StructType([StructField('dependencies',StructType([StructField('schema',StringType()),StructField('table',StringType())]))]))]))])
ddf = spark.createDataFrame(items1, schema1)
ddf.printSchema()
ddf.show()
ddf.select(ddf['foundation'].datamart).show(truncate=False)
I have one column in data frame with values like this List with dictionary inside
[{'symbol': '$', 'value': 5.2, 'currency': 'USD', 'raw': '$5.20', 'name': '$5.20$5.20 ($1.30/Fl Oz)', 'asin': 'B07N31VZP8']
I want only 'value' from this dictionary.
for i in df["prices"]:
try:
#print(type(i[0]["value"]))
df["prices"] = df["prices"].apply(lambda i:i[0]["value"])
except Exception as e:
print("",e)
but I'm getting the following error even if I was able to get that value, I cant populate it in dataframe column
'float' object is not subscribable
How to overcome this issue ?
I think the problem is that you apply the transformation multiple times. The apply() already applies the transformation for every row in your dataframe. If you remove the loop it should work:
import pandas as pd
# Create your data
df = pd.DataFrame([
['test',[{'symbol': '$', 'value': 5.2, 'currency': 'USD', 'raw': '$5.20', 'name': '$5.20$5.20 ($1.30/Fl Oz)', 'asin': 'B07N31VZP8'}]]
, ['test',[{'symbol': '$', 'value': 6.8, 'currency': 'USD', 'raw': '$5.20', 'name': '$5.20$5.20 ($1.30/Fl Oz)', 'asin': 'B07N31VZP8'}]]
], columns=['test','prices'])
print(df)
df["prices"] = df["prices"].apply(lambda i:i[0]["value"])
print(df)
Input dataframe:
test prices
0 test [{'symbol': '$', 'value': 5.2, 'currency': 'US...
1 test [{'symbol': '$', 'value': 6.8, 'currency': 'US...
Output dataframe:
test prices
0 test 5.2
1 test 6.8