Beispiel #1
0
    def refresh_available_windows(self, *args, **kwargs):
        """Refresh each grid table with available tables

        After an app is selected, other grids should not be able to select it as well.
        """
        dpg_core.log_debug(f"Refreshing available windows for table {self.id}")
        active_windows = set(self.ACTIVE_WINDOWS)
        available_windows = active_windows - self._allocated_windows
        grid_mapping = defaultdict(list)
        for row in range(1, self._nrows + 1):
            dpg_core.clear_table(f"{self._id}_{row}_table")

            selected_active_windows = set(
                self._grid_mapping[row]) & active_windows
            grid_mapping[row] = list(selected_active_windows)

            windows = sorted(list(available_windows | selected_active_windows))
            for n, name in enumerate(windows):
                dpg_core.add_row(f"{self._id}_{row}_table", [name])

                if name in selected_active_windows:
                    dpg_core.set_table_selection(f"{self._id}_{row}_table", n,
                                                 0, True)

        self._grid_mapping = grid_mapping
        dpg_core.log_debug(f"Refreshed available windows for table {self.id}")
Beispiel #2
0
 def compose_workout(self):
     equipment_val = core.get_value("Equipment##widget")
     exercise_type_val = core.get_value("Exercise Type##widget")
     muscle_group_val = core.get_value("Muscle Group##widget")
     if not equipment_val or not exercise_type_val or not muscle_group_val:
         simple.show_item("Fill all the inputs, please.")
     else:
         simple.hide_item("workout_composition_group")
         self._composed_workout = workout_services.get_composed_workout(
             equipment_val, exercise_type_val, muscle_group_val)
         core.add_group(name="buttons", parent="workout_execution_group")
         core.add_table(
             "workout_table",
             ["Exercise", "Sets", "Reps", "Example"],
             parent="workout_execution_group",
             callback=self.toggle,
         )
         for workout in self._composed_workout:
             core.add_row("workout_table", list(workout.values()))
         core.add_button("Cancel##widget",
                         callback=self.cancel_workout,
                         parent="buttons")
         core.add_button("Clear##widget",
                         callback=self.clear_table,
                         parent="buttons")
         core.add_button("Save##widget",
                         callback=self.save_workout,
                         parent="buttons")
Beispiel #3
0
 def clear_table(self):
     for workout in self._composed_workout:
         workout["Sets"] = 0
         workout["Reps"] = 0
     core.clear_table("workout_table")
     for workout in self._composed_workout:
         core.add_row("workout_table", list(workout.values()))
Beispiel #4
0
 def __render(self, sender, data):
     """Run every frame to update the GUI.
     Updates the table by clearing it and inserting rows with the data.
     """
     dpg.clear_table('Files')
     for f in self.files_list:
         dpg.add_row('Files', [f['path'], f['name']])
Beispiel #5
0
def update_password_table():
    """Update password table contents.

    Clear the all contents in the password table,
    and recreate table entirely.
    """

    core.clear_table('##password_table')

    try:
        password_infos = model.select_all_items()
    except Exception:
        logger.add_error_message('Failed to fetch passwords.')
        return

    if password_infos:
        for password_info in password_infos:
            core.add_row('##password_table', [
                password_info.row_id,
                password_info.title,
                password_info.identifier,
                format_password(password_info.password.decode()),
                password_info.note,
            ])
    logger.add_info_message('Password table was updated.')
Beispiel #6
0
 def __render(self, sender, data):
     """Run every frame to update the GUI.
     Updates the table by clearing it and inserting rows with the data.
     """
     dpg.clear_table('Todos')
     for todo in self.todos:
         dpg.add_row('Todos', [todo['id'], todo['content'], todo['done']])
Beispiel #7
0
        def file_callback(sender, data):
            nonlocal c_board
            nonlocal pars

            pars = Parser()
            pars.get_plays(data[0]+'/'+data[1])

            # Lista de partidas cargadas--------------------------------TODO
            dpg.add_window('Lista de Partidas',on_close=close_callback)
            colums = set()
            for match in pars.matches:
                for att in match.attr:
                    colums.add(att)
            colums = list(colums)
            # colums.sort()
            dpg.add_table("Partidas", colums, callback=load_match)

            rows = list()
            for match in pars.matches:
                row = list()
                for colum in colums:
                    row.append(match.attr[colum])

                rows.append(row)

            for row in rows:
                dpg.add_row("Partidas", row)

            dpg.end()
Beispiel #8
0
 def generate_records_table(self):
     self._records = record_services.get_all_records_by_user(self._username)
     core.add_table(
         "record_table",
         ["Exercise", "Sets", "Reps", "Date"],
     )
     for record_arr in self._records:
         core.add_row("record_table", record_arr)
Beispiel #9
0
 def __render(self, sender, data):
     """Run every frame to update the GUI.
     Updates the table by clearing it and inserting rows with the data.
     """
     dpg.clear_table("Stocks")
     for stock in self.stocks:
         dpg.add_row(
             "Stocks",
             [stock["Stock"], stock["Prediction"], stock["Confidence"]])
Beispiel #10
0
    def __tableRefresh(self):
        if core.does_item_exist("table"):
            core.delete_item("table")

        # build the data model so we can search it
        core.add_table("table", self.__headers, parent="panel")
        search = core.get_value("filter")
        search = re.compile(filter, re.I)
        for row in self.__rows:
            for cell in row:
                if search.search(cell):
                    core.add_row("table", row)
                    break
Beispiel #11
0
 def add_row_to_entry_table(self, entry: Entry) -> None:
     """
     Helper to add entry to the table
     :param entry: A single entry to convert to entries table
     :return: New row attached to the Entries##table
     """
     row_data = [
         entry.project_name,
         entry.description,
         str(entry.duration)[:10],
         entry.start_time.time().strftime("%I:%M"),
         entry.end_time.time().strftime("%I:%M"),
     ]
     c.add_row(self.table_name, row_data)
Beispiel #12
0
 def compose_workout(self):
     equipment_val = core.get_value("Equipment##widget")
     exercise_type_val = core.get_value("Exercise Type##widget")
     muscle_group_val = core.get_value("Muscle Group##widget")
     if not equipment_val or not exercise_type_val or not muscle_group_val:
         simple.show_item("Fill all the inputs, please.")
     else:
         self.composed_workout = get_composed_workout(
             equipment_val, exercise_type_val, muscle_group_val)
         simple.hide_item("workout_composition_group")
         core.add_table("Workout", ["Exercise", "Sets", "Reps", "Example"],
                        callback=self.toggle)
         for el in self.composed_workout:
             core.add_row("Workout", list(el.values()))
         core.add_button("Cancel##widget")
         core.add_button("Save##widget")
Beispiel #13
0
    def set_rows(self, nrows):
        """ "Set the rows in the table

        Each row has two columns. The first column is the grid number. The second column is a list
        of applications to snap to the grid. We use a table to enable multiselect
        """
        dpg_core.log_info(f"Refreshing rows for table {self.id}")
        for row in range(1, nrows + 1):
            name = f"{self._id}_{row}"
            # If the row already exists, we don't need to do anything else
            if dpg_core.does_item_exist(name):
                continue

            with dpg_simple.managed_columns(name,
                                            len(self.HEADER),
                                            parent=self.parent):
                # The first column is the grid number
                dpg_core.add_input_int(
                    f"##{self._id}_{row}_number",
                    default_value=row,
                    readonly=True,
                    step=0,
                    parent=name,
                )

                # The second column is the table. Wrap in a collapsing header so the screen isn't
                # too full the entire time.
                with dpg_simple.collapsing_header(f"##{self._id}_{row}_header",
                                                  parent=name):
                    dpg_core.add_table(
                        f"{self._id}_{row}_table",
                        [""],  # no headers
                        callback=self.selected,
                        parent=f"##{self._id}_{row}_header",
                    )
                    # populate the table with the names of available windows
                    for window_name in sorted(self.ACTIVE_WINDOWS):
                        dpg_core.add_row(f"{self._id}_{row}_table",
                                         [window_name])

            # Separate each row with a line
            dpg_core.add_separator(name=f"{self._id}_{row}_sep", parent=name)

        self._nrows = nrows
        dpg_core.log_info(f"Refreshed rows for table {self.id}")
 def user_dashboard(self):
     with window("User Dash", width=500, height=500):
         self.menu(True, False, False, False)
         with group("Basic user info", horizontal=True):
             gg.add_text(f"Username: {self.user.file[:-3]}")
             gg.add_text(f"Starting Balance: {self.user.start_funds}")
             net_worth = round(sum(self.user.share_quantity[ticker]*yfs.get_live_price(ticker)
                              for ticker in self.user.share_quantity), 2) + self.user.current_balance
             gg.add_text(f"Net Worth: {net_worth}")
         with group("Tables", horizontal=True):
             gg.add_table("Your Watchlist", headers=["Watchlist Ticker Name"], width=150)
             for stock in self.user.watchlist:
                 gg.add_row("Your Watchlist", [f"{stock}"])
             gg.add_table("Your stocks", headers=["Ticker Name", "Date", "Quantity"])
             for stock in self.user.share_by_name:
                 for share_data in self.user.share_by_name[stock]:
                     row = [stock, share_data[1], str(share_data[-1])]
                     gg.add_row("Your stocks", row)
    def info_single_stock(self, data: dict):
        ticker = data["Ticker"]
        with window(ticker + "##window", width=500, height=500, no_scrollbar=False):
            self.menu(False, False, False, False)
            ticker_data = yfs.get_quote_table(ticker, dict_result=True)
            date_time = datetime.datetime.now()
            time = date_time.time()
            date = date_time.date()
            price = round(ticker_data["Quote Price"], 2)
            with group("heading", horizontal=True):
                with group("day_info"):
                    gg.add_text("Date: " + str(date), color=[255, 0, 0])
                    gg.add_text("Time: " + str(time), color=[255, 0, 0])
                try:
                    gg.add_label_text("Current Shares",
                                      label=f"Number of shares: {self.user.share_quantity[ticker]}",
                                      color=[0, 255, 0])
                except KeyError:
                    gg.add_label_text("Current Shares",
                                      label=f"Number of shares: 0",
                                      color=[0, 255, 0])
            with menu_bar("local_info"):
                gg.add_menu_item("ticker", label=ticker, enabled=False)
                gg.add_label_text("Current Balance", label=f"Current Balance: {self.user.current_balance}",
                                  color=[255, 0, 0])

            gg.add_separator()
            gg.add_text("Today")
            gg.add_separator()
            with managed_columns("day_info_ticker", columns=3):
                gg.add_text("Last close: " + str(ticker_data["Previous Close"]))
                gg.add_text("Open price: " + str(ticker_data["Open"]))
                gg.add_text("Current price: " + str(price))
            gg.add_separator()

            with group("Extra info", horizontal=True):
                with group("Extra Info##1"):
                    gg.add_text("Volume: " + str(ticker_data["Volume"]), bullet=True)
                    gg.add_text("Market Cap: " + str(ticker_data["Market Cap"]), bullet=True)
            
                with group("Extra info##2"):
                    gg.add_text("52 Week Range: " + str(ticker_data["52 Week Range"]), bullet=True)
                    one_year_estimate = ticker_data["1y Target Est"]
                    percent_change = get_percent_change(price, one_year_estimate)
                    if one_year_estimate > price:
                        colour = [0, 255, 0]
                    else:
                        colour = [255, 0, 0]

                    with group("1Y estimate", horizontal=True):
                        gg.add_text(f"1y Target Estimate: {ticker_data['1y Target Est']} |", bullet=True)
                        gg.add_text(f"{percent_change}%", color=colour)

            gg.add_spacing(count=5)

            # Table of share data on first day of each month since 365 days ago
            date_data_since = date - datetime.timedelta(365)
            table_monthly_interval_data = yfs.get_data(ticker, start_date=date_data_since, interval="1mo")
            gg.add_table("monthly_data", headers=["date"] + [header for header in table_monthly_interval_data])
            for date_index in table_monthly_interval_data.index:
                list_values = [str(date_index)[:10]]
                list_values.extend(list(table_monthly_interval_data.loc[date_index]))
                for i in range(len(list_values)):
                    if type(list_values[i]) == str:
                        continue
                    else:
                        list_values[i] = str(round(list_values[i], 3))
                gg.add_row("monthly_data", list_values)

            gg.add_spacing(count=2)

            def make_plot():
                date_data_since = date - datetime.timedelta(30)
                scatter_plot_weekly_data = yfs.get_data(ticker, start_date=date_data_since, interval="1d")
                indecis = [x for x in scatter_plot_weekly_data.index]
                start_date = indecis[0]
                x_axis = [(x - start_date).days for x in indecis]
                y_axis_max = [scatter_plot_weekly_data.loc[x]['high'] for x in indecis]
                y_axis_min = [scatter_plot_weekly_data.loc[x]['low'] for x in indecis]
                gg.add_plot("30 Day Price Fluctuation", height=300, scale_max=.5,
                            x_axis_name=f"Days since {start_date}", y_axis_name="Single share price")
                gg.add_scatter_series("30 Day Price Fluctuation", "Day High", x=x_axis, y=y_axis_max, size=3)
                gg.add_scatter_series("30 Day Price Fluctuation", "Day Low", x=x_axis, y=y_axis_min, marker=1, size=3)

                # Set initial plot view
                gg.set_plot_xlimits("30 Day Price Fluctuation", 0, 30)
                gg.set_plot_ylimits("30 Day Price Fluctuation", min(y_axis_min)*.97, max(y_axis_max)*1.03)
                gg.set_plot_ylimits_auto("30 Day Price Fluctuation")
                gg.set_plot_xlimits_auto("30 Day Price Fluctuation")

            make_plot()
            # Create purchase button and what not

            def purchase_stocks(sender, data):
                quantity = round(gg.get_value("Quantity"), 2)
                total_price = quantity * price
                gg.set_item_color("Message", style=1, color=[255, 0, 0])
                if self.user.current_balance < total_price:
                    set_item_label("Message", "Cannot purchase, insufficient funds")
                elif 0 >= total_price:
                    set_item_label("Message", "Must spend more than 0$")
                else:
                    set_item_label("Message", f"Purchase of {quantity} {ticker} shares at {price} made")
                    gg.set_item_color("Message", style=1, color=[0, 255, 0])
                    self.user.buy_share(quantity, price, ticker, str(date), str(time))
                    set_item_label("Current Balance", f"Current Balance: {self.user.current_balance}")
                    set_item_label("Current Shares", f"Number of shares: {self.user.share_quantity[ticker]}")

            def add_to_watchlist(sender, data):
                self.user.add_to_watchlist(ticker, price, database=True)
                set_item_label(sender, "Remove From Watchlist")
                gg.set_item_callback(sender, remove_from_watchlist)

            def remove_from_watchlist(sender, data):
                self.user.remove_from_watchlist(ticker)
                set_item_label(sender, "Add To Watchlist")
                gg.set_item_callback(sender, add_to_watchlist)

            with group("footer", horizontal=True):
                with group("Buy Stock Group"):
                    def get_dynamic_cost(sender, data):
                        # TODO dynamic colouring
                        cost = round(gg.get_value("Quantity") * price, 2)
                        set_item_label("Stock volume", f"Total Cost: {cost}")

                    gg.add_input_float("Stock volume", default_value=0,
                                       width=100, source="Quantity", label="Total cost: 0",
                                       callback=get_dynamic_cost, on_enter=True)
                    gg.add_label_text("Message", label="", color=[255, 0, 0])
                    gg.add_button("Buy Shares", callback=purchase_stocks)
                with group("Stock Watchlist"):
                    if ticker not in self.user.watchlist:
                        gg.add_button("Watchlist Button", callback=add_to_watchlist, label="Add To Watchlist")
                    else:
                        gg.add_button("Watchlist Button", callback=remove_from_watchlist, label="Remove From Watchlist")
Beispiel #16
0
    core.set_table_item("Earnings", 5, 1, repr(calendar.iloc[5, 0]))
    core.set_table_item("Earnings", 6, 1, repr(calendar.iloc[6, 0]))


with simple.window("Tables",
                   height=300,
                   width=500,
                   x_pos=980,
                   y_pos=110,
                   no_close=True):
    with simple.menu("Select Company##table"):
        for file in os.listdir("dataset"):
            filename = os.fsdecode(file)
            if filename.endswith(".csv"):
                core.add_menu_item(filename.split('_')[0] + "##table",
                                   callback_data=filename.split('_')[0],
                                   callback=update_table)
    core.add_table("Earnings", ["Specs", "Value"])
    core.add_row("Earnings", ["Earnings Date", ""])
    core.add_row("Earnings", ["Earnings Average", ""])
    core.add_row("Earnings", ["Earnings Low", ""])
    core.add_row("Earnings", ["Earnings High", ""])
    core.add_row("Earnings", ["Revenue Average", ""])
    core.add_row("Earnings", ["Revenue Low", ""])
    core.add_row("Earnings", ["Revenue High", ""])

# core.show_logger()
# simple.show_documentation()

core.start_dearpygui()