Ejemplo n.º 1
0
def func(n_nlicks,radio_value):
    if radio_value=='Fruit':
        fd1=fd[fd['Item Type']=='Fruit']
        return send_data_frame(fd1.to_excel, "Fruit.xlsx", index=False)
    elif radio_value=='Vegitable':
        fd2=fd[fd['Item Type']=='Vegitable']
        return send_data_frame(fd2.to_excel, "Vegitable.xlsx", index=False)
    else:
        return send_data_frame(fd.to_excel, "All_Data.xlsx", index=False)
Ejemplo n.º 2
0
def download_table(csvdownload, xlsdownload, jsondownload, data):
    df = pd.read_json(data, orient="records")
    if int(csvdownload) > int(xlsdownload) and int(csvdownload) > int(
            jsondownload):
        return send_data_frame(df.to_csv, "data.csv", index=False)
    elif int(xlsdownload) > int(csvdownload) and int(xlsdownload) > int(
            jsondownload):
        return send_data_frame(df.to_excel, r"data.xlsx", index=False)
    elif int(jsondownload) > int(csvdownload) and int(jsondownload) > int(
            xlsdownload):
        return send_data_frame(df.to_json, "data.json", orient="records")
Ejemplo n.º 3
0
 def twoDownload(n_clicks, children):
     if (n_clicks is not None) and (n_clicks > 0) and (children is not None):
         searchDate = children.strip('Sun_')
         searchDate = searchDate.strip('.fits')
         try:
             specData = read_csv(two.find_one({'filename': {'$regex': '.*' + searchDate + '.*'}}))
             return send_data_frame(specData.to_csv, filename=searchDate + ".2d_spectrum.csv")
         except:
             entry = one.find_one({})
             specData = read_csv(entry)
             return send_data_frame(specData.to_csv, filename="2D_sprectrum.csv")
Ejemplo n.º 4
0
    def downloadCallback(n_clicks):
      if not n_clicks is None:
        dl = self.downloads['grid']

        return send_data_frame(dl['data'].to_excel, dl['filename'] + '.xlsx', index=True)
      else:
        return no_update
Ejemplo n.º 5
0
def generate_csv(drtime, Locname):
    if Locname is not None and drtime is not None:
        df = pd.read_csv("currdf.csv")
        df["KeyTime"] = df.KeyTime.astype('datetime64[ns]')
        df = df[(df["Location"] == Locname) & (df["KeyTime"] == drtime)]
        #can do stuff  to dataframe here (trim down columns or w/e)
        return send_data_frame(df.to_csv, filename="battdata.csv", index=False)
def generar_csv(n_clicks, data, titulo_reporte) :
    """
    Callback para generar un archivo csv con los datos de la matrícula de todas
    las escuelas del reporte.
    
    Args:
        n_clicks (int): número de veces que se ha dado click al botón de descargar
            csv, o None si no se a presionado ninguna vez.
        data (dict): diccionario que contiene los datos de la sesión, incluidos 
            los de las escuelas.
        titulo_reporte (str): título del reporte o None si no se a escrito nada
            en el input del título del reporte.
    
    Returns:
        Genera y descarga un archivo csv con los datos de la matrícula y la predicción
            de todas las escuelas con el nombre del título del reporte.
    """
    titulo_reporte = titulo_reporte or 'Reporte sin titulo'
    
    if n_clicks :
        escuelas = data['escuelas']
        primer_anio = min((escuelas[cct]['primer_anio'] for cct in escuelas))
        ultimo_anio = max((len(escuelas[cct]['matricula']) + escuelas[cct]['primer_anio'] for cct in escuelas)) + 5
        nombre_columnas = ["cct"] + ["%d-%d" % (anio, anio + 1) for anio in range(primer_anio, ultimo_anio)]
        matricula = [
            [cct] + [
                (escuelas[cct]['matricula'] + escuelas[cct]['pred'])[anio - escuelas[cct]['primer_anio']] if anio >= escuelas[cct]['primer_anio'] else ''
                for anio in range(primer_anio, ultimo_anio)]
        for cct in escuelas]
        dataframe = pd.DataFrame(matricula, columns = nombre_columnas)
        return send_data_frame(dataframe.to_csv, filename = "%s.csv" % (titulo_reporte))
    else :
        raise PreventUpdate
Ejemplo n.º 7
0
def func(n_clicks):
    if os.path.exists('tmp.csv'):
        print('exists')
        df = pd.read_csv('tmp.csv')
        fn = 'poem_' + datetime.now().strftime('%Y_%m_%d_%H_%M_%S') + '.csv'
        os.remove('tmp.csv')
        return send_data_frame(df.to_csv, fn, index=False)
Ejemplo n.º 8
0
def func(n_clicks, prod_cons_matrix, region_lvl):
    #temp_dff = load_matrix(str(prod_cons_path), str(prod_cons_matrix))
    fpath = set_filepath(auth.get_current_username(), results_path,
                         results_filepath) + 'output.csv'
    return send_data_frame(
        download_df.to_csv, fpath
    )  #results_filepath)#"mydf.csv") # dash_extensions.snippets: send_data_frame
def generate_csv(n_clicks, raw):
    # I had to write this line otherwise it would automatically download the file even if you didn't click the download button...seems hacky
    if n_clicks is None or raw == None:
        raise PreventUpdate
    json_data = json.loads(raw)
    df = pd.DataFrame.from_dict(json_data, orient='columns')
    return send_data_frame(df.to_csv, filename="raw_data.csv")
def update_uploads(
    n_clicks,
    techSheetFilename,
    techSheetContents,
):
    if n_clicks is not None:
        if techSheetFilename is not None:

            list_of_df = [
                parseContents(c, n)
                for c, n in zip(techSheetContents, techSheetFilename)
            ]
            """
            Do something cool with df
            """

            outputDF = [
                send_data_frame(
                    df.to_csv,
                    filename=df_name,
                ) for df, df_name in zip(list_of_df, techSheetFilename)
            ] + [None for i in range(5 - len(techSheetFilename))]

            return outputDF
        else:
            return [None for i in range(5)]
    else:
        return [None for i in range(5)]
Ejemplo n.º 11
0
def func(n_clicks, selected_subs, selected_sig1):

    selected_sig1.append('Substation')
    selected_sig1.append('datetime')
    sel_customer = customer[selected_sig1]
    sel_customer = sel_customer[sel_customer['Substation'].isin(selected_subs)]

    return send_data_frame(sel_customer.to_csv, "substations.csv", index=False)
Ejemplo n.º 12
0
def func(n_clicks, selected_sites, selected_sig2):

        selected_sig2.append('Site')
        selected_sig2.append('datetime')
        sel_weather = weather[selected_sig2]
        sel_weather = sel_weather[sel_weather['Site'].isin(selected_sites)]

        return send_data_frame(sel_weather.to_csv, "weather.csv", index=False)
Ejemplo n.º 13
0
def export_button_click(n_clicks, data):
    if n_clicks is None:
        return None

    df = pd.DataFrame(data)
    df.drop(columns=['PointsHistory', 'Similarity'], inplace=True)
    df['Points'] = df['Points'].apply(lambda x: x[0])
    return send_data_frame(df.to_csv, 'points.csv', sep=';', index=False)
Ejemplo n.º 14
0
def generate_csv(data, n1):
    if data is not None:
        data = json.loads(data)
        data = pd.DataFrame.from_dict(data)
        if n1 is not None:
            return send_data_frame(data.to_csv, filename=f"sample_predictions_{datetime.today().strftime('%Y-%m-%d')}.csv", index = False)
    else:
        return None
Ejemplo n.º 15
0
def download_strengths_csv(n_clicks: Union[int, None]) -> Union[dict, None]:
    """ダウンロードボタンがクリックされたら資質ファイルをダウンロード"""
    if type(n_clicks) == int:
        df = pd.read_csv(strengths_path)
        dataframe_content = send_data_frame(df.to_csv,
                                            filename="member_strengths.csv")
        return dataframe_content
    else:
        return None
Ejemplo n.º 16
0
def generate_csv(n_clicks, jsonified_cleaned_data, jsonified_cleaned_data2,
                 jsonified_cleaned_data3):
    if n_clicks is None:
        raise PreventUpdate
    else:
        if jsonified_cleaned_data:
            df = pd.read_json(jsonified_cleaned_data, orient='split')

            return send_data_frame(df.to_csv, filename="some_name.csv")
        else:
            if jsonified_cleaned_data2:
                df = pd.read_json(jsonified_cleaned_data2, orient='split')
                return send_data_frame(df.to_csv, filename="some_name.csv")
            else:
                if jsonified_cleaned_data3:
                    df = pd.read_json(jsonified_cleaned_data3, orient='split')
                    return send_data_frame(df.to_csv, filename="some_name.csv")
                else:
                    raise PreventUpdate
Ejemplo n.º 17
0
def generate_csv(n_clicks, data):
    if n_clicks < 1:
        raise PreventUpdate
    # df = cache.get(session_id)
    df = pd.DataFrame(data)
    if df is None:
        raise PreventUpdate
    else:
        df['Sample_Date'] = pd.to_datetime(df['Sample_Date'])
        df['Sample_Date'] = df['Sample_Date'].dt.strftime('%m/%d/%Y')
        return send_data_frame(df.to_csv, filename='querydata.csv')
Ejemplo n.º 18
0
    def __download_graph_data(self, *inputs):
        """Download data associated with a figure"""

        # prep data file
        to_concat = []
        for trace_name, df in self.data.items():
            df_to_concat = df.copy()
            df_to_concat.insert(0, "trace", trace_name)
            to_concat.append(df_to_concat)
        df = pd.concat(to_concat).reset_index()
        return send_data_frame(df.to_excel, f"{df.columns[-1]}.xlsx")
Ejemplo n.º 19
0
def csv_download(cb_clicks, time, HRR, jobidd):

    #---------UNPACK JSON DATA
    flat_time = json.loads(time)
    flat_HRR = json.loads(HRR)
    #---------CREATE PANDAS DATAFRAME
    int_dict = {'Time (s)': flat_time, 'HRR (kW/s^2)': flat_HRR}

    t2_df = pd.DataFrame(int_dict)

    csv_title = 't_squard - ' + str(jobidd) + '.csv'

    return send_data_frame(t2_df.to_csv, filename=csv_title)
Ejemplo n.º 20
0
def download(n_clicks, years_range, nbds):
    if n_clicks:
        nbds = json.loads(nbds) if nbds else [default_nbd_id]
        df_nbh = df[df["nbhid"].isin(nbds)]  # filter chosen states
        nbhname = df_nbh['nbh_name'].iloc[0]
        df_nbh = df_nbh[(df_nbh['CREATION YEAR'] <= years_range[1])
                        & (df_nbh['CREATION YEAR'] >= years_range[0])]
        return send_data_frame(df_nbh.to_csv,
                               "".join([
                                   "kc311_", "_".join(nbds), '_', nbhname, '_',
                                   str(years_range[0]), '-',
                                   str(years_range[1]), ".csv"
                               ]),
                               index=False)
Ejemplo n.º 21
0
    def export_to_csv(self, n_clicks):
        try:
            team = int(request.cookies["team_metrics_idx"])
        except BadRequestKeyError:
            team = 0

        tm = self.projects[team]

        if n_clicks > 0:
            logging.debug("Downloading CSV file")
            return send_data_frame(
                tm.cycle_data.to_csv,
                filename=f"{tm.name}.csv",
            )
Ejemplo n.º 22
0
def export_range_csv(n_clicks, start_date, end_date, plot, sensor_tag,
                     df_save):
    if n_clicks > 0:
        out_filename = str(start_date) + "_" + str(end_date) + "_data.csv"
        df = pd.read_json(df_save, orient="split")

        visible_traces = []
        for key in plot["data"]:
            if key.get("visible") == 1 or str(key.get("visible")) == "None":
                visible_traces.append(key.get(sensor_tag))
        df = df[df[sensor_tag].isin(visible_traces)]

        return send_data_frame(df.sort_values(by=["ip", "datetime"]).to_csv,
                               out_filename,
                               index=False)
Ejemplo n.º 23
0
def generate_csv(n_clicks, plotted_data):
    """
    Callback to download graph data to a CSV file.

    :param n_clicks: number of times the download button was clicked.
                     Used here to simply detect if the button was clicked.
    :param plotted_data: the data that is currently displayed
    :return: an instruction for the browser to initiate a download of the
             DataFrame
    """
    if n_clicks:
        data = pd.read_json(plotted_data, orient="split")
        return send_data_frame(data.to_csv,
                               "ukbb_metadata_variable_subset.csv",
                               index=False)
Ejemplo n.º 24
0
def export_csv(n_clicks, date, plot, sensor_tag, df_save):
    if n_clicks > 0:
        data_source = get_sensor_datafile_name(date)
        df = pd.read_json(df_save, orient="split")
        out_filename = data_source.split("_")[0] + "_data.csv"

        visible_traces = []
        for key in plot["data"]:
            if key.get("visible") == 1 or str(key.get("visible")) == "None":
                visible_traces.append(key.get(sensor_tag))
        df = df[df[sensor_tag].isin(visible_traces)]

        return send_data_frame(df.sort_values(by=["ip", "datetime"]).to_csv,
                               out_filename,
                               index=False)
    return dash.no_update
Ejemplo n.º 25
0
def save_to_csv(n_clicks, n_intervals, sec):
    no_notification = html.Plaintext("", style={'margin': "0px"})
    notification_text = html.Plaintext("The Shown Table Data has been saved to the excel sheet.",
                                       style={'color': 'green', 'font-weight': 'bold', 'font-size': 'large'})
    input_triggered = dash.callback_context.triggered[0]["prop_id"].split(".")[0]
    if input_triggered == "excel_btn" and n_clicks:
        sec = 10
        return send_data_frame(df_table_content.to_csv, filename="Labeled_Eye_Images.csv"), notification_text, sec
    elif input_triggered == 'excel_notification_interval' and sec > 0:
        sec = sec - 1
        if sec > 0:
            return None, notification_text, sec
        else:
            return None, no_notification, sec
    elif sec == 0:
        return None, no_notification, sec
Ejemplo n.º 26
0
def func(n_nlicks,url,dados):
    ctx = dash.callback_context
    trigger_id = ctx.triggered[0]["prop_id"].split(".")[0]
    if trigger_id != 'btn-exp-tabela':
        raise PreventUpdate
    else:
        nome_arquivo = 'arquivo.xlsx'
        if url == '/' or url == '/contratos':
            nome_arquivo = 'tabela_contratos.xlsx'
        if url == '/balanco':
            nome_arquivo = 'tabela_balanço.xlsx'
        if url == '/custos':
            nome_arquivo = 'tabela_custos.xlsx'
        
        df = pd.DataFrame(dados) 
        if n_nlicks != None:
            return send_data_frame(df.to_excel, nome_arquivo, index=False)
Ejemplo n.º 27
0
def func(n_nlicks,url,fig):
    ctx = dash.callback_context
    trigger_id = ctx.triggered[0]["prop_id"].split(".")[0]
    if trigger_id != 'btn-exp-grafico':
        raise PreventUpdate
    else:
        nome_arquivo = 'arquivo.xlsx'
        if url == '/' or url == '/contratos':
            nome_arquivo = 'grafico_contratos.xlsx'
        if url == '/balanco':
            nome_arquivo = 'grafico_balanço.xlsx'
        if url == '/custos':
            nome_arquivo = 'grafico_custos.xlsx'
            
        if n_nlicks != None:
            df2 = pd.DataFrame(gf.retorna_grafico(fig))
            return send_data_frame(df2.to_excel, nome_arquivo, index=False)
def generar_csv(n_clicks, data, id_escuela):
    """
    Callback para generar un archivo csv con los datos de la matrícula de la escuela
    del reporte.
    
    Args:
        n_clicks (int): número de veces que se ha dado click al botón de descargar
            csv, o None si no se a presionado ninguna vez.
        data (dict): diccionario que contiene los datos de la sesión, incluidos 
            los de las escuelas.
        id_escuela (dict): diccionario que contiene el id del objeto para descargar
            el archivo csv, que a su vez contiene la cct de la escuela.
    
    Returns:
        Genera y descarga un archivo csv con los datos de la matrícula y la predicción
            de todas las escuelas con el nombre de la cct de la escuela.
    """
    if n_clicks:
        cct = id_escuela['index']
        escuelas = data['escuelas']
        primer_anio = escuelas[cct]['primer_anio']
        ultimo_anio = len(
            escuelas[cct]['matricula']) + escuelas[cct]['primer_anio'] + 5
        nombre_columnas = ["cct"] + [
            "%d-%d" % (anio, anio + 1)
            for anio in range(primer_anio, ultimo_anio)
        ]

        matricula = [cct] + [(escuelas[cct]['matricula'] +
                              escuelas[cct]['pred'])[anio - primer_anio]
                             for anio in range(primer_anio, ultimo_anio)]

        dataframe = pd.DataFrame([matricula], columns=nombre_columnas)
        return send_data_frame(dataframe.to_csv, filename="%s.csv" % (cct))
    else:
        raise PreventUpdate
Ejemplo n.º 29
0
def generate_csv(n_clicks, final_df, EpitopeDB_type):
    if n_clicks != 0:
        if final_df is not None:
            final_df = pd.read_json(final_df, orient='split')
            return send_data_frame(final_df.to_csv,
                                   filename=f"DESA, {EpitopeDB_type}.csv")
Ejemplo n.º 30
0
def func(n_clicks):
    return send_data_frame(df.to_excel, "mydf.xls")