Skip to content

Commit

Permalink
Refactoring Part 3 + auto formatting w/ black
Browse files Browse the repository at this point in the history
  • Loading branch information
jtyliu committed Mar 4, 2022
1 parent effc571 commit ce154f3
Show file tree
Hide file tree
Showing 19 changed files with 1,789 additions and 1,613 deletions.
21 changes: 10 additions & 11 deletions Main.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,24 +15,23 @@
def main():
# https://github.com/cheran-senthil/TLE/blob/bae59c2de6a2313be4a6ba4a5a5cbba81352e229/tle/__main__.py
dotenv.load_dotenv()
BOT_TOKEN = os.environ.get('JOMD_BOT_TOKEN')
BOT_TOKEN = os.environ.get("JOMD_BOT_TOKEN")

if not BOT_TOKEN:
logger.critical('Missing bot token')
logger.critical("Missing bot token")
return

pref = '+'
bot = lightbulb.BotApp(token=BOT_TOKEN, prefix=pref,
banner=None,
intents=hikari.Intents.ALL,
default_enabled_guilds=707067613993500692)
pref = "+"
bot = lightbulb.BotApp(
token=BOT_TOKEN, prefix=pref, banner=None, intents=hikari.Intents.ALL, default_enabled_guilds=707067613993500692
)

# bot.load_extensions_from('./extensions/')
# TESTING
extensions = ['admin', 'meta', 'gitgud', 'handles', 'user']
extensions = ["admin", "meta", "gitgud", "handles", "user", "plot"]
for extension in extensions:
bot.load_extensions(f'extensions.{extension}')
logger.debug('Extensions loaded: %s', ', '.join(bot.extensions))
bot.load_extensions(f"extensions.{extension}")
logger.debug("Extensions loaded: %s", ", ".join(bot.extensions))

# Get preliminary data
if session.query(Problem_DB).count() == 0:
Expand All @@ -46,5 +45,5 @@ def main():
bot.run()


if __name__ == '__main__':
if __name__ == "__main__":
main()
4 changes: 3 additions & 1 deletion alembic/env.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
# add your model's MetaData object here
# for 'autogenerate' support
from utils.db import Base

# target_metadata = mymodel.Base.metadata
target_metadata = Base.metadata

Expand Down Expand Up @@ -65,7 +66,8 @@ def run_migrations_online():

with connectable.connect() as connection:
context.configure(
connection=connection, target_metadata=target_metadata,
connection=connection,
target_metadata=target_metadata,
render_as_batch=True,
)

Expand Down
560 changes: 331 additions & 229 deletions alembic/versions/2535204cd05a_.py

Large diffs are not rendered by default.

25 changes: 13 additions & 12 deletions alembic/versions/94b640653b2d_.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,44 +15,45 @@


class Contest(Base):
__tablename__ = 'contest'
__tablename__ = "contest"

key = sa.Column(sa.String, primary_key=True)
rankings = sa.Column(Json)
is_rated = sa.Column(sa.Boolean)
end_time = sa.Column(sa.DateTime)


class User(Base):
__tablename__ = 'user'
__tablename__ = "user"

id = sa.Column(sa.String, primary_key=True)
username = sa.Column(sa.String)
max_rating = sa.Column(sa.Integer)


# revision identifiers, used by Alembic.
revision = '94b640653b2d'
down_revision = '2535204cd05a'
revision = "94b640653b2d"
down_revision = "2535204cd05a"
branch_labels = None
depends_on = None


def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('user', sa.Column('max_rating', sa.Integer(), nullable=True))
op.add_column("user", sa.Column("max_rating", sa.Integer(), nullable=True))
bind = op.get_bind()
session = orm.Session(bind=bind)
max_rating = {}
contests = session.query(Contest).filter(Contest.is_rated == 1)\
.order_by(Contest.end_time.desc()).all()
contests = session.query(Contest).filter(Contest.is_rated == 1).order_by(Contest.end_time.desc()).all()
print("Getting max rating for every user")
for contest in contests:
for participation in contest.rankings:
username = participation['user']
if participation['new_rating'] is not None:
username = participation["user"]
if participation["new_rating"] is not None:
if username not in max_rating:
max_rating[username] = participation['new_rating']
max_rating[username] = participation["new_rating"]
else:
max_rating[username] = max(participation['new_rating'], max_rating[username])
max_rating[username] = max(participation["new_rating"], max_rating[username])

print("Adding data to max_rating column")
for user in session.query(User):
Expand All @@ -67,5 +68,5 @@ def upgrade():

def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('user', 'max_rating')
op.drop_column("user", "max_rating")
# ### end Alembic commands ###
12 changes: 6 additions & 6 deletions alembic/versions/e9b5f8adf047_remove_volatility.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,21 +10,21 @@


# revision identifiers, used by Alembic.
revision = 'e9b5f8adf047'
down_revision = '94b640653b2d'
revision = "e9b5f8adf047"
down_revision = "94b640653b2d"
branch_labels = None
depends_on = None


def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('user') as batch_op:
batch_op.drop_column('volatility')
with op.batch_alter_table("user") as batch_op:
batch_op.drop_column("volatility")
# ### end Alembic commands ###


def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('user') as batch_op:
batch_op.add_column('volatility')
with op.batch_alter_table("user") as batch_op:
batch_op.add_column("volatility")
# ### end Alembic commands ###
2 changes: 1 addition & 1 deletion extensions/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ async def on_slash_command(event: lightbulb.SlashCommandCompletionEvent) -> None
async def reload_all(ctx: lightbulb.Context) -> None:
try:
# extensions = [file.stem for file in Path('extensions').glob('*.py')]
extensions = ["admin", "meta", "gitgud", "handles", "user"]
extensions = ["admin", "meta", "gitgud", "handles", "user", "plot"]
for extension in extensions:
ctx.bot.reload_extensions(f"extensions.{extension}")
except lightbulb.ExtensionNotLoaded as e:
Expand Down
28 changes: 3 additions & 25 deletions extensions/gitgud.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from utils.gitgud import Gitgud as Gitgud_utils
from utils.query import Query
from utils.constants import SHORTHANDS, RATING_TO_POINT, POINT_VALUES
from utils.jomd_common import gimme_common
from utils.jomd_common import gimme_common, PointRangeConverter
from utils.db import (
session,
Problem as Problem_DB,
Expand Down Expand Up @@ -33,27 +33,9 @@
plugin = lightbulb.Plugin("GitGud")


class PointRangeConverter(base.BaseConverter[t.List[int]]):
"""Implementation of the base converter for converting arguments into a point range."""

__slots__ = ()

async def convert(self, arg: str) -> t.List[int]:
try:
if "-" in arg:
arg = arg.split("-")
if len(arg) != 2:
raise TypeError("Too many arguements, invalid range")
return list(map(int, arg))
point_high = point_low = int(arg)
return [point_high, point_low]
except ValueError:
raise TypeError("Point value is not an integer")


@plugin.command()
@lightbulb.option(
"filters", "Problem filters", t.List[str], required=False, modifier=OptionModifier.CONSUME_REST, default=[]
"filters", "Problem filters", str, required=False, modifier=OptionModifier.GREEDY, default=[]
)
@lightbulb.option(
"points",
Expand Down Expand Up @@ -83,7 +65,6 @@ async def gitgud(ctx: lightbulb.Context) -> None:
# TODO Fix converters for slash commands
points = ctx.options.points
filters = ctx.options.filters
logging.info(f"Filter: %s, Points: %s" % (filters, points))
query = Query()
gitgud_util = Gitgud_utils()
# get the user's dmoj handle
Expand Down Expand Up @@ -188,7 +169,6 @@ async def gitlog(ctx):
# paginate

pag = lightbulb.utils.EmbedPaginator()
content = ""
for idx, solved in enumerate(history):
# problem = solved.problem_id or await query.get_problem(solved.problem_id)
problem = await query.get_problem(solved.problem_id)
Expand All @@ -199,9 +179,7 @@ async def gitlog(ctx):
days_str = "yesterday"
else:
days_str = f"{days} days ago"
content += f"[{problem.name}](https://dmoj.ca/problem/{problem.code}) " f"[+{solved.point}] ({days_str})"
pag.add_line(content)
content = ""
pag.add_line(f"[{problem.name}](https://dmoj.ca/problem/{problem.code}) " f"[+{solved.point}] ({days_str})")
if idx == 100:
break

Expand Down
Loading

0 comments on commit ce154f3

Please sign in to comment.