Failed to find application object 'server' in 'app' - heroku

I am trying to serve a Dash app using Heroku. I have 5 files in my app:
.gitignore
venv
*.pyc
.DS_Store
.env
app.py
import os
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objs as go
import pandas as pd
# Read in the data
districts_change = pd.read_csv("https://github.com/thedatasleuth/New-York-Congressional-Districts/blob/master/districts_change.csv?raw=True")
df = districts_change.drop(['TOTAL'], axis=1)
# Get a list of all the districts
districts = districts_change['DISTRICT'].unique()
# Create the app
app = dash.Dash()
# Populate the layout with HTML and graph components
app.layout = html.Div([
html.H2("New York Congressional Districts"),
html.Div(
[
dcc.Dropdown(
id="DISTRICT",
options=[{
'label': 'District {}'.format(i),
'value': i
} for i in districts],
value='All Districts'),
],
style={'width': '25%',
'display': 'inline-block'}),
dcc.Graph(id='funnel-graph'),
])
# Add the callbacks to support the interactive componets
#app.callback(
dash.dependencies.Output('funnel-graph', 'figure'),
[dash.dependencies.Input('DISTRICT', 'value')])
def update_graph(Districts):
if Districts == "All Districts":
df_plot = df.copy()
else:
df_plot = df[df['DISTRICT'] == Districts]
trace1 = go.Bar(x=df_plot ['Year'], y=df_plot [('DEM')], name='DEM')
trace2 = go.Bar(x=df_plot ['Year'], y=df_plot [('REP')], name='REP')
trace3 = go.Bar(x=df_plot ['Year'], y=df_plot [('CON')], name='CON')
trace4 = go.Bar(x=df_plot ['Year'], y=df_plot [('WOR')], name='WOR')
trace5 = go.Bar(x=df_plot ['Year'], y=df_plot [('IND')], name='IND')
trace6 = go.Bar(x=df_plot ['Year'], y=df_plot [('GRE')], name='GRE')
trace7 = go.Bar(x=df_plot ['Year'], y=df_plot [('WEP')], name='WEP')
trace8 = go.Bar(x=df_plot ['Year'], y=df_plot [('REF')], name='REF')
trace9 = go.Bar(x=df_plot ['Year'], y=df_plot [('OTH')], name='OTH')
trace10 = go.Bar(x=df_plot ['Year'], y=df_plot [('BLANK')], name='BLANK')
return {
'data': [trace1, trace2, trace3, trace4, trace5,
trace6, trace7, trace8, trace9, trace10],
'layout':
go.Layout(
title='District {}'.format(Districts),
barmode='group')
}
if __name__ == '__main__':
app.server.run(debug=True)
Procfile
web: gunicorn app:server
requirements.txt
Flask==1.0.2
gunicorn==19.9.0
dash==0.26.5
dash-core-components==0.29.0
dash-html-components==0.12.0
dash-renderer==0.13.2
plotly==3.2.1
pandas==0.23.1
pandas-datareader==0.6.0
runtime.txt
python-3.6.6
I am able to build the app successfully in Heroku, however, I am unable to serve it properly, given this error message:
Failed to find application object 'server' in 'app'
What server is it talking about? Usually when I get this error I just add whatever is missing to the requirements.txt file.

I added: server = app.server right under app = dash.Dash()

Related

Plotly Dash Heatmap not updating with dropdown selection

I am new to plotly dash and i'm trying to make a heatmap that changes with a dropdown selection. The dropdown is to choose a month, but the heatmap doesn't change!
My data frame is called 'New'.
Here's my code:
Month_Default = New['Month'].unique()
Month_def = 2
#create the dash app
app = dash.Dash()
app.layout = html.Div([
html.H1('//Title'),
html.Div([
html.Div([
html.H4('Select Month...'),
dcc.Dropdown(
id='Month_dropdown',
options=[{'label': i, 'value': i} for i in Month_Default],
value = Month_Def
),
],
style={'width': '48%', 'display': 'inline-block'}),
dcc.Graph(id='heatmap',
figure = {
'data': [go.Heatmap(
x=New['Days'].where(New['Month']==2),
y=New['Hour'],
z=New['Usage'],
colorscale='Viridis')],
'layout': go.Layout(
xaxis = dict(title = 'Days'),
yaxis = dict( title = 'Hours'),
)})
]),])
#app.callback(
dash.dependencies.Output(component_id='heatmap',component_property='figure'),
[dash.dependencies.Input(component_id='Month_dropdown',component_property='value')]
)
def update_graph(Month_dropdown):
filtered_df = New[New['Month'] == Month_dropdown]
heat_fig = go.Heatmap(filtered_df,
x='Days', y='Hour', z='Usage',
colorscale='Viridis',
title='PM KWH Usage')
return heat_fig
have created New dataframe in the way you described it in comments
using dash 2.0.0 hence only need to import dash
two key steps missed
did not app.run_server() to start the dash app
no callback to respond to Dropdown
instead of repeating code in dash layout and callback moved figure creation to just the callback
import dash
from jupyter_dash import JupyterDash
import plotly.graph_objects as go
from dash.dependencies import Input, Output, State
import pandas as pd
import numpy as np
New = pd.DataFrame(
{"date": pd.date_range("1-jan-2021", "15-jun-2021", freq="H")}
).assign(
Usage=lambda d: np.random.uniform(0, 1, len(d)),
Month=lambda d: d["date"].dt.month,
Days=lambda d: d["date"].dt.day,
Hour=lambda d: d["date"].dt.hour,
)
Month_Default = New["Month"].unique()
Month_def = 2
# create the dash app
# app = dash.Dash()
app = JupyterDash(__name__)
app.layout = dash.html.Div(
[
dash.html.H1("//Title"),
dash.html.Div(
[
dash.html.Div(
[
dash.html.H4("Select Month..."),
dash.dcc.Dropdown(
id="Month_dropdown",
options=[{"label": i, "value": i} for i in Month_Default],
value=Month_def,
),
],
style={"width": "48%", "display": "inline-block"},
),
dash.dcc.Graph(id="heatmap"),
]
),
]
)
#app.callback(Output("heatmap", "figure"), Input("Month_dropdown", "value"))
def updateGraph(value):
if not value:
value = Month_def
return {
"data": [
go.Heatmap(
x=New["Days"].where(New["Month"] == value),
y=New["Hour"],
z=New["Usage"],
colorscale="Viridis",
)
],
"layout": go.Layout(
xaxis=dict(title="Days"),
yaxis=dict(title="Hours"),
margin={"l": 0, "r": 0, "t": 0, "b": 0},
),
}
app.run_server(mode="inline")

Gatsby: How Do I Make a List of All Nodes?

I want to make a list of all unique node values and render them on my page. This is what I have:
import { graphql, Link } from "gatsby"
import React from "react"
import Layout from "../layouts/Layout"
const _ = require("lodash")
export default props => {
const majorNodes = props.item.edges.node
let majors = []
let major = []
majorNodes.map(majorNode => majors.push(majorNode.major))
majors = majors.concat(major)
majors = _.uniq(majors)
return (
<Layout>
<div>{majors}</div>
</Layout>
)
}
export const query = graphql`
query majors {
item: allContentfulPortfolio {
edges {
node {
major
}
}
}
}
`
However, this gives me the following error:
TypeError: Cannot read property 'edges' of undefined
_default
D:/Gatsby/archives/src/pages/majors.js:7
4 | const _ = require("lodash")
5 |
6 | export default props => {
> 7 | const majorNodes = props.item.edges.node
8 | let majors = []
9 | let major = []
10 | majorNodes.map(majorNode => majors.push(majorNode.major))
How do I fix this? Additionally, is this how I should pass the array majors for rendering? I think that is where I am going wrong.
Your nodes are stored inside props.data so:
const majorNodes = props.item.edges.node
Should become:
const majorNodes = props.data.item.edges.node
Additionally, is this how I should pass the array majors for
rendering? I think that is where I am going wrong.
majors is an array so printing it directly as:
<div>{majors}</div>
Won't work.
You should loop through each element with something like:
<div>{majors.map(major => <p> Major element is {major}</p> )}</div>

BuildBot: unable to inject extended event handler in master.cfg

Buildbot version: 1.3.0
Twisted version: 18.4.0
my master.cfg
# -*- python -*-
# ex: set filetype=python:
from buildbot.plugins import *
from config import *
import os
from hooks import CustomHandler
# ip related imports
import socket
import fcntl
import struct
def get_ip_address(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', bytes(ifname[:15], 'utf-8'))
)[20:24])
#--------------------------------------------------------------
# CONSTANTS
localhost = get_ip_address(NETWORK_INTERFACE)
HOME = os.environ['HOME']
#--------------------------------------------------------------
c = BuildmasterConfig = {}
####### WORKERS
c['workers'] = [worker.Worker("example-worker", "pass")]
c['protocols'] = {'pb': {'port': 9989}}
c['www'] = dict(port=8010,plugins=dict(waterfall_view={}, console_view={}, grid_view={}))
####### CHANGESOURCES
c['www']['change_hook_dialects'] = { }
c['www']['change_hook_dialects']['bitbucketcloud'] = {
'class': CustomHandler
}
####### SCHEDULERS
c['schedulers'] = []
c['schedulers'].append(schedulers.SingleBranchScheduler(
name="schedulerQueryBuilder",
change_filter=util.ChangeFilter(repository_re='.*/querybuilder',
branch_re='.*/build_bot_testing',
category='push'),
treeStableTimer=None,
builderNames=["BuilderOfQueryBuilder"]
))
c['schedulers'].append(schedulers.ForceScheduler(
name="build",
builderNames=["BuilderOfQueryBuilder"]))
####### BUILDERS
BitBucketFactory = util.BuildFactory()
BitBucketFactory.addStep(steps.Git(
repourl='git#host:A/B.git',
branch='build_bot_testing',
retryFetch=True,
clobberOnFailure=True,
mode='incremental'))
BitBucketFactory.addStep(steps.PyLint(command=['pylint', '--py3k', '--ignore ln2sql',
'--disable C,import-error,import-error,too-few-public-methods,undefined-variable',
'swagger_server'],
haltOnFailure=True))
BitBucketFactory.addStep(steps.Test(command=["pytest", "swagger_server"],
haltOnFailure=False))
BitBucketFactory.addStep(steps.ShellSequence(commands=[
util.ShellArg(command=['zip', '-r', '/home/rajat/buildbot/worker/BuilderOfQueryBuilder/build.zip',
'/home/rajat/buildbot/worker/BuilderOfQueryBuilder/build'],
logfile='ShellSequenceLog', haltOnFailure=True),
util.ShellArg(command=['scp', '-i', '/home/rajat/.ssh/id_rsa.pub', '-rp',
'/home/rajat/buildbot/worker/BuilderOfQueryBuilder/build.zip',
'rajat#192.168.0.21:/home/rajat/buildbot/querybuilder/build.zip'],
logfile='ShellSequenceLog', haltOnFailure=True),
util.ShellArg(command=['ssh', '-i', '/home/rajat/.ssh/id_rsa.pub', 'rajat#192.168.0.21',
'rm','-rf', '/home/rajat/buildbot/querybuilder/build'],
logfile='ShellSequenceLog', flunkOnFailure=True),
util.ShellArg(command=['ssh', '-i', '/home/rajat/.ssh/id_rsa.pub', 'rajat#192.168.0.21',
'unzip','-o', '/home/rajat/buildbot/querybuilder/build.zip', '-d', '/home/rajat/buildbot/querybuilder/'],
logfile='ShellSequenceLog', haltOnFailure=True),
util.ShellArg(command=['ssh', '-i', '/home/rajat/.ssh/id_rsa.pub', 'rajat#192.168.0.21',
'/home/rajat/anaconda3/envs/querybuilder/bin/pip',
'install', '--upgrade', 'setuptools'],
logfile='ShellSequenceLog', haltOnFailure=True),
util.ShellArg(command=['ssh', '-i', '/home/rajat/.ssh/id_rsa.pub', 'rajat#192.168.0.21',
'/home/rajat/anaconda3/envs/querybuilder/bin/pip', 'install', '-r', '/home/rajat/buildbot/querybuilder/build/requirements.txt'],
logfile='ShellSequenceLog', haltOnFailure=True),
util.ShellArg(command=['ssh', '-f', '-i', '/home/rajat/.ssh/id_rsa.pub', 'rajat#192.168.0.21',
'cd', '/home/rajat/buildbot/querybuilder/build','&&','nohup','/home/rajat/anaconda3/envs/querybuilder/bin/python', '-m',
'swagger_server', '&>',
'/home/rajat/logs/log.txt', '&'],
logfile='ShellSequenceLog', haltOnFailure=True),
]))
# BitBucketFactory.workdir = 'customDirName'
# Default is build in path /worker/<BuilderName>/build/<fetched files>
c['builders'] = []
c['builders'].append(util.BuilderConfig(
name="BuilderOfQueryBuilder",
workernames=["example-worker"],
factory=BitBucketFactory,
properties = {'owner': [
'foo#leadics.com'
]
}))
####### BUILDBOT SERVICES
c['services'] = []
c['services'].append(reporters.MailNotifier(fromaddr="buildbot#foo.com",
sendToInterestedUsers=True,
#extraRecipients=["foo#bar.com"],
useTls=True, relayhost="smtp.gmail.com",
smtpPort=587, smtpUser="buildbot#company.com",
smtpPassword="password"))
####### PROJECT IDENTITY
c['title'] = "BitBucket_BuildBot"
c['titleURL'] = "https://buildbot.github.io/hello-world/"
c['buildbotURL'] = "http://"+localhost+":8010/"
####### DB URL
c['db'] = {
'db_url' : "sqlite:///state.sqlite",
}
hooks.py
from buildbot.www.hooks.bitbucketcloud import BitbucketCloudEventHandler
class CustomHandler(BitbucketCloudEventHandler):
def handle_repo_push(self, payload):
changes = []
#project = payload['repository']['name']
repo_url = payload['repository']['links']['self']['href']
web_url = payload['repository']['links']['html']['href']
for payload_change in payload['push']['changes']:
if payload_change['new']:
age = 'new'
category = 'push'
else: # when new is null the ref is deleted
age = 'old'
category = 'ref-deleted'
commit_hash = payload_change[age]['target']['hash']
if payload_change[age]['type'] == 'branch':
branch = GIT_BRANCH_REF.format(payload_change[age]['name'])
elif payload_change[age]['type'] == 'tag':
branch = GIT_TAG_REF.format(payload_change[age]['name'])
change = {
'revision': commit_hash,
'revlink': '{}/commits/{}'.format(web_url, commit_hash),
'repository': repo_url,
'author': '{} <{}>'.format(payload['actor']['display_name'],
payload['actor']['username']),
'comments': 'Bitbucket Cloud commit {}'.format(commit_hash),
'branch': branch,
#'project': project,
'category': category
}
if callable(self._codebase):
change['codebase'] = self._codebase(payload)
elif self._codebase is not None:
change['codebase'] = self._codebase
changes.append(change)
return (changes, payload['repository']['scm'])
but still it's pointing to the buildbot.www.hooks.bitbucketcloud 's BitbucketCloudEventHandler
getting following error
2018-07-16 17:02:05+0530 [_GenericHTTPChannelProtocol,0,127.0.0.1] adding changes from web hook
Traceback (most recent call last):
File "/home/rajat/anaconda3/envs/buildbot/lib/python3.6/site-packages/twisted/internet/defer.py", line 1532, in unwindGenerator
return _inlineCallbacks(None, gen, Deferred())
File "/home/rajat/anaconda3/envs/buildbot/lib/python3.6/site-packages/twisted/internet/defer.py", line 1386, in _inlineCallbacks
result = g.send(result)
File "/home/rajat/anaconda3/envs/buildbot/lib/python3.6/site-packages/buildbot/www/change_hook.py", line 107, in getAndSubmitChanges
changes, src = yield self.getChanges(request)
File "/home/rajat/anaconda3/envs/buildbot/lib/python3.6/site-packages/twisted/internet/defer.py", line 1532, in unwindGenerator
return _inlineCallbacks(None, gen, Deferred())
--- <exception caught here> ---
File "/home/rajat/anaconda3/envs/buildbot/lib/python3.6/site-packages/twisted/internet/defer.py", line 1386, in _inlineCallbacks
result = g.send(result)
File "/home/rajat/anaconda3/envs/buildbot/lib/python3.6/site-packages/buildbot/www/change_hook.py", line 168, in getChanges
changes, src = yield handler.getChanges(request)
File "/home/rajat/anaconda3/envs/buildbot/lib/python3.6/site-packages/buildbot/www/hooks/bitbucketcloud.py", line 165, in getChanges
return self.process(request)
File "/home/rajat/anaconda3/envs/buildbot/lib/python3.6/site-packages/buildbot/www/hooks/bitbucketcloud.py", line 56, in process
return handler(payload)
File "/home/rajat/anaconda3/envs/buildbot/lib/python3.6/site-packages/buildbot/www/hooks/bitbucketcloud.py", line 75, in handle_repo_push
project = payload['repository']['project']['name']
builtins.KeyError: 'project'
what am i doing wrong ?
i have to override the class because bitbucket has changed their hook json and project key is removed.
any help'll be appreciated.

Nativescript iOS UIColor

I want set the NavigationBar/ActionBar Color to Transparent/Clear in Nativescript.
import {BasePage} from "../../shared/BasePage";
import frameModule = require("ui/frame");
import {topmost} from "ui/frame";
import {Observable, EventData} from "data/observable";
import {View} from "ui/core/view";
class HomePage extends BasePage{
mainContentLoaded(args:EventData){
let view = <View>args.object;
if(view.ios){
var controller = frameModule.topmost().ios.controller;
controller.navigationBar.barTintColor = UIColor.redColor();
}
view.bindingContext = new Observable({ myText: 'This is the home page' });
}
}
export = new HomePage();
But i get this error: "error TS2304: Cannot find name 'UIColor'"
What i doing wrong?
Thanks for help
I suggest you to use the NS color module and convert it to iOS color, so that you can use any color that you want. Like this:
var colorModule = require("color");
var red = new colorModule.Color("#ff0000");
var controller = frameModule.topmost().ios.controller;
controller.navigationBar.barTintColor = red.ios;

Cannot Get Pygtk to Display Label in Hbox

I'm extremely new to Pygtk and Stackoverflow in general. I'm trying to build a small dictionary application: I have one master VBox and an Hbox containing two Vboxes divided by a Vseparator. I am trying to display text through a label in the right-hand Vbox, but it will not appear. Here's my pitiful code:
import gtk
import pygtk
from Wordlist import *
pygtk.require('2.0')
def click_handler(button):
for i in nouns:
print i
k = gtk.Label(str=i)
k.show()
meaningvbox.pack_start(k,True,True,0)
window = gtk.Window(gtk.WINDOW_TOPLEVEL)
window.set_size_request(300,400)
window.set_title("English-Japanese Reference")
window.show()
window.connect("delete-event", gtk.main_quit)
vbox = gtk.VBox(False,0)
window.add(vbox)
vbox.show()
hbox = gtk.HBox(True,0)
vbox.pack_end(hbox,False)
hbox.show()
hbox2 = gtk.HBox(True,0)
vbox.pack_end(hbox2,False)
hbox2.show()
vsep = gtk.VSeparator()
vbox.pack_start(vsep)
vsep.show()
dichbox = gtk.HBox() #### These are boxes created to store the words
vbox.pack_start(dichbox)
wordvbox = gtk.VBox()
dichbox.pack_start(wordvbox)
wordvbox.show()
meaningvbox = gtk.VBox()
dichbox.pack_start(meaningvbox)
meaningvbox.show()
label = gtk.Label(str="hi")
meaningvbox.pack_start(label)
label.show()
verbButton = gtk.Button(label="Verbs")
hbox.pack_end(verbButton,True,False)
verbButton.set_size_request(100,30)
verbButton.show()
nounButton = gtk.Button(label="Nouns")
nounButton.set_size_request(100,30)
hbox.pack_end(nounButton,True,False)
nounButton.show()
nounButton.connect("clicked", click_handler)
familyButton = gtk.Button(label="Family")
familyButton.set_size_request(100,30)
hbox.pack_end(familyButton,True,False)
familyButton.show()
particleButton = gtk.Button(label="Particles")
hbox2.pack_end(particleButton,True,False)
particleButton.set_size_request(100,30)
particleButton.show()
adjectiveButton = gtk.Button(label="Adjectives")
adjectiveButton.set_size_request(100,30)
hbox2.pack_end(adjectiveButton,True,False)
adjectiveButton.show()
pronounButton = gtk.Button(label="Pronouns")
pronounButton.set_size_request(100,30)
hbox2.pack_end(pronounButton,True,False)
pronounButton.show()
def main():
gtk.mainloop()
main()
You forgot to call dichbox.show().
I would also recommend to restructure your code and group similar function calls, use show_all() instead of many show()s and use a class for the whole window.
That's what it would look like:
import pygtk
pygtk.require('2.0')
import gtk
from Wordlist import *
class Window(gtk.Window):
def __init__(self):
gtk.Window.__init__(self,gtk.WINDOW_TOPLEVEL)
self.set_size_request(300,400)
self.set_title("English-Japanese Reference")
self.connect("delete-event", gtk.main_quit)
verbButton = gtk.Button(label="Verbs")
nounButton = gtk.Button(label="Nouns")
nounButton.connect("clicked", self.click_handler)
familyButton = gtk.Button(label="Family")
particleButton = gtk.Button(label="Particles")
adjectiveButton = gtk.Button(label="Adjectives")
pronounButton = gtk.Button(label="Pronouns")
verbButton.set_size_request(100,30)
nounButton.set_size_request(100,30)
familyButton.set_size_request(100,30)
particleButton.set_size_request(100,30)
adjectiveButton.set_size_request(100,30)
pronounButton.set_size_request(100,30)
hbox = gtk.HBox(True,0)
hbox.pack_end(verbButton, True, False)
hbox.pack_end(nounButton, True, False)
hbox.pack_end(familyButton, True, False)
hbox2 = gtk.HBox(True,0)
hbox2.pack_end(particleButton, True, False)
hbox2.pack_end(adjectiveButton, True, False)
hbox2.pack_end(pronounButton, True, False)
label = gtk.Label("hi")
self.meaningvbox = gtk.VBox()
self.meaningvbox.pack_start(label)
wordvbox = gtk.VBox()
vsep = gtk.VSeparator()
dichbox = gtk.HBox()
dichbox.pack_start(wordvbox)
dichbox.pack_start(vsep)
dichbox.pack_start(self.meaningvbox)
vbox = gtk.VBox(False, 0)
vbox.pack_end(hbox, False)
vbox.pack_end(hbox2, False)
vbox.pack_start(dichbox)
self.add(vbox)
self.show_all()
def click_handler(self,button):
for i in nouns:
k = gtk.Label(i)
k.show()
self.meaningvbox.pack_start(k, True, True, 0)
def main():
win = Window()
gtk.main()
main()

Resources