Multiple Input Callback in Plotly Express using dcc.DatePickerRange - callback

I am using plotly express and dash to create my first live interactive dashboard. The current display is very basic just 2 graphs and a checkbox list for province. My next addition was going to be a date range picker from dash core components. However I cannot seem to integrate this piece successfully into the callback.
I also cannot seem to find any examples online of callbacks with multiple inputs that are using the date range picker.
My code is below, any suggestions or feedback is appreciated.
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.express as px
import pandas as pd
import datetime
from dash.dependencies import Input, Output
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
# assume you have a "long-form" data frame
# see https://plotly.com/python/px-arguments/ for more options
df = pd.read_csv(r'DashboardInfo.csv', header=None, names= ['ACR ID',
'Agent ID',
'Agency Code',
'Agreement ID',
'Unit Total',
'TXN Date',
'Product Code',
'Original Unit Quantity',
'Current Unit Quantity',
'Is Escalator',
'Escalator Percentage',
'Primary Sub ID',
'Sub Birthdate',
'Sub Gender',
'Residential ID',
'Province',
'City',
'Postal Code',
'Address 1',
'Address 2',
'Agent Name',
'Branch'])
today_date = datetime.datetime.today().strftime('%Y%m%d')
df['TXN Date'] = pd.to_datetime(df['TXN Date'])
print(df['TXN Date'])
#df.set_index('TXN Date',inplace=True)
print(df.dtypes)
app.layout = html.Div(children=[
html.H1(children='Sales Results Dashboard'),
html.Div(children='''
Sales Rep Production for
''' + today_date),
dcc.Graph(
id='example-graph',
),
dcc.Graph(
id='branch-graph',
),
#plan type checklist
html.Label('Checkboxes'),
dcc.Checklist(
id='Plan_Type_Checklist',
options=[
{'label': x, 'value': x, 'disabled': False}
for x in df['Province'].unique()
],
value=['BC','AB','SK','MB','ON','QC','NB','NL','PE','NS']
),
html.Label('Date Picker Range'),
dcc.DatePickerRange(
id = 'Date Picker Range',
clearable = True,
start_date=df['TXN Date'].iloc[0],
end_date=df['TXN Date'].iloc[-1]
#min_date_allowed=datetime(2018,1,1)
),
])
#app.callback([
Output(component_id = 'example-graph',component_property ='figure'),
Output(component_id = 'branch-graph',component_property ='figure')],
[Input(component_id = 'Plan_Type_Checklist', component_property = 'value'),
Input(component_id = 'Date Picker Range', component_property = 'start_date'),
Input(component_id = 'Date Picker Range', component_property = 'end_date')
])
def update_graph(options_chosen, start_date, end_date):
#options chosen links to component properter = 'value'
df_modified_chart = df[(df['TXN Date'] > start_date) & (df['TXN Date'] < end_date)(df['Province'].isin(options_chosen))].groupby(by=['Agent Name'],as_index=False)['Unit Total'].sum()#['TXN Date']
#df_modified_chart.set_index('TXN Date', inplace=True)
print(df_modified_chart.head())
print('df_modified_chart head printed above')
df_modified_chart2 = df[(df['Province'].isin(options_chosen))].groupby(by=['Branch'],as_index=False)['Unit Total'].sum().loc[start_date:end_date]
print(df_modified_chart2.dtypes)
fig = px.bar(
df_modified_chart,
x="Agent Name",
y="Unit Total",
).update_xaxes(categoryorder='total descending')
fig2 = px.bar(
df_modified_chart2,
x="Branch",
y="Unit Total"
).update_xaxes(categoryorder='total descending')
return fig, fig2
if __name__ == '__main__':
app.run_server(debug=True)

Figured out I was messing up the dataframe setup in the callback. Revised code below:
The line that was giving me trouble is below:
df_modified_chart = df[(df['TXN Date'] > start_date) & (df['TXN Date'] < end_date) & (df['Province'].isin(options_chosen))].groupby(by=['Agent Name'],as_index=False)['Unit Total'].sum()
Complete revised code below:
# -*- coding: utf-8 -*-
# Run this app with `python app.py` and
# visit http://127.0.0.1:8050/ in your web browser.
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.express as px
import pandas as pd
import datetime
from dash.dependencies import Input, Output
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
# assume you have a "long-form" data frame
# see https://plotly.com/python/px-arguments/ for more options
df = pd.read_csv(r'DashboardInfo.csv', header=None, names= ['ACR ID',
'Agent ID',
'Agency Code',
'Agreement ID',
'Unit Total',
'TXN Date',
'Product Code',
'Original Unit Quantity',
'Current Unit Quantity',
'Is Escalator',
'Escalator Percentage',
'Primary Sub ID',
'Sub Birthdate',
'Sub Gender',
'Residential ID',
'Province',
'City',
'Postal Code',
'Address 1',
'Address 2',
'Agent Name',
'Branch'])
today_date = datetime.datetime.today().strftime('%Y%m%d')
df['TXN Date'] = pd.to_datetime(df['TXN Date'])
print(df['TXN Date'])
#df.set_index('TXN Date',inplace=True)
print(df.dtypes)
app.layout = html.Div(children=[
html.H1(children='Sales Results Dashboard'),
html.Div(children='''
Sales Rep Production for
''' + today_date),
dcc.Graph(
id='example-graph',
),
dcc.Graph(
id='branch-graph',
),
#plan type checklist
html.Label('Checkboxes'),
dcc.Checklist(
id='Plan_Type_Checklist',
options=[
{'label': x, 'value': x, 'disabled': False}
for x in df['Province'].unique()
],
value=['BC','AB','SK','MB','ON','QC','NB','NL','PE','NS']
),
html.Label('Date Picker Range'),
dcc.DatePickerRange(
id = 'Date Picker Range',
clearable = True,
start_date=df['TXN Date'].iloc[0],
end_date=df['TXN Date'].iloc[-1]
#min_date_allowed=datetime(2018,1,1)
),
# Map
html.Div([
dcc.Graph(id='graph', config={'displayModeBar': False, 'scrollZoom': True},
style={'background':'#00FC87','padding-bottom':'2px','padding-left':'2px','height':'100vh'}
)
], className='nine columns'
),
])
#app.callback([
Output(component_id = 'example-graph',component_property ='figure'),
Output(component_id = 'branch-graph',component_property ='figure')],
[Input(component_id = 'Plan_Type_Checklist', component_property = 'value'),
Input(component_id = 'Date Picker Range', component_property = 'start_date'),
Input(component_id = 'Date Picker Range', component_property = 'end_date')
])
def update_graph(options_chosen, start_date, end_date):
#options chosen links to component properter = 'value'
df_modified_chart = df[(df['TXN Date'] > start_date) & (df['TXN Date'] < end_date) & (df['Province'].isin(options_chosen))].groupby(by=['Agent Name'],as_index=False)['Unit Total'].sum()#['TXN Date']
#df_modified_chart.set_index('TXN Date', inplace=True)
print(df_modified_chart.head())
print('df_modified_chart head printed above')
df_modified_chart2 = df[(df['Province'].isin(options_chosen))].groupby(by=['Branch'],as_index=False)['Unit Total'].sum().loc[start_date:end_date]
print(df_modified_chart2.dtypes)
fig = px.bar(
df_modified_chart,
x="Agent Name",
y="Unit Total",
).update_xaxes(categoryorder='total descending')
fig2 = px.bar(
df_modified_chart2,
x="Branch",
y="Unit Total"
).update_xaxes(categoryorder='total descending')
return fig, fig2
if __name__ == '__main__':
app.run_server(debug=True)

Related

I am using pdf lib to generate pdf and want put a dyanamic table in flutter

I am trying to add a dynamic table with a loop in pdf, but it is not working.
pdfLib.Table.fromTextArray(
context: context,
data: <List<String>>[
<String>[
'#',
'Product Name',
'HSN',
'Qty',
'Unit Price',
'MRP',
'Disc%',
'Disc Amnt',
'Taxable Amnt',
'SGST%',
'SGST Amnt',
'CGST%',
'CGST Amnt',
'Net Amnt'
],
_list(),
],
),
_list here is a function which returns list of strings but it is only able to add one row in table,
for (var i = 0; i < _items.length; i++) {
return <String>[
(i + 1).toString(),
_items[i].title,
'HSN',
_items[i].quantity.toString(),
_items[i].price.toString(),
_items[i].mrp.toString(),
_items[i].discount.toString(),
_item[i].gst,
_item[i].amount
_item[i].sGst,
_item[i].someitem,
_item[i].cGst,
_items[i].price,
_items[i].quantity];
}
Can someone please help me with this?
Thanks
_list needs to return a List<List<String>> as it need to return multiple string lists - one for each item. It can be written with List.map() like:
List<List<String>> _list() {
return _items
.map((item) => <String>[
item.title,
'HSN',
item.quantity.toString(),
// etc
])
.toList();
}
which maps each item into a string list, and returns the list of lists.
You need to change how you use that to use a spread operator ... so that the list of items is expanded into the overall list, like this:
var data = <List<String>>[
<String>[
'#',
'Product Name',
'HSN',
'Qty',
'Unit Price',
'MRP',
'Disc%',
'Disc Amnt',
'Taxable Amnt',
'SGST%',
'SGST Amnt',
'CGST%',
'CGST Amnt',
'Net Amnt'
],
..._list(),
];
}
Or, you could inline the whole operation with the for operator:
var data = <List<String>>[
<String>[
'#',
'Product Name',
'HSN',
'Qty',
'Unit Price',
'MRP',
'Disc%',
'Disc Amnt',
'Taxable Amnt',
'SGST%',
'SGST Amnt',
'CGST%',
'CGST Amnt',
'Net Amnt'
],
for (var item in _items)
<String>[
item.title,
'HSN',
item.quantity.toString(),
// etc
],
];
}
There are several ways to do it, I prefer to fill the List separately, like:
`List<List<String>> salidas = new List();
salidas.add(<String>['Title1','Title2', ... , 'Title n']);
for(var indice=0;indice<records.length;indice++) {
var recind = {
'field1': records[indice].Stringfield1,
'field2': records[indice].Stringfield2,
...
'fieldn': records[indice].Stringfieldn
};
salidas.add(recind);
}
...
fpdf.Table.fromTextArray(context: context,data: salidas),
`
// Generate Dynamic PDF
_generatePdfAndView(context) async {
final pw.Document pdf = pw.Document(deflate: zlib.encode);
pdf.addPage(
pw.MultiPage(
build: (context) => [
pw.Table.fromTextArray(
context: context,
data: <List<String>>[
// These will be your columns as Parameter X, Parameter Y etc.
<String>[
'Parameter',
'Price',
],
for (int i = 0; i < featureNames.length; i++)
<String>[
// ith element will go in ith column means
// featureNames[i] in 1st column
featureNames[i],
// featureValues[i] in 2nd column
featureValues[i].toString(),
],
],
),
],
),
);
}
Hope that will work for you.

Getting unnecessary stop words from text in matlab?

stopwords_cellstring={'a','s', 'about', 'above', 'above', 'across', 'after', ...
'afterwards', 'again', 'against', 'all', 'almost', 'alone', 'along', ...
'already', 'also','although','always','am','among', 'amongst', 'amoungst', ...
'amount', 'an', 'and', 'another', 'any','anyhow','anyone','anything','anyway', ...
'anywhere', 'are', 'around', 'as', 'at', 'back','be','became', 'because','become',...
'becomes', 'becoming', 'been', 'before', 'beforehand', 'behind', 'being', 'below',...
'beside', 'besides', 'between', 'beyond', 'bill','all','When', 'both', 'bottom','but', 'by',...
'call', 'can', 'cannot', 'cant', 'co', 'con', 'could', 'couldnt', 'cry', 'de',...
'describe', 'detail', 'do', 'done', 'down', 'due', 'during', 'each', 'eg', 'eight',...
'either', 'eleven','else', 'elsewhere', 'empty', 'enough', 'etc', 'even', 'ever', ...
'every', 'everyone', 'everything', 'everywhere', 'except', 'few', 'fifteen', 'fify',...
'fill', 'find', 'fire', 'first', 'five', 'for', 'former', 'formerly', 'forty', 'found',...
'four', 'from', 'front', 'full', 'further', 'get', 'give', 'go', 'had', 'has', 'hasnt',...
'have', 'he', 'hence', 'her', 'here', 'hereafter', 'hereby', 'herein', 'hereupon', ...
'hers', 'herself', 'him', 'himself', 'his', 'how', 'however', 'hundred', 'ie', 'if',...
'in', 'inc', 'indeed', 'interest', 'into', 'is', 'it', 'its', 'itself', 'keep', 'last',...
'latter', 'latterly', 'least', 'less', 'ltd', 'made', 'many', 'may', 'me', 'meanwhile',...
'might', 'mill', 'mine', 'more', 'moreover', 'most', 'mostly', 'move', 'much', 'must',...
'my', 'myself', 'name', 'namely', 'neither', 'never', 'nevertheless', 'next', 'nine',...
'no', 'nobody', 'none', 'noone', 'nor', 'not', 'nothing', 'now', 'nowhere', 'of', 'off',...
'often', 'on', 'once', 'one', 'only', 'onto', 'or', 'other', 'others', 'otherwise',...
'our', 'ours', 'ourselves', 'out', 'over', 'own','part', 'per', 'perhaps', 'please',...
'put', 'rather', 're', 'same', 'see', 'seem', 'seemed', 'seeming', 'seems', 'serious',...
'several', 'she', 'should', 'show', 'side', 'since', 'sincere', 'six', 'sixty', 'so',...
'some', 'somehow', 'someone', 'something', 'sometime', 'sometimes', 'somewhere', ...
'still', 'such', 'system', 'take', 'ten', 'than', 'that', 'the', 'their', 'them',...
'themselves', 'then', 'thence', 'there', 'thereafter', 'thereby', 'therefore', ...
'therein', 'thereupon', 'these', 'they', 'thickv', 'thin', 'third', 'this', 'those',...
'though', 'three', 'through', 'throughout', 'thru', 'thus', 'to', 'together', 'too',...
'top', 'toward', 'towards', 'twelve', 'twenty', 'two', 'un', 'under', 'until', 'up',...
'upon', 'us', 'very', 'via', 'was', 'we','all', 'well', 'were','uses','way','went', 'what', 'whatever', 'when',...
'whence', 'whenever', 'where', 'whereafter', 'whereas', 'whereby', 'wherein',...
'whereupon', 'wherever', 'whether', 'which', 'while', 'whither', 'who', 'whoever',...
'whole','When', 'whom', 'whose','saw', 'why', 'will', 'with', 'within', 'without', 'would', 'yet',...
'you', 'your', 'yours', 'yourself', 'yourselves', 'the'};
above are the stop words that i am using to process a text file and removing them but there are some words which are not still eliminated listed as follows:
[3] 'The'
[6] 'â'
[5] 's'
can anyone help me how to eliminate these words the code i'm using is as follows
str1 = F
split1 = regexp(str1,'\s','Split');
out_str1 = strjoin(split1(~ismember(split1,stopwords_cellstring)),' ')
C = regexp(out_str1, '<s>|\w*|</s>', 'match');
Just concentrating on word filtering and if willing to be case insensitive, using ~ismember will not work. Here is a solution to filter stopwords while being not case sensitive:
str1 = F
split1 = regexp(str1,'\s','Split');
%%%%
logic = arrayfun(#(word)any(strcmpi(word, stopwords_cellstring)), split1);
out_str1 = strjoin(split1(~logic), ' ');
%%%%
C = regexp(out_str1, '<s>|\w*|</s>', 'match');
How it works:
I have replaced ismember test with arrayfun. For each word in split1, the arrayfun checks if this word match any of the words in stopwords_cellstring using strcmpi (case insensitive).
NB1: For s it is not part of your stop list.
NB2: For â, I don't know if there's a quick solution to convert it to a (i.e without accentuation) ... easy solution would be to add it to your list unless it is included in more complex word like âmer for instance ... in this last case I would advice you to prefilter str1 with str1 = strrep(str1, 'â', 'a').

CKEditor Link dialog modification

I am trying to add a drop down to CKEditor's link dialog. When selected, the drop down should insert corresponding class name to the link.
CKEDITOR.on( 'dialogDefinition', function( ev ) {
var dialogName = ev.data.name;
var dialogDefinition = ev.data.definition;
if ( dialogName == 'link' ) {
var infoTab = dialogDefinition.getContents( 'info' );
infoTab.add({
type: 'select',
label: 'Display link as a button',
id: 'buttonType',
'default': '',
items: [
['- Not button -', ''],
['Button one', 'btn-primary'],
['Button two', 'btn-success'],
['Button three', 'btn-danger']
],
commit: function(data) {
data.className = this.getValue();
}
});
}
});
I have a feeling commit function is not doing the job, but cannot figure out how to make it work. I saw a code that almost does the same thing as I want at http://www.lxg.de/code/simplify-ckeditors-link-dialog. I tried it and it does not work either.
I am using CKEditor 4.3.2.
I appreciate your help in advance.
If you console.log the data object in link dialog's onOk, you'll find quite a different hierarchy. Element classes are in data.advanced.advCSSClasses. But even if you decide to override (or extend) the value of this property in your commit, your string will be nuked by the original commit of advCSSClasses input field ("Advanced" tab) anyway. So the approach got to be a little bit different:
Always store the value of the select in data.
Override commit of advCSSClasses input field to consider stored value.
Remember to execute the original commit of advCSSClasses input.
Here we go:
CKEDITOR.on( 'dialogDefinition', function( ev ) {
var dialogName = ev.data.name;
var dialogDefinition = ev.data.definition;
if ( dialogName == 'link' ) {
var infoTab = dialogDefinition.getContents( 'info' ),
advTab = dialogDefinition.getContents( 'advanced' ),
advCSSClasses = advTab.get( 'advCSSClasses' );
infoTab.add( {
type: 'select',
label: 'Display link as a button',
id: 'buttonType',
'default': '',
items: [
['- Not button -', ''],
['Button one', 'btn-primary'],
['Button two', 'btn-success'],
['Button three', 'btn-danger']
],
commit: function( data ) {
data.buttonType = this.getValue();
}
});
var orgAdvCSSClassesCommit = advCSSClasses.commit;
advCSSClasses.commit = function( data ) {
orgAdvCSSClassesCommit.apply( this, arguments );
if ( data.buttonType && data.advanced.advCSSClasses.indexOf( data.buttonType ) == -1 )
data.advanced.advCSSClasses += ' ' + data.buttonType;
};
}
});
Now you got to only write a setup function which will detect whether one of your button classes is present to set a proper value of your select field once the dialog is open.

Zend_Db - union

I have code:
$balanceModelCredit = new Model_BalanceCredit();
$balanceModelDebt = new Model_BalanceDebt();
$selectQueryDebt = $balanceModelDebt->select()
->from('balance_debt', array('date',
'amount',
'description',
new Zend_Db_Expr('"koszta"')
));
$selectQueryDebt->where('balance_id=?', $balance_id);
$selectQueryCredit = $balanceModelCredit->select()
->from('balance_credit', array('date',
'amount',
'description',
new Zend_Db_Expr('"przychod"')
));
$selectQueryCredit->where('balance_id=?', $balance_id);
How can I do UNION statement?
You only need to do :
$selectQueryCredit->where('balance_id = ?', $balance_id);
$selectQueryCredit->union(array($selectQueryDebt));
Hope it helps.

Removing stop words from single string

My query is string = 'Alligator in water' where in is a stop word. How can I remove it so that I get stop_remove = 'Alligator water' as output. I have tried it with ismember but it returns integer value for matching word, I want to get the remaining words as output.
in is just an example, I'd like to remove all possible stop words.
A slightly more elegant way than Luis Mendo's solution is to use regexprep that does exactly what you want
>> result = regexprep( 'Alligator in water', 'in\s*', '' ); % replace with an empty string
result =
Alligator water
If you have several stop words you can simply add them to the pattern (in this example I consider 'in' and 'near' as stop words):
>> result = regexprep( 'Alligator in water near land', {'in\s*','near\s*'}, '' )
result =
Alligator water land
Use this for removing all stop-words.
Code
% Source of stopwords- http://norm.al/2009/04/14/list-of-english-stop-words/
stopwords_cellstring={'a', 'about', 'above', 'above', 'across', 'after', ...
'afterwards', 'again', 'against', 'all', 'almost', 'alone', 'along', ...
'already', 'also','although','always','am','among', 'amongst', 'amoungst', ...
'amount', 'an', 'and', 'another', 'any','anyhow','anyone','anything','anyway', ...
'anywhere', 'are', 'around', 'as', 'at', 'back','be','became', 'because','become',...
'becomes', 'becoming', 'been', 'before', 'beforehand', 'behind', 'being', 'below',...
'beside', 'besides', 'between', 'beyond', 'bill', 'both', 'bottom','but', 'by',...
'call', 'can', 'cannot', 'cant', 'co', 'con', 'could', 'couldnt', 'cry', 'de',...
'describe', 'detail', 'do', 'done', 'down', 'due', 'during', 'each', 'eg', 'eight',...
'either', 'eleven','else', 'elsewhere', 'empty', 'enough', 'etc', 'even', 'ever', ...
'every', 'everyone', 'everything', 'everywhere', 'except', 'few', 'fifteen', 'fify',...
'fill', 'find', 'fire', 'first', 'five', 'for', 'former', 'formerly', 'forty', 'found',...
'four', 'from', 'front', 'full', 'further', 'get', 'give', 'go', 'had', 'has', 'hasnt',...
'have', 'he', 'hence', 'her', 'here', 'hereafter', 'hereby', 'herein', 'hereupon', ...
'hers', 'herself', 'him', 'himself', 'his', 'how', 'however', 'hundred', 'ie', 'if',...
'in', 'inc', 'indeed', 'interest', 'into', 'is', 'it', 'its', 'itself', 'keep', 'last',...
'latter', 'latterly', 'least', 'less', 'ltd', 'made', 'many', 'may', 'me', 'meanwhile',...
'might', 'mill', 'mine', 'more', 'moreover', 'most', 'mostly', 'move', 'much', 'must',...
'my', 'myself', 'name', 'namely', 'neither', 'never', 'nevertheless', 'next', 'nine',...
'no', 'nobody', 'none', 'noone', 'nor', 'not', 'nothing', 'now', 'nowhere', 'of', 'off',...
'often', 'on', 'once', 'one', 'only', 'onto', 'or', 'other', 'others', 'otherwise',...
'our', 'ours', 'ourselves', 'out', 'over', 'own','part', 'per', 'perhaps', 'please',...
'put', 'rather', 're', 'same', 'see', 'seem', 'seemed', 'seeming', 'seems', 'serious',...
'several', 'she', 'should', 'show', 'side', 'since', 'sincere', 'six', 'sixty', 'so',...
'some', 'somehow', 'someone', 'something', 'sometime', 'sometimes', 'somewhere', ...
'still', 'such', 'system', 'take', 'ten', 'than', 'that', 'the', 'their', 'them',...
'themselves', 'then', 'thence', 'there', 'thereafter', 'thereby', 'therefore', ...
'therein', 'thereupon', 'these', 'they', 'thickv', 'thin', 'third', 'this', 'those',...
'though', 'three', 'through', 'throughout', 'thru', 'thus', 'to', 'together', 'too',...
'top', 'toward', 'towards', 'twelve', 'twenty', 'two', 'un', 'under', 'until', 'up',...
'upon', 'us', 'very', 'via', 'was', 'we', 'well', 'were', 'what', 'whatever', 'when',...
'whence', 'whenever', 'where', 'whereafter', 'whereas', 'whereby', 'wherein',...
'whereupon', 'wherever', 'whether', 'which', 'while', 'whither', 'who', 'whoever',...
'whole', 'whom', 'whose', 'why', 'will', 'with', 'within', 'without', 'would', 'yet',...
'you', 'your', 'yours', 'yourself', 'yourselves', 'the'};
str1 = 'Alligator in water of the pool'
split1 = regexp(str1,'\s','Split');
out_str1 = strjoin(split1(~ismember(split1,stopwords_cellstring)),' ')
Output
str1 =
Alligator in water of the pool
out_str1 =
Alligator water pool
NOTE: This code uses strjoin from Mathworks File-exchange.
Use regexp:
string = 'Alligator in water'; %// data string
result = regexp(string, 'in\s*', 'split'); %// split according to stop word
result = [result{:}]; %// join remaining pieces