Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: Remove Mypy errors from examples. #2171

Open
wants to merge 28 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion py/examples/background_progress.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ def blocking_function(q: Q, loop: asyncio.AbstractEventLoop):
# If future is not done yet, skip the update to keep the correct order.
if not future or future.done():
# Assume you are able to emit some kind of progress.
future = asyncio.ensure_future(update_ui(q, count / total), loop=loop)
future = asyncio.ensure_future(update_ui(q, round(count / total)), loop=loop)


async def show_cancel(q: Q):
Expand Down
7 changes: 6 additions & 1 deletion py/examples/db_todo.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,11 @@ async def show_todos(q: Q):
rows, err = await db.exec('select id, label, done from todo where user=?', q.auth.subject)
if err:
raise RuntimeError(f'Failed fetching todos: {err}')
todos = [TodoItem(id, label, done) for id, label, done in rows]

if rows is not None:
todos = [TodoItem(id, label, done) for id, label, done in rows]
else:
todos = []

# Create done/not-done checkboxes.
done = [ui.checkbox(name=f'todo_{todo.id}', label=todo.label, value=True, trigger=True) for todo in todos if
Expand All @@ -85,6 +89,7 @@ async def show_todos(q: Q):
await q.page.save()



async def add_todo(q: Q):
# Insert a new item
db: WaveDB = q.app.db
Expand Down
2 changes: 1 addition & 1 deletion py/examples/form.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# Form
# Use a #form to collect data or show textual information.
# ---
from .synth import FakeCategoricalSeries
from .synth import FakeCategoricalSeries # type: ignore
from h2o_wave import main, app, Q, ui, pack, data
import random

Expand Down
78 changes: 38 additions & 40 deletions py/examples/graphics_spline.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
# Graphics / Spline
# Use the #graphics module to render splines.
# ---

import random
from h2o_wave import site, ui, graphics as g

# Define a function to convert a list of values to float
def to_float(lst): # for example, [1, 2, 3] -> [1.0, 2.0, 3.0]
return [float(v) for v in lst]

x = [i * 20 for i in range(50)]
y = [
88, 100, 116, 128, 126, 128, 118, 108, 121, 120, 99, 113, 117, 103, 98, 90, 104, 98, 82, 102, 104, 89, 87, 69,
Expand All @@ -17,43 +17,41 @@

splines = [
# Lines
g.spline(x=x, y=y, **line_style), # same as curve='linear'
g.spline(x=x, y=y, curve='basis', **line_style),
g.spline(x=x, y=y, curve='basis-closed', **line_style),
g.spline(x=x, y=y, curve='basis-open', **line_style),
g.spline(x=x, y=y, curve='cardinal', **line_style),
g.spline(x=x, y=y, curve='cardinal-closed', **line_style),
g.spline(x=x, y=y, curve='cardinal-open', **line_style),
g.spline(x=x, y=y, curve='smooth', **line_style),
g.spline(x=x, y=y, curve='smooth-closed', **line_style),
g.spline(x=x, y=y, curve='smooth-open', **line_style),
g.spline(x=x, y=y, curve='linear', **line_style),
g.spline(x=x, y=y, curve='linear-closed', **line_style),
g.spline(x=x, y=y, curve='monotone-x', **line_style),
g.spline(x=x, y=y, curve='monotone-y', **line_style),
g.spline(x=x, y=y, curve='natural', **line_style),
g.spline(x=x, y=y, curve='step', **line_style),
g.spline(x=x, y=y, curve='step-after', **line_style),
g.spline(x=x, y=y, curve='step-before', **line_style),
g.spline(x=to_float(x), y=to_float(y), curve='basis', style=line_style),
g.spline(x=to_float(x), y=to_float(y), curve='basis-closed', style=line_style),
g.spline(x=to_float(x), y=to_float(y), curve='basis-open', style=line_style),
g.spline(x=to_float(x), y=to_float(y), curve='cardinal', style=line_style),
g.spline(x=to_float(x), y=to_float(y), curve='cardinal-closed', style=line_style),
g.spline(x=to_float(x), y=to_float(y), curve='cardinal-open', style=line_style),
g.spline(x=to_float(x), y=to_float(y), curve='smooth', style=line_style),
g.spline(x=to_float(x), y=to_float(y), curve='smooth-closed', style=line_style),
g.spline(x=to_float(x), y=to_float(y), curve='smooth-open', style=line_style),
g.spline(x=to_float(x), y=to_float(y), curve='linear-closed', style=line_style),
g.spline(x=to_float(x), y=to_float(y), curve='monotone-x', style=line_style),
g.spline(x=to_float(x), y=to_float(y), curve='monotone-y', style=line_style),
g.spline(x=to_float(x), y=to_float(y), curve='natural', style=line_style),
g.spline(x=to_float(x), y=to_float(y), curve='step', style=line_style),
g.spline(x=to_float(x), y=to_float(y), curve='step-after', style=line_style),
g.spline(x=to_float(x), y=to_float(y), curve='step-before', style=line_style),
# Areas
g.spline(x=x, y=y, y0=y0, **area_style), # same as curve='linear'
g.spline(x=x, y=y, y0=y0, curve='basis', **area_style),
g.spline(x=x, y=y, y0=[], curve='basis', **area_style),
g.spline(x=x, y=y, y0=y0, curve='basis-open', **area_style),
g.spline(x=x, y=y, y0=y0, curve='cardinal', **area_style),
g.spline(x=x, y=y, y0=[], curve='cardinal', **area_style),
g.spline(x=x, y=y, y0=y0, curve='cardinal-open', **area_style),
g.spline(x=x, y=y, y0=y0, curve='smooth', **area_style),
g.spline(x=x, y=y, y0=[], curve='smooth', **area_style),
g.spline(x=x, y=y, y0=y0, curve='smooth-open', **area_style),
g.spline(x=x, y=y, y0=y0, curve='linear', **area_style),
g.spline(x=x, y=y, y0=[], curve='linear', **area_style),
g.spline(x=x, y=y, y0=y0, curve='monotone-x', **area_style),
g.spline(x=x, y=y, y0=y0, curve='monotone-y', **area_style),
g.spline(x=x, y=y, y0=y0, curve='natural', **area_style),
g.spline(x=x, y=y, y0=y0, curve='step', **area_style),
g.spline(x=x, y=y, y0=y0, curve='step-after', **area_style),
g.spline(x=x, y=y, y0=y0, curve='step-before', **area_style),
g.spline(x=to_float(x), y=to_float(y), y0=to_float(y0), curve='linear', style=area_style),
g.spline(x=to_float(x), y=to_float(y), y0=to_float(y0), curve='basis', style=area_style),
g.spline(x=to_float(x), y=to_float(y), y0=[], curve='basis', style=area_style),
g.spline(x=to_float(x), y=to_float(y), y0=to_float(y0), curve='basis-open', style=area_style),
g.spline(x=to_float(x), y=to_float(y), y0=to_float(y0), curve='cardinal', style=area_style),
g.spline(x=to_float(x), y=to_float(y), y0=[], curve='cardinal', style=area_style),
g.spline(x=to_float(x), y=to_float(y), y0=to_float(y0), curve='cardinal-open', style=area_style),
g.spline(x=to_float(x), y=to_float(y), y0=to_float(y0), curve='smooth', style=area_style),
g.spline(x=to_float(x), y=to_float(y), y0=[], curve='smooth', style=area_style),
g.spline(x=to_float(x), y=to_float(y), y0=to_float(y0), curve='smooth-open', style=area_style),
g.spline(x=to_float(x), y=to_float(y), y0=to_float(y0), curve='linear', style=area_style),
g.spline(x=to_float(x), y=to_float(y), y0=[], curve='linear', style=area_style),
g.spline(x=to_float(x), y=to_float(y), y0=to_float(y0), curve='monotone-x', style=area_style),
g.spline(x=to_float(x), y=to_float(y), y0=to_float(y0), curve='monotone-y', style=area_style),
g.spline(x=to_float(x), y=to_float(y), y0=to_float(y0), curve='natural', style=area_style),
g.spline(x=to_float(x), y=to_float(y), y0=to_float(y0), curve='step', style=area_style),
g.spline(x=to_float(x), y=to_float(y), y0=to_float(y0), curve='step-after', style=area_style),
g.spline(x=to_float(x), y=to_float(y), y0=to_float(y0), curve='step-before', style=area_style),
]

page = site['/demo']
Expand Down
2 changes: 1 addition & 1 deletion py/examples/graphics_turtle.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
t = g.turtle().f(100).r(90).pd()
for _ in range(36):
t.f(200).l(170)
spirograph = t.pu(1).path(stroke='red', fill='yellow')
spirograph = t.pu(close=True).path(stroke='red', fill='yellow')

page = site['/demo']
page['example'] = ui.graphics_card(
Expand Down
10 changes: 5 additions & 5 deletions py/examples/image.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,11 @@
0.76648938, 0.89679732, 0.77222302, 0.92717429, 0.61465203, 0.60906377,
0.68468487, 0.25101297, 0.83783764, 0.11861562, 0.79723474, 0.94900427,
0.14806288])) ** 2,
c=[0.90687198, 0.78837333, 0.76840584, 0.59849648, 0.44214562, 0.72303802,
0.41661825, 0.2268104, 0.45422734, 0.84794375, 0.93665595, 0.95603618,
0.39209432, 0.70832467, 0.12951583, 0.35379639, 0.40427152, 0.6485339,
0.03307097, 0.53800936, 0.13171312, 0.52093493, 0.10248479, 0.15798038,
0.92002965],
c=[0.90687198, 0.78837333, 0.76840584, 0.59849648, 0.44214562, 0.72303802, # type: ignore
0.41661825, 0.2268104, 0.45422734, 0.84794375, 0.93665595, 0.95603618, # type: ignore
0.39209432, 0.70832467, 0.12951583, 0.35379639, 0.40427152, 0.6485339, # type: ignore
0.03307097, 0.53800936, 0.13171312, 0.52093493, 0.10248479, 0.15798038, # type: ignore
0.92002965], # type: ignore
alpha=0.5,
)

Expand Down
4 changes: 2 additions & 2 deletions py/examples/plot_altair.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# Plot / Altair
# Use #Altair to create #plot specifications for the #Vega card.
# ---
import altair
from vega_datasets import data
import altair # type: ignore
from vega_datasets import data # type: ignore
from h2o_wave import site, ui

spec = altair.Chart(data.cars()).mark_circle(size=60).encode(
Expand Down
2 changes: 1 addition & 1 deletion py/examples/plot_app.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# Plot / App
# Make a #plot from an app.
# ---
from .synth import FakeMultiCategoricalSeries as F
from .synth import FakeMultiCategoricalSeries as F # type: ignore
from h2o_wave import main, app, data, Q, ui

n = 10
Expand Down
6 changes: 4 additions & 2 deletions py/examples/plot_bokeh_callbacks.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@

import json
from random import random

from bokeh.core.types import ID
from h2o_wave import main, app, Q, ui
from bokeh.resources import CDN
from bokeh.layouts import row
Expand All @@ -31,7 +33,7 @@ async def serve(q: Q):
p2 = figure(width=250, height=300, x_range=(0, 1), y_range=(0, 1), tools="", title="Watch Here")
p2.circle('x', 'y', source=s2, alpha=0.6)

s1.selected.js_on_change(
s1.selected.js_on_change( # type: ignore
'indices',
CustomJS(
args=dict(s1=s1, s2=s2),
Expand Down Expand Up @@ -68,7 +70,7 @@ async def serve(q: Q):
# Serialize the plot as JSON.
# See https://docs.bokeh.org/en/latest/docs/user_guide/embed.html#json-items
plot_id = 'my_plot'
plot_data = json.dumps(json_item(layout, plot_id))
plot_data = json.dumps(json_item(layout, ID(plot_id)))

q.page['meta'] = ui.meta_card(
box='',
Expand Down
5 changes: 4 additions & 1 deletion py/examples/plot_bokeh_script.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
# ---

import json

from bokeh.core.types import ID
from h2o_wave import site, ui
from bokeh.resources import CDN
from bokeh.plotting import figure
Expand All @@ -21,7 +23,8 @@
# Serialize the plot as JSON.
# See https://docs.bokeh.org/en/latest/docs/user_guide/embed.html#json-items
plot_id = 'my_plot'
plot_data = json.dumps(json_item(plot, plot_id))
plot_data = json.dumps(json_item(plot, ID(plot_id)))


page = site['/demo']

Expand Down
4 changes: 2 additions & 2 deletions py/examples/plot_events_routing.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@
# Handle #events on a #plot card using routing.
# ---
from h2o_wave import main, app, on, run_on, Q, ui, data

import typing

@on('pricing.select_marks')
async def show_selected_marks(q: Q, marks: any):
async def show_selected_marks(q: Q, marks: typing.Any):
q.page['details'].content = f'You selected {marks}'
await q.page.save()

Expand Down
4 changes: 3 additions & 1 deletion py/examples/plot_matplotlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,12 @@ async def serve(q: Q):

# Render plot
plt.figure(figsize=(2, 2))
# Generate random RGB colors for each point
colors = [(float(r), float(g), float(b)) for r, g, b in np.random.rand(n, 3)]
plt.scatter(
np.random.rand(n), np.random.rand(n),
s=(30 * np.random.rand(n)) ** 2,
c=np.random.rand(n),
c=colors,
alpha=q.client.alpha / 100.0
)
image_filename = f'{str(uuid.uuid4())}.png'
Expand Down
2 changes: 1 addition & 1 deletion py/examples/plot_plotly.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
# ---

import numpy as np
from plotly import graph_objects as go
from plotly import graph_objects as go # type: ignore
from plotly import io as pio

from h2o_wave import ui, main, app, Q
Expand Down
2 changes: 1 addition & 1 deletion py/examples/plot_theme.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
# ---
import random

from .synth import FakeTimeSeries, FakeMultiTimeSeries, FakeCategoricalSeries, FakeMultiCategoricalSeries, FakeScatter
from .synth import FakeTimeSeries, FakeMultiTimeSeries, FakeCategoricalSeries, FakeMultiCategoricalSeries, FakeScatter # type: ignore
from h2o_wave import main, app, data, Q, ui


Expand Down
2 changes: 1 addition & 1 deletion py/examples/site_async.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
# Update any page on a site from within an app using an `AsyncSite` instance.
# #site
# ---
from .synth import FakePercent
from .synth import FakePercent # type: ignore
from h2o_wave import Q, app, main, ui, AsyncSite

site = AsyncSite()
Expand Down
13 changes: 7 additions & 6 deletions py/examples/synth.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import datetime
import random
from typing import Optional


class FakeSeries:
def __init__(self, min=0.0, max=100.0, variation=10.0, start: int = None):
def __init__(self, min=0.0, max=100.0, variation=10.0, start: Optional[int] = None):
self.min = min
self.max = max
self.variation = variation
Expand All @@ -21,7 +22,7 @@ def next(self):


class FakeTimeSeries:
def __init__(self, min=0.0, max=100.0, variation=10.0, start: int = None, delta_days=1):
def __init__(self, min=0.0, max=100.0, variation=10.0, start: Optional[int] = None, delta_days=1):
self.series = FakeSeries(min, max, variation, start)
self.delta_days = delta_days
self.date = datetime.datetime.utcnow() - datetime.timedelta(days=10 * 365)
Expand All @@ -33,7 +34,7 @@ def next(self):


class FakeMultiTimeSeries:
def __init__(self, min=0.0, max=100.0, variation=10.0, start: int = None, delta_days=1, groups=5):
def __init__(self, min=0.0, max=100.0, variation=10.0, start: Optional[int] = None, delta_days=1, groups=5):
self.series = [(f'G{c + 1}', FakeTimeSeries(min, max, variation, start, delta_days)) for c in range(groups)]

def next(self):
Expand All @@ -45,7 +46,7 @@ def next(self):


class FakeCategoricalSeries:
def __init__(self, min=0.0, max=100.0, variation=10.0, start: int = None):
def __init__(self, min=0.0, max=100.0, variation=10.0, start: Optional[int] = None):
self.series = FakeSeries(min, max, variation, start)
self.i = 0

Expand All @@ -56,7 +57,7 @@ def next(self):


class FakeMultiCategoricalSeries:
def __init__(self, min=0.0, max=100.0, variation=10.0, start: int = None, groups=5):
def __init__(self, min=0.0, max=100.0, variation=10.0, start: Optional[int] = None, groups=5):
self.series = [(f'G{c + 1}', FakeCategoricalSeries(min, max, variation, start)) for c in range(groups)]

def next(self):
Expand All @@ -68,7 +69,7 @@ def next(self):


class FakeScatter:
def __init__(self, min=0.0, max=100.0, variation=10.0, start: int = None):
def __init__(self, min=0.0, max=100.0, variation=10.0, start: Optional[int] = None):
self.x = FakeSeries(min, max, variation, start)
self.y = FakeSeries(min, max, variation, start)

Expand Down
5 changes: 3 additions & 2 deletions py/examples/table_filter_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,9 @@ def df_to_rows(df: pd.DataFrame):


def search_df(df: pd.DataFrame, term: str):
str_cols = df.select_dtypes(include=[object])
return df[str_cols.apply(lambda column: column.str.contains(term, case=False, na=False)).any(axis=1)]
str_cols = df.select_dtypes(include=['object']).columns
return df[df[str_cols].apply(lambda column: column.str.contains(term, case=False, na=False)).any(axis=1)]
Comment on lines +31 to +32
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What mypy err does this resolve?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

table_filter_backend.py:31: error: List item 0 has incompatible type "type[object]"; expected "str" [list-item]

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The visual effect looks the same




@app('/demo')
Expand Down
4 changes: 3 additions & 1 deletion py/examples/table_markdown_pandas.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,13 @@
# ---
from h2o_wave import site, ui
import pandas as pd
import numpy as np


df = pd.DataFrame({'A': 1.,
'B': pd.Timestamp('20130102'),
'C': pd.Series(1, index=list(range(4)), dtype='float32'),
'D': pd.np.array([3] * 4, dtype='int32'),
'D': np.array([3] * 4, dtype='int32'),
7460m marked this conversation as resolved.
Show resolved Hide resolved
'E': pd.Categorical(["test", "train", "test", "train"]),
'F': 'foo'})

Expand Down
8 changes: 4 additions & 4 deletions py/examples/table_pagination.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
# ---

import os
from typing import Dict, List
from typing import Optional, Dict, List
from h2o_wave import main, app, Q, ui
from copy import deepcopy
import csv
Expand All @@ -17,12 +17,12 @@ def __init__(self, text: str, status: str):
self.status = status


all_rows = [Issue(text=i + 1, status=('Closed' if i % 2 == 0 else 'Open')) for i in range(100)]
all_rows = [Issue(text=str(i + 1), status=('Closed' if i % 2 == 0 else 'Open')) for i in range(100)]
rows_per_page = 10
total_rows = len(all_rows)


def get_rows(base: List, sort: Dict[str, bool] = None, search: Dict = None, filters: Dict[str, List[str]] = None) -> List:
def get_rows(base: List, sort: Optional[Dict[str, bool]] = None, search: Optional[Dict] = None, filters: Optional[Dict[str, List[str]]] = None) -> List:
# Make a deep copy in order to not mutate the original `all_issues` which serves as our baseline.
rows = deepcopy(base)

Expand All @@ -37,7 +37,7 @@ def get_rows(base: List, sort: Dict[str, bool] = None, search: Dict = None, filt
rows = [row for row in rows if any(search_val in str(getattr(row, col)).lower() for col in cols)]
# Filter out rows that do not contain filtered column value.
if filters:
for col, filters in filters.items():
for col, filters in filters.items(): # type: ignore
rows = [row for row in rows if not filters or any(f in getattr(row, col) for f in filters)]

return rows
Expand Down
Loading