Exemple #1
0
def send_data_to_teacher():
    top_data = maximum()
    bottom_data = minimum()
    output1 = build_table(top_data, 'blue_light')
    output2 = build_table(bottom_data, 'blue_light')
    send_mail(output1, output2)

    return "Mail sent successfully."
Exemple #2
0
def relatorio_html(ir):
    relatorio = '<html>'
    relatorio += __h1('RELATORIO')
    relatorio += __p('')
    relatorio += __h2('Custódia')
    custodia = calcula_custodia(ir.df, datetime.datetime.now().date())
    custodia = custodia[custodia.valor > 0]
    total_na_carteira = custodia['valor'].sum()
    custodia['valorizacao'] = custodia.apply(lambda row: '{:.2f}'.format(float(row.valorizacao)), axis=1)
    custodia['valor'] = custodia.apply(lambda row: '{:.2f}'.format(row.valor), axis=1)
    custodia['preco_atual'] = custodia.apply(lambda row: '{:.2f}'.format(row.preco_atual), axis=1)
    custodia['preco_medio_compra'] = custodia.apply(lambda row: '{:.2f}'.format(row.preco_medio_compra), axis=1)
    custodia['ultimo_yield'] = custodia.apply(lambda row: '' if row.ultimo_yield is None else '{:.2f}'.format(row.ultimo_yield), axis=1)
    headers = ['ticker', 'qtd', 'valor (R$)', 'Preco Atual (R$)', 'Preco Medio Compra (R$)', 'valorizacao (%)', 'Ultimo Yield [%]', 'tipo', 'Dt.Compra']
    columns = ['ticker', 'qtd', 'valor', 'preco_atual', 'preco_medio_compra', 'valorizacao', 'ultimo_yield', 'tipo', 'data_primeira_compra']
    custodia = custodia[columns]
    custodia.columns = headers
    relatorio += build_table(custodia, __cor_tabela())
    relatorio += __p('Total na carteira : ' + __format(total_na_carteira))
    relatorio += __hr()

    for data in ir.datas:
        if ir.possui_vendas_no_mes(data):

            relatorio += __p('')
            relatorio += __h3('MES : ' + str(data.month) + '/' + str(data.year))
            relatorio += __p('Vendas:', tab=1)

            vendas_no_mes_por_tipo = ir.get_vendas_no_mes_por_tipo(data)
            for tipo in TipoTicker:
                if len(vendas_no_mes_por_tipo[tipo]):
                    relatorio += __p(tipo.name + ':', tab=2)
                    df_mes_por_tipo = pd.DataFrame(columns=['ticker', 'Qtd Vendida [#]', 'Preco Médio de Compra [R$]', 'Preco Médio de Venda [R$]', 'Resultado Apurado [R$]'])

                    for venda in vendas_no_mes_por_tipo[tipo]:
                        df_mes_por_tipo.loc[len(df_mes_por_tipo)] = [venda['ticker'],
                                                                     str(int(venda['qtd_vendida'])),
                                                                     __format(venda['preco_medio_compra']),
                                                                     __format(venda['preco_medio_venda']),
                                                                     __format(venda['resultado_apurado'])]

                    relatorio += __p(build_table(df_mes_por_tipo, __cor_tabela(tipo)), tab=3)
                    relatorio += __p('Lucro/Prejuizo no mês: ' + __format(ir.calcula_prejuizo_por_tipo(data, tipo)), tab=3)
                    relatorio += __p('Lucro/Prejuizo acumulado: ' + __format(ir.calcula_prejuizo_acumulado(data, tipo)), tab=3)
                    relatorio += __p('IR no mês para ' + tipo.name + ': ' + __format(ir.calcula_ir_a_pagar(ir.calcula_prejuizo_acumulado(data, tipo), tipo)), tab=3)

            relatorio += __p('Dedo-Duro TOTAL no mês: ' + __format(ir.calcula_dedo_duro_no_mes(data)), tab=2)
            relatorio += __p('IR a pagar TOTAL no mês: ' + __format(ir.calcula_ir_a_pagar_no_mes(data)), tab=2)
            relatorio += __hr()

    relatorio += __close_html()
    return ''.join(relatorio)
def overview():
    # Create summary ---
    URLstats = URL + 'dailystats.csv'
    URLcurr = URL + 'currency_output.csv'
    URLpred = URL + 'usdtwd_prediction.csv'

    # Table daily stats usdtwd_prediction
    df = pd.read_csv(URLstats)
    yesterday = date.today() - timedelta(
        days=2
    )  # most recent set to 2 previous days from today to ensure values.
    pd.set_option('display.float_format', '{0:,.0f}'.format)
    df = df[(df['date'] == yesterday.strftime("%Y-%m-%d"))].sort_values(
        by='total_deaths', ascending=False).head(6)
    day_before_data = df[[
        'location', 'new_cases', 'new_deaths', 'total_cases', 'total_deaths'
    ]].round(0)

    # Using pretty_html_table library to ease conversion from pandas to html table
    table1 = build_table(day_before_data,
                         'blue_light',
                         font_family='Proxima Nova',
                         font_size='small')

    # Table currency
    pd.set_option('display.float_format', '{0:,.4}'.format)
    dfc = pd.read_csv(URLcurr).head(4).iloc[:, 1:7]
    table2 = build_table(dfc,
                         'blue_light',
                         font_family='Proxima Nova',
                         font_size='small')

    # Table prediction
    dft = pd.read_csv(URLpred)
    dft['date'] = pd.to_datetime(dft.date)
    dft.sort_values(by=['date'], inplace=True, ascending=False)
    dft = dft.head(4)
    table3 = build_table(dft,
                         'blue_light',
                         font_family='Proxima Nova',
                         font_size='small')

    tables = [table1, table2, table3]
    date_output = date.today().strftime('%B %d')
    notify_details = "There's a preview of the data updated to S3 on %s \n Datasets are available here:\n - Main covid stats: %s\n - USD/TWD currency values: %s\n - Caculated values for the prediction %s" % (
        date_output, URLstats, URLcurr, URLpred)

    return (tables, notify_details)
Exemple #4
0
   def adiciona_tabela(self, tabela, tab=0):
        #TODO: Precisa alinhar corretamente pela direita as colunas numéricas e esquerda as restantes
        # Deixando tudo na direita pelo menos fica mais facil de ver os números

       # Para não truncar as colunas
        with pd.option_context('display.max_colwidth', -1): 
           self.p(build_table(tabela, cor_tabela(), text_align='right'), tab=tab)
def sendEmailNotification(df):
    # https://www.google.com/settings/security/lesssecureapps
    user = decode(dict(configReader(GMAIL))['user'])
    password = decode(dict(configReader(GMAIL))['password'])
    sender = decode(dict(configReader(GMAIL))['user'])
    recipients = decode(dict(configReader(GMAIL))['user'])
    smtpServer = dict(configReader(GMAIL))['smtpserver']
    port = int(dict(configReader(GMAIL))['port'])

    msg = MIMEMultipart()
    msg['Subject'] = "Trading-Report-" + datetime.datetime.now().strftime("%d %B %I:%M")
    msg['From'] = sender
    msg['To'] = recipients

    body_content = build_table(df, 'grey_dark')
    msg.attach(MIMEText(body_content, "html"))
    msg_body = msg.as_string()
    context = ssl.create_default_context()
    try:
        server = smtplib.SMTP(smtpServer, port)
        server.set_debuglevel(0)
        server.ehlo()
        server.starttls(context=context)
        server.ehlo()
        server.login(user, password)
        server.sendmail(msg['From'], msg['To'], msg_body)
        server.quit()
        log.info("Mail Sent...")
    except smtplib.SMTPException as err:
        log.exception(err)
Exemple #6
0
def factor_sensitivity(factor_selection):
    if (not factor_selection):
        ret=df['Daily_Returns'].sum().round(decimals=1)
        data = {'Factors':['Alpha'], 'Coefficient':[ret/ndays]}
        coeff_df = pd.DataFrame(data)
        return build_table(coeff_df, 'blue_dark')
    ###### Doing a linear regression on factor_variables and daily returns on the entire period
    X = df[factor_selection].values
    Y = (df['Daily_Returns']-df[factor_riskfree[0]]).values # Calculating Excess Daily returns by subtracting Risk free returns
    dates = df['Date'].values
    regressor = LinearRegression().fit(X, Y)

    ###### Constructing dataframe of Alphas and Betas - Sensitivity Analysis
    results = np.append(regressor.coef_,regressor.intercept_)
    coeff_df = pd.DataFrame(results.round(decimals=2), columns=['Coefficient'])
    coeff_df.insert(loc=0, column='Factors', value=factor_selection+['Alpha'])
    return build_table(coeff_df, 'blue_dark')
 def email_callback(df):
     df = pd.read_csv(io.StringIO(df))
     files = glob.glob("figures/*.png")
     content = build_table(df, 'blue_light')
     send_email(to=["*****@*****.**"],
                subject='Report',
                html_content=content,
                files=files)
def send_PL_update():
    df = create_player_standings()
    output = build_table(df,
                         'red_light',
                         font_size='large',
                         font_family='Times new Roman',
                         text_align='left')
    send_mail(output)
Exemple #9
0
def query(input):
    airquality_results = sparql_queries.get_airquality(input)
    airquality_plots = sparql_queries.build_airquality_graphs(airquality_results)
    # facility_results = sparql_queries.get_environmental_facilities(input)
    openei_organization_results = sparql_queries.run_clean_energy_company_by_country(input)
    openei_tools_by_country_results = sparql_queries.run_tools_by_country(input)
    openei_policy_by_country = sparql_queries.run_policy_by_country(input)

    return render_template('results.html', graphs=airquality_plots,
                           tables=[HTML(build_table(airquality_results, 'blue_dark')),
                                   # HTML(build_table(facility_results, 'blue_dark')),
                                   HTML(build_table(openei_organization_results, 'blue_dark')),
                                   HTML(build_table(openei_tools_by_country_results, 'blue_dark')),
                                   HTML(build_table(openei_policy_by_country, 'blue_dark'))],
                           # TRY HTML(build_table(openei_policy_by_country, 'blue_dark').to_html(escape=False))],
                           # HTML(pandas_.to_html(escape=False))
                           titles=["Airquality results in " + input,
                                   # facility_results.columns.values,
                                   # openei_organization_results.columns.values,
                                   "Tools by Country results in " + input,
                                   "Policy by Country results in " + input])
Exemple #10
0
def send_email():
    data = build_table(new_df
                        , 'green_dark'
                        , font_size='medium'
                        , font_family='Open Sans,sans-serif'
                        , text_align='left'
                        , width='auto'
                        , index=False
			, even_color='black'
			, even_bg_color='white'
                        )
    send_mail(data)
    return print('Email was sent succesfully')
def index():
    if request.method == 'POST':
        search_string = request.form['content'].replace(" ", "")
        content = company_financials(search_string)
        table = build_table(content,
                            'blue_light',
                            font_size='small',
                            font_family='Lucida Grande',
                            text_align='right')
        financials = BeautifulSoup(table, 'html.parser')
        return render_template('main.html',
                               tables=financials,
                               company=search_string.upper())
    else:
        return render_template('index.html')
Exemple #12
0
def LinkeDary(fbusername, fbpw, fb_url, max_iteration, liusername, lipw,
              first_row, last_row, text_whith_company, text_whithout_company,
              dryrun, min_wait, max_wait):
    browser, df = prepare_data(fbusername, fbpw, fb_url, max_iteration,
                               text_whith_company, text_whithout_company)
    if isinstance(df, str):
        return "NO Name Found"
    else:
        browser.execute_script("window.open('','_blank');")
        browser.switch_to.window(browser.window_handles[-1])
        browser.get('https://www.linkedin.com/')
        browser.switch_to.window(browser.current_window_handle)
        browser.execute_script(
            f"document.getElementById('session_key').value='{liusername}'")
        browser.execute_script(
            f"document.getElementById('session_password').value='{lipw}'")
        login_button = browser.find_element_by_class_name(
            "sign-in-form__submit-button")
        move_and_click(browser, login_button)
        if last_row >= df.size:
            if first_row >= df.size:
                first_row = df.size - 2
            last_row = df.size - 1
        for index, row in df[first_row:last_row].iterrows():
            check_link(browser, df, index, row, "link", dryrun, min_wait,
                       max_wait)
        result_html = "<h1>Summary:</h1>"
        result_html += build_table(
            df[first_row:last_row]["result"].apply(
                lambda x: x if x == "Not Found" else x[0]).value_counts().
            to_frame().reset_index(), 'orange_light')
        result_html += "<h1>Details:</h1>"
        result_html += build_table(
            df[first_row:last_row][["name", "result", "message"]],
            'orange_light')
        return result_html
Exemple #13
0
def get_html_df(df, df_title):
    url_columns = [c for c in df.columns if 'url' in c]
    df['links'] = df.apply(lambda x: ', '.join([add_url_tags(x[c]) for c in url_columns]), axis=1)
    df = df.drop(columns=url_columns)
    def trunc(txt):
        return txt[:15] + '..' if len(txt) > 15 else txt
    df['address'] = df.apply(lambda x: trunc(x.address), axis=1)

    theme = 'red_dark'
    html_table = build_table(df, color=theme, font_size='small')
    html_table = html_table.replace("URLSTART", "<a href=\"")
    html_table = html_table.replace("URLMID", "\">")
    html_table = html_table.replace("URLEND", "</a>")
    title_txt = f'<b>{df_title}</b><br>'
    return title_txt + html_table
Exemple #14
0
def main():
    company = 'Champion'
    c_hour = str(datetime.now().strftime("%H"))
    date = datetime.now().strftime("%d-%m-%Y %H")
    date = str(date) + 'hrs'

    temp = create_xls(date, company)
    output = build_table(temp, 'blue_light')
    time.sleep(5)
    a = send_email(c_hour, date, company, output)

    if a == 1:
        log.insert_log('OK', 'Correo enviado')
    else:
        log.insert_log('ERROR', 'Correo no enviado')
Exemple #15
0
def send_mail(email_content):
    output = build_table(email_content, 'blue_light')  # Format of the email
    body = output.replace('&lt;', '<').replace('&gt;', '>')

    # Content of the email
    message = MIMEMultipart()
    message['Subject'] = 'Seguimiento subastas'
    message['From'] = SENDING_EMAIL
    message['To'] = TO_EMAILS
    body_content = body
    message.attach(MIMEText(body_content, "html"))
    msg_body = message.as_string()

    # Server setup
    server = SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.login(message['From'], PASSWORD)
    server.sendmail(message['From'], message['To'], msg_body)
    server.quit()
def calc_metrics_func():
    files = os.listdir(app.config['UPLOAD_PATH'])
    sorted(filter(os.path.isfile, files), key=os.path.getmtime)
    metrics = []
    if len(files) != 2:
        abort(400)
    for f in files:
        #первым брать с меньшей датой записи и относительно него сравнивать
        file_ext = os.path.splitext(f)[1]
        if file_ext not in app.config['UPLOAD_EXTENSIONS']:
            abort(400)
    f1_name = os.path.join(app.config['UPLOAD_PATH'], files[0])
    f2_name = os.path.join(app.config['UPLOAD_PATH'], files[1])
    get_metrics(f1_name, f2_name)
    filename = 'metrics_res.csv'
    data = pd.read_csv(filename)
    metrics = data.values.tolist()
    html_table = pretty_html_table.build_table(data, 'blue_light')
    return html_table
Exemple #17
0
def main():
    result = []
    nombre = 'nada'
    url = 'https://www.sistemax.cl'
    # Se entrega el agente de browser o entrega error de acceso.
    headers = {
        'User-Agent':
        'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'
    }
    # Se hace un request a la página y queda todo almacenado en la variable.
    page_response = requests.get(url, headers=headers, timeout=30)

    # Se parsea el texto a html.
    soup = BeautifulSoup(page_response.content, "html.parser")
    content = soup.find_all("div", {"id": "content"})

    for i in content:
        items = i.find_all("div", {"class": "caption"})

        for a in items:
            #print(a)
            nombre = a.find('h4').text
            precio = a.find('span', {'class': 'price-new'}).text

            if "3060" in nombre or "3070" in nombre:
                info = {'nombre': nombre, 'precio': precio}
                result.append(info)
            else:
                continue

    df = pd.DataFrame(result)
    if len(df) > 0:
        output = build_table(df, 'blue_light')
        company = 'Sistemax'
        c_hour = str(datetime.now().strftime("%H"))
        date = datetime.now().strftime("%d-%m-%Y %H")
        date = str(date) + 'hrs'

        send_email(c_hour, date, company, output)
    else:
        pass

    return
Exemple #18
0
def getStatus():
	global Send_Email
	global Location
	global Data
	global Position
	with open(Location) as fh:
		fh.seek(Position)
		lines = fh.readlines()
		Position = fh.tell()
	temp_count = len(lines)
	for l in lines:
		z = re.match(exp, l)
		if XSS_check(z[6]):
			x = 'XSS'
		elif SQLi_check(z[6]):
			x = 'SQLi'
		elif PT_check(z[6]):
			x = 'PT'
		elif OS_check(z[6]):
			x = 'OS'
		elif CRLFi_check(z[6]):
			x = 'CRLFi'
		elif SSI_check(z[6]):
			x = 'SSI'
		elif LDAPi_check(z[6]):
			x = 'LDAPi'
		elif XPath_check(z[6]):
			x = 'XPath'
		elif Anomaly_check(z[6]):
			x = 'Anomaly'
		else:
			x = 'Normal'
		Data.append([z[1],z[4],z[5],z[6],z[8],x])
	df = pd.DataFrame(Data, columns=['IP Address', 'Timestamp', 'Method','Request Vector','Response Code','Type'])
	if Send_Email == 1:
		notDB = df.tail(temp_count)
		notDB = notDB[notDB['Type'] != 'Normal']
		if not notDB.empty:
			output = build_table(notDB, 'blue_light')
			sendmail(output)
	return df.to_html()
Exemple #19
0
def send_mail(df, newbies):
    email_content = prepare_email(df, newbies)
    output = build_table(email_content, 'blue_light')  # Format of the email
    body = output.replace('&lt;', '<').replace('&gt;', '>')

    # Content of the email
    message = MIMEMultipart()
    hoy = pd.to_datetime(date.today(), format='%Y-%m-%d')
    hoy = hoy.strftime('%d-%m-%Y')
    message['Subject'] = 'Subastas BOE del ' + str(hoy)
    message['From'] = SENDING_EMAIL
    message['To'] = TO_EMAILS
    body_content = body
    message.attach(MIMEText(body_content, "html"))
    msg_body = message.as_string()

    # Server setup
    server = SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.login(message['From'], PASSWORD)
    server.sendmail(message['From'], message['To'], msg_body)
    server.quit()
Exemple #20
0
    def export_report(self, routine, time, curr_temps, target_temps):
        if self.report_status:
            data = {
                "Target temperature (°C)": [],
                "Start time": [],
                "End time": [],
                "Duration (s)": [],
                "Transition time (s)": []
            }

            for i in routine:
                data["Target temperature (°C)"].append(i["temperature"])
                data["Start time"].append(i["start_time"])
                data["End time"].append(i["end_time"])
                data["Transition time (s)"].append(
                    round(i["transition_time"], 1))
                data["Duration (s)"].append(round(i["duration"], 1))

            df = pd.DataFrame(data)
            html_pretty = build_table(df, color='green_dark')
            f = open(f"{self.export_path}/{self.report_file_name}", "w")
            f.write(html_pretty)
            f.close()
    def run(self, dispatcher, tracker, domain):
        # config = {"user_key": "f4924dc9ad672ee8c4f8c84743301af5"}

        loc = tracker.get_slot('location')
        cuisine = tracker.get_slot('cuisine')
        budget = tracker.get_slot('budget')
        search_validity = "valid"
        print("Location : {} || Cuisine : {} || Budget : {}".format(
            loc, cuisine, budget))
        search_results = self.get_restuarant(loc, cuisine, budget)
        print("Results Shape after Buget Filtering : {}".format(
            search_results.shape[0]))
        search_results = search_results.head(10)

        if search_results.shape[0] > 0:
            response = 'Showing you top results:' + "\n"
            for index, row in search_results.iterrows():
                response = response + str(
                    row['restaurant_name']) + ' in ' + row[
                        'restaurant_address'] + ' has been rated ' + row[
                            'restaurant_rating'] + "\n"

            dispatcher.utter_message("-----" + response)
            response = build_table(search_results, 'blue_light')
            response = "Here are your search results ! Enjoy Eating :) \n" + response
            # response = ""  # For creating stories lets keep message empty

        else:
            response = "Sorry No Resturants Found !!"
            search_validity = "invalid"
            dispatcher.utter_message("-----" + response)

        # response_body = build_table(search_results, 'blue_light')
        return [
            SlotSet("check_search_validity", search_validity),
            SlotSet("email_message", response)
        ]
Exemple #22
0
def send_country_list():
    gdp_data = get_gdp_data()
    output = build_table(gdp_data, 'blue_light')
    send_mail(output)
    return "Mail sent successfully."
Exemple #23
0
def make_table(item):
    df = csv_to_df(item)
    html = build_table(df, 'blue_light')
    return html
Exemple #24
0
def send_automato_list():
    gdp_data = df_review
    output = build_table(gdp_data, 'blue_light')
    send_mail(output)
    return "Mail sent successfully."
Exemple #25
0
    y, x = df_filtrado[f]['Latitude'].values, df_filtrado[f][
        'Longitude'].values
    x, y = [float(i.replace(',', '.'))
            for i in x], [float(i.replace(',', '.')) for i in y]
    ax1.scatter(x, y, label=s, marker='x')

ax1.axis('scaled')
ax1.set_title('Mapa de distribuição')
ax1.set_ylabel('Latitude')
ax1.set_xlabel('Longitude')
ax1.legend(framealpha=0.0)
ax1.grid(alpha=0.5, linestyle='--')

fisicos = fisicos.drop(columns=['Longitude', 'Latitude', 'Obs'])

t = build_table(fisicos, color='green_light', font_size='10px')

tabfis = open("tabelas/tabela_fisicos.html", "w", encoding='utf-8')
tabfis.write(t)
tabfis.close()

#portarias ano
filtro_outorga = []
for idx, row in df[['Classificação', 'Status',
                    'Data de saída do processo']].iterrows():
    #if row['Número da portaria'].split('-')[0] == 'O' and row['Data de saída do processo'].split('/')[-1] == str(ano):
    if row['Classificação'] == 'Outorga' and row[
            'Status'] == 'Concedida' and row[
                'Data de saída do processo'].split('/')[-1] == str(ano):
        filtro_outorga.append(True)
    else:
Exemple #26
0
def html():
    df = pd.read_csv('ranks.csv')
    html_table = build_table(df, 'blue_dark')
    Path("output").mkdir(exist_ok=True)
    with open('output/pretty_table.html', 'w') as f:
        f.write(html_table)
def generate_table():
    df = pd.DataFrame(
        data={
            'ID': [1, 2, 3, 4],
            'First Name': ['Flore', 'Grom', 'Truip', 'Ftro'],
            'Last Name': ['Ju', 'Re', 'Ve', 'Cy'],
            'Age': [23, 45, 67, 12],
            'Place of Birth': ['France', 'USA', 'China', 'India'],
            'Date of Birth':
            ['1996-10-04', '1974-10-10', '1952-04-07', '2007-10-06']
        })

    start = """<html><body>"""
    end = """ </body></html>"""

    output = start \
            + '<p style="font-family:Century Gothic;">blue_light<br /><p>' \
            + build_table(
                df,
                'blue_light',
                even_color='white',
                even_bg_color='grey') \
            + '<p style="font-family:Century Gothic;">blue_dark<br /><p>' \
            + build_table(df, 'blue_dark') \
            + '<p style="font-family:Century Gothic;">grey_light<br /><p>' \
            + build_table(df, 'grey_light') \
            + '<p style="font-family:Century Gothic;">grey_dark<br /><p>' \
            + build_table(df, 'grey_dark') \
            + '<p style="font-family:Century Gothic;">orange_light<br /><p>' \
            + build_table(df, 'orange_light') \
            + '<p style="font-family:Century Gothic;">orange_dark<br /><p>' \
            + build_table(df, 'orange_dark') \
            + '<p style="font-family:Century Gothic;">yellow_light<br /><p>' \
            + build_table(df, 'yellow_light') \
            + '<p style="font-family:Century Gothic;">yellow_dark<br /><p>' \
            + build_table(df, 'yellow_dark') \
            + '<p style="font-family:Century Gothic;">green_light<br /><p>' \
            + build_table(df, 'green_light') \
            + '<p style="font-family:Century Gothic;">green_dark<br /><p>' \
            + build_table(df, 'green_dark') \
            + '<p style="font-family:Century Gothic;">red_light<br /><p>' \
            + build_table(df, 'red_light') \
            + '<p style="font-family:Century Gothic;">red_dark<br /><p>' \
            + build_table(df, 'red_dark') \
            + end

    with open('example.html', 'w') as f:
        f.write(output)
Exemple #28
0
output = file.worksheet_by_title('Output')
output.set_dataframe(df_validated, (1,1), copy_index=False, copy_head=True, fit=True)

# to be reviewed
df_review = df2.loc[df2['validation'] == 'False']
df_review.reset_index(drop=True)
del df_review['validation']
file = gs.open_by_key('1NlDNmho_lp4LLSWjUDJRwGnScvazuO5bTvVdGHBxdXw')
output = file.worksheet_by_title('To Be Reviewed')
output.set_dataframe(df_review, (1,1), copy_index=False, copy_head=True, fit=True)

validated_html = df_validated.to_html()
review_html = df_review.to_html()

from pretty_html_table import build_table
output = build_table(df_review, 'blue_light')

from email.mime.text import MIMEText
import smtplib


def send_mail(body):

    message = MIMEMultipart()
    message['Subject'] = 'Automato Filling run!' + date_enable)
    message['From'] = '<*****@*****.**'
    message['To'] = '<*****@*****.**'

    body_content = body
    message.attach(MIMEText(body_content, "html"))
    msg_body = message.as_string()
Exemple #29
0
def email_alert(subject, to, dataset_fact, forecast, df_merged, username, api_key, user, password):



    # change URL of the graph per new client
    # make table and pull it to email body

    email_body = build_table(df_merged, 'red_light')
    # plotting
    fig = go.Figure()

    fig.add_trace(go.Scatter(x=forecast['ds'], y=forecast['yhat_lower'], name='Lowest expected value',line=dict(color='rgb(231,107,243)', width=2), line_shape='spline', ))
    fig.add_trace(go.Scatter(x=forecast['ds'], y=forecast['yhat_upper'], fill='tonexty', name='Highest expected value',line=dict(color='rgb(231,107,243)', width=2), line_shape='spline', ))
    fig.add_trace(go.Scatter(x=dataset_fact['ds'], y=dataset_fact['y'], name='Real value', line=dict(color='royalblue', width=2), line_shape='spline', ))
    fig.add_trace(go.Scatter(x=forecast['ds'], y=forecast['trend'], name='General trend', line_shape='spline', ))
    fig.add_trace(go.Scatter(x=forecast['ds'], y=forecast['yearly'], name='Yearly seasonality', ))
    # fig.add_trace(go.Scatter(x=forecast['ds'], y=forecast['rain'], name='Rain',))
    # fig.add_trace(go.Scatter(x=forecast['ds'], y=forecast['temp'], name='Temp',))
    # fig.add_trace(go.Scatter(x=forecast['ds'], y=forecast['holidays'], name='Holidays', ))
    # fig.add_trace(go.Scatter(x=forecast['ds'], y=forecast['weekly'], name='Weekly', ))


    # connect to plotly
    username = username # your username
    api_key = api_key # your api key - go to profile > settings > regenerate key
    chart_studio.tools.set_credentials_file(username=username, api_key=api_key)
    # generate URL of the plot
    url = py.plot(fig, auto_open=False, filename=plotly_graph)

    template = (''
                #'<a href="{graph_url}" target="_blank">'  # Open the interactive graph when you click on the image
                #'<img src="{graph_url}.png">'  # Use the ".png" magic url so that the latest, most-up-to-date image is included
                #'</a>'
                #'{caption}'  # Optional caption to include below the graph
                '<br>'  # Line break
                '<a href="{graph_url}" style="color: rgb(0,0,0); text-decoration: none; font-weight: 200;" target="_blank">'
                #'Click to see the interactive graph'
                '<img src="{graph_url}.png">'# Direct readers to Plotly for commenting, interactive graph
                '</a>'
                '<br>'
                '<br>'  # Line break
                '<hr>'  # horizontal line
                '')
    _ = template
    _ = _.format(graph_url=url, caption='')
    email_body += _

    """
    Add template button, if click - then anomaly doesnt count
    """
    # email attributes, connection to gmail
    message = MIMEMultipart()
    message['Subject'] = subject
    user = (user+'@gmail.com')
    password = password
    message['from'] = user
    message['To'] = to

    body_content = email_body
    message.attach(MIMEText(body_content, "html"))
    msg_body = message.as_string()

    server = SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.login(message['From'], password)
    server.sendmail(message['From'], message['To'], msg_body)
    server.quit()
    return
Exemple #30
0
def send_dataframe(best_picks_dataframe, table_color):
    output = build_table(best_picks_dataframe, table_color)
    send_mail(output)
    return "Mail sent successfully."