├── app ├── __init__.py ├── api │ ├── __init__.py │ ├── endpoints │ │ ├── auth.py │ │ ├── submissions.py │ │ └── challenges.py │ └── deps.py ├── models │ ├── base.py │ ├── __init__.py │ ├── user.py │ ├── challenge.py │ └── submission.py ├── schemas │ ├── token.py │ ├── __init__.py │ ├── user.py │ ├── challenge.py │ └── submission.py ├── crud │ ├── __init__.py │ ├── user.py │ ├── submission.py │ └── challenge.py ├── core │ ├── config.py │ └── security.py ├── db │ └── session.py ├── templates │ ├── login.html │ ├── register.html │ ├── create_challenge.html │ ├── base.html │ ├── submission_detail.html │ ├── edit_challenge.html │ ├── challenges.html │ ├── index.html │ ├── challenge_submissions.html │ └── challenge_detail.html ├── services │ └── judge.py └── main.py ├── static ├── js │ └── main.js └── css │ └── styles.css ├── temp └── .gitignore ├── .gitignore ├── CodeProofTheArena └── Basic.lean ├── lean-toolchain ├── alembic ├── README ├── script.py.mako ├── versions │ ├── bb314d1e428a_create_users_table.py │ ├── c8d943b1cdb2_create_submissions_table.py │ ├── d774e9296d79_create_submissions_table.py │ ├── 2d62d4517dce_update_submissions.py │ ├── 4b777e24b130_add_display_name_to_user_model.py │ ├── 3284fb1b9b67_add_theorem2_signature_to_challenges.py │ ├── 1fe89fc6a18f_add_owner_id_to_challenges.py │ ├── 5169b67d6dcc_add_proof2_and_related_fields_to_.py │ ├── 5bd0e0a04e0c_create_submissions_table.py │ └── 4701dab251fc_add_user_and_challenge_models.py └── env.py ├── run.sh ├── deploy.sh ├── dotenv.example ├── CodeProofTheArena.lean ├── .github └── workflows │ └── lean_action_ci.yml ├── lakefile.toml ├── pyproject.toml ├── README.md ├── lake-manifest.json ├── alembic.ini ├── scripts ├── import_challenges.py ├── easy.jsonl └── code_contests_sample_passed.jsonl └── LICENSE /app/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /static/js/main.js: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /temp/.gitignore: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /.lake 2 | -------------------------------------------------------------------------------- /app/api/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /CodeProofTheArena/Basic.lean: -------------------------------------------------------------------------------- 1 | def hello := "world" -------------------------------------------------------------------------------- /lean-toolchain: -------------------------------------------------------------------------------- 1 | leanprover/lean4:v4.14.0-rc2 2 | -------------------------------------------------------------------------------- /alembic/README: -------------------------------------------------------------------------------- 1 | Generic single-database configuration. -------------------------------------------------------------------------------- /run.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | poetry run uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload 3 | -------------------------------------------------------------------------------- /deploy.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | poetry run uvicorn app.main:app --host 0.0.0.0 --port 8000 --workers 4 3 | -------------------------------------------------------------------------------- /app/models/base.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy.ext.declarative import declarative_base 2 | 3 | Base = declarative_base() -------------------------------------------------------------------------------- /app/models/__init__.py: -------------------------------------------------------------------------------- 1 | from .user import User 2 | from .challenge import Challenge 3 | from .submission import Submission 4 | 5 | -------------------------------------------------------------------------------- /dotenv.example: -------------------------------------------------------------------------------- 1 | DATABASE_URL="postgresql://coding_challenge_user:LocalPass@localhost/coding_challenge_db" 2 | SECRET_KEY="GasStationSecret" 3 | 4 | -------------------------------------------------------------------------------- /CodeProofTheArena.lean: -------------------------------------------------------------------------------- 1 | -- This module serves as the root of the `CodeProofTheArena` library. 2 | -- Import modules here that should be built as part of the library. 3 | import CodeProofTheArena.Basic -------------------------------------------------------------------------------- /app/schemas/token.py: -------------------------------------------------------------------------------- 1 | from pydantic import BaseModel 2 | 3 | class Token(BaseModel): 4 | access_token: str 5 | token_type: str 6 | 7 | class TokenPayload(BaseModel): 8 | sub: int | None = None 9 | 10 | -------------------------------------------------------------------------------- /app/crud/__init__.py: -------------------------------------------------------------------------------- 1 | from .user import get_user, get_user_by_email, get_users, create_user, authenticate_user, is_active, is_superuser 2 | from .challenge import get_challenge, get_challenges, create_challenge, update_challenge, delete_challenge 3 | from .submission import get_submission 4 | 5 | -------------------------------------------------------------------------------- /.github/workflows/lean_action_ci.yml: -------------------------------------------------------------------------------- 1 | name: Lean Action CI 2 | 3 | on: 4 | push: 5 | pull_request: 6 | workflow_dispatch: 7 | 8 | jobs: 9 | build: 10 | runs-on: ubuntu-latest 11 | 12 | steps: 13 | - uses: actions/checkout@v4 14 | - uses: leanprover/lean-action@v1 15 | -------------------------------------------------------------------------------- /app/schemas/__init__.py: -------------------------------------------------------------------------------- 1 | from .user import User, UserCreate, UserInDB 2 | from .challenge import Challenge, ChallengeCreate, ChallengeUpdate 3 | from .token import Token, TokenPayload 4 | from .submission import Submission, SubmissionInDB, SubmissionCreate, SubmissionUpdate, SubmissionResult 5 | 6 | 7 | -------------------------------------------------------------------------------- /app/core/config.py: -------------------------------------------------------------------------------- 1 | from pydantic_settings import BaseSettings 2 | 3 | class Settings(BaseSettings): 4 | DATABASE_URL: str 5 | # Add other configuration variables here 6 | SECRET_KEY: str 7 | ACCESS_TOKEN_EXPIRE_MINUTES: int = 30 8 | 9 | class Config: 10 | env_file = ".env" 11 | 12 | settings = Settings() 13 | -------------------------------------------------------------------------------- /app/db/session.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy import create_engine 2 | from sqlalchemy.orm import sessionmaker 3 | from app.core.config import settings 4 | 5 | engine = create_engine(settings.DATABASE_URL) 6 | SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) 7 | 8 | #def get_db(): 9 | # db = SessionLocal() 10 | # try: 11 | # yield db 12 | # finally: 13 | # db.close() 14 | -------------------------------------------------------------------------------- /lakefile.toml: -------------------------------------------------------------------------------- 1 | name = "CodeProofTheArena" 2 | version = "0.1.0" 3 | keywords = ["math"] 4 | defaultTargets = ["CodeProofTheArena"] 5 | 6 | [leanOptions] 7 | pp.unicode.fun = true # pretty-prints `fun a ↦ b` 8 | autoImplicit = false 9 | 10 | [[require]] 11 | name = "mathlib" 12 | scope = "leanprover-community" 13 | 14 | [[require]] 15 | name = "SafeVerify" 16 | git = "https://github.com/GasStationManager/SafeVerify.git" 17 | 18 | 19 | [[lean_lib]] 20 | name = "CodeProofTheArena" 21 | -------------------------------------------------------------------------------- /app/schemas/user.py: -------------------------------------------------------------------------------- 1 | from pydantic import BaseModel, EmailStr 2 | 3 | class UserBase(BaseModel): 4 | email: EmailStr 5 | display_name: str | None = None 6 | 7 | class UserCreate(UserBase): 8 | password: str 9 | 10 | class UserInDBBase(UserBase): 11 | id: int 12 | is_active: bool 13 | is_superuser: bool 14 | 15 | class Config: 16 | orm_mode = True 17 | 18 | class User(UserInDBBase): 19 | pass 20 | 21 | class UserInDB(UserInDBBase): 22 | hashed_password: str 23 | 24 | -------------------------------------------------------------------------------- /app/templates/login.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | 3 | {% block content %} 4 |

Login

5 | {% if error %} 6 |

{{ error }}

7 | {% endif %} 8 |
9 | 10 | 11 | 12 | 13 | 14 |
15 |

Don't have an account yet? Please register to create one.

16 | {% endblock %} 17 | 18 | -------------------------------------------------------------------------------- /app/models/user.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy import Boolean, Column, Integer, String 2 | from sqlalchemy.orm import relationship 3 | from app.models.base import Base 4 | 5 | class User(Base): 6 | __tablename__ = "users" 7 | 8 | id = Column(Integer, primary_key=True, index=True) 9 | email = Column(String, unique=True, index=True) 10 | display_name = Column(String) 11 | hashed_password = Column(String) 12 | is_active = Column(Boolean(), default=True) 13 | is_superuser = Column(Boolean(), default=False) 14 | 15 | challenges = relationship("Challenge", back_populates="owner") 16 | submissions = relationship("Submission", back_populates="user") 17 | -------------------------------------------------------------------------------- /app/schemas/challenge.py: -------------------------------------------------------------------------------- 1 | from pydantic import BaseModel 2 | from typing import Optional 3 | 4 | class ChallengeBase(BaseModel): 5 | title: str 6 | description: str 7 | function_signature: str 8 | theorem_signature: str 9 | theorem2_signature: Optional[str] = None 10 | 11 | class ChallengeCreate(ChallengeBase): 12 | pass 13 | 14 | class ChallengeUpdate(ChallengeBase): 15 | pass 16 | 17 | class ChallengeInDBBase(ChallengeBase): 18 | id: int 19 | owner_id: Optional[int] = None 20 | class Config: 21 | orm_mode = True 22 | 23 | class Challenge(ChallengeInDBBase): 24 | pass 25 | 26 | class ChallengeInDB(ChallengeInDBBase): 27 | pass 28 | 29 | -------------------------------------------------------------------------------- /app/models/challenge.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy import Column, Integer, String, Text, ForeignKey 2 | from sqlalchemy.orm import relationship 3 | from app.models.base import Base 4 | 5 | class Challenge(Base): 6 | __tablename__ = "challenges" 7 | 8 | id = Column(Integer, primary_key=True, index=True) 9 | title = Column(String, index=True) 10 | description = Column(Text) 11 | function_signature = Column(String) 12 | theorem_signature = Column(String) 13 | theorem2_signature = Column(String, nullable=True) 14 | owner_id = Column(Integer, ForeignKey("users.id")) 15 | 16 | owner = relationship("User", back_populates="challenges") 17 | submissions = relationship("Submission", back_populates="challenge") 18 | -------------------------------------------------------------------------------- /alembic/script.py.mako: -------------------------------------------------------------------------------- 1 | """${message} 2 | 3 | Revision ID: ${up_revision} 4 | Revises: ${down_revision | comma,n} 5 | Create Date: ${create_date} 6 | 7 | """ 8 | from typing import Sequence, Union 9 | 10 | from alembic import op 11 | import sqlalchemy as sa 12 | ${imports if imports else ""} 13 | 14 | # revision identifiers, used by Alembic. 15 | revision: str = ${repr(up_revision)} 16 | down_revision: Union[str, None] = ${repr(down_revision)} 17 | branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)} 18 | depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)} 19 | 20 | 21 | def upgrade() -> None: 22 | ${upgrades if upgrades else "pass"} 23 | 24 | 25 | def downgrade() -> None: 26 | ${downgrades if downgrades else "pass"} 27 | -------------------------------------------------------------------------------- /alembic/versions/bb314d1e428a_create_users_table.py: -------------------------------------------------------------------------------- 1 | """Create users table 2 | 3 | Revision ID: bb314d1e428a 4 | Revises: 4701dab251fc 5 | Create Date: 2024-09-28 06:14:37.940984 6 | 7 | """ 8 | from typing import Sequence, Union 9 | 10 | from alembic import op 11 | import sqlalchemy as sa 12 | 13 | 14 | # revision identifiers, used by Alembic. 15 | revision: str = 'bb314d1e428a' 16 | down_revision: Union[str, None] = '4701dab251fc' 17 | branch_labels: Union[str, Sequence[str], None] = None 18 | depends_on: Union[str, Sequence[str], None] = None 19 | 20 | 21 | def upgrade() -> None: 22 | # ### commands auto generated by Alembic - please adjust! ### 23 | pass 24 | # ### end Alembic commands ### 25 | 26 | 27 | def downgrade() -> None: 28 | # ### commands auto generated by Alembic - please adjust! ### 29 | pass 30 | # ### end Alembic commands ### 31 | -------------------------------------------------------------------------------- /alembic/versions/c8d943b1cdb2_create_submissions_table.py: -------------------------------------------------------------------------------- 1 | """Create submissions table 2 | 3 | Revision ID: c8d943b1cdb2 4 | Revises: d774e9296d79 5 | Create Date: 2024-09-28 18:14:06.123364 6 | 7 | """ 8 | from typing import Sequence, Union 9 | 10 | from alembic import op 11 | import sqlalchemy as sa 12 | 13 | 14 | # revision identifiers, used by Alembic. 15 | revision: str = 'c8d943b1cdb2' 16 | down_revision: Union[str, None] = 'd774e9296d79' 17 | branch_labels: Union[str, Sequence[str], None] = None 18 | depends_on: Union[str, Sequence[str], None] = None 19 | 20 | 21 | def upgrade() -> None: 22 | # ### commands auto generated by Alembic - please adjust! ### 23 | pass 24 | # ### end Alembic commands ### 25 | 26 | 27 | def downgrade() -> None: 28 | # ### commands auto generated by Alembic - please adjust! ### 29 | pass 30 | # ### end Alembic commands ### 31 | -------------------------------------------------------------------------------- /alembic/versions/d774e9296d79_create_submissions_table.py: -------------------------------------------------------------------------------- 1 | """Create submissions table 2 | 3 | Revision ID: d774e9296d79 4 | Revises: 1fe89fc6a18f 5 | Create Date: 2024-09-28 08:29:45.280692 6 | 7 | """ 8 | from typing import Sequence, Union 9 | 10 | from alembic import op 11 | import sqlalchemy as sa 12 | 13 | 14 | # revision identifiers, used by Alembic. 15 | revision: str = 'd774e9296d79' 16 | down_revision: Union[str, None] = '1fe89fc6a18f' 17 | branch_labels: Union[str, Sequence[str], None] = None 18 | depends_on: Union[str, Sequence[str], None] = None 19 | 20 | 21 | def upgrade() -> None: 22 | # ### commands auto generated by Alembic - please adjust! ### 23 | pass 24 | # ### end Alembic commands ### 25 | 26 | 27 | def downgrade() -> None: 28 | # ### commands auto generated by Alembic - please adjust! ### 29 | pass 30 | # ### end Alembic commands ### 31 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [tool.poetry] 2 | name = "codeproofarena" 3 | version = "0.1.0" 4 | description = "" 5 | authors = ["Your Name "] 6 | readme = "README.md" 7 | 8 | [tool.poetry.dependencies] 9 | python = "^3.10" 10 | fastapi = "^0.115.0" 11 | uvicorn = "^0.30.6" 12 | SQLAlchemy = "^2.0.35" 13 | alembic = "^1.13.3" 14 | psycopg2-binary = "^2.9.9" 15 | pydantic = {extras = ["email"], version = "^2.9.2"} 16 | python-jose = {extras = ["cryptography"], version = "^3.3.0"} 17 | passlib = {extras = ["bcrypt"], version = "^1.7.4"} 18 | python-multipart = "^0.0.10" 19 | pydantic-settings = "^2.5.2" 20 | jinja2 = "^3.1.4" 21 | bcrypt = "3.2.0" 22 | itsdangerous = "^2.2.0" 23 | requests = "^2.32.3" 24 | 25 | 26 | [tool.poetry.group.dev.dependencies] 27 | pytest = "^8.3.3" 28 | pytest-asyncio = "^0.24.0" 29 | httpx = "^0.27.2" 30 | 31 | [build-system] 32 | requires = ["poetry-core"] 33 | build-backend = "poetry.core.masonry.api" 34 | -------------------------------------------------------------------------------- /alembic/versions/2d62d4517dce_update_submissions.py: -------------------------------------------------------------------------------- 1 | """update submissions 2 | 3 | Revision ID: 2d62d4517dce 4 | Revises: 5bd0e0a04e0c 5 | Create Date: 2024-09-28 22:36:18.462748 6 | 7 | """ 8 | from typing import Sequence, Union 9 | 10 | from alembic import op 11 | import sqlalchemy as sa 12 | 13 | 14 | # revision identifiers, used by Alembic. 15 | revision: str = '2d62d4517dce' 16 | down_revision: Union[str, None] = '5bd0e0a04e0c' 17 | branch_labels: Union[str, Sequence[str], None] = None 18 | depends_on: Union[str, Sequence[str], None] = None 19 | 20 | 21 | def upgrade() -> None: 22 | # ### commands auto generated by Alembic - please adjust! ### 23 | op.add_column('submissions', sa.Column('feedback', sa.Text(), nullable=True)) 24 | # ### end Alembic commands ### 25 | 26 | 27 | def downgrade() -> None: 28 | # ### commands auto generated by Alembic - please adjust! ### 29 | op.drop_column('submissions', 'feedback') 30 | # ### end Alembic commands ### 31 | -------------------------------------------------------------------------------- /alembic/versions/4b777e24b130_add_display_name_to_user_model.py: -------------------------------------------------------------------------------- 1 | """Add display_name to User model 2 | 3 | Revision ID: 4b777e24b130 4 | Revises: 2d62d4517dce 5 | Create Date: 2024-09-30 07:34:06.599976 6 | 7 | """ 8 | from typing import Sequence, Union 9 | 10 | from alembic import op 11 | import sqlalchemy as sa 12 | 13 | 14 | # revision identifiers, used by Alembic. 15 | revision: str = '4b777e24b130' 16 | down_revision: Union[str, None] = '2d62d4517dce' 17 | branch_labels: Union[str, Sequence[str], None] = None 18 | depends_on: Union[str, Sequence[str], None] = None 19 | 20 | 21 | def upgrade() -> None: 22 | # ### commands auto generated by Alembic - please adjust! ### 23 | op.add_column('users', sa.Column('display_name', sa.String(), nullable=True)) 24 | # ### end Alembic commands ### 25 | 26 | 27 | def downgrade() -> None: 28 | # ### commands auto generated by Alembic - please adjust! ### 29 | op.drop_column('users', 'display_name') 30 | # ### end Alembic commands ### 31 | -------------------------------------------------------------------------------- /app/models/submission.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy import Column, Integer, String, Text, ForeignKey, DateTime, Boolean 2 | from sqlalchemy.orm import relationship 3 | from sqlalchemy.sql import func 4 | from app.models.base import Base 5 | 6 | class Submission(Base): 7 | __tablename__ = "submissions" 8 | 9 | id = Column(Integer, primary_key=True, index=True) 10 | challenge_id = Column(Integer, ForeignKey("challenges.id")) 11 | user_id = Column(Integer, ForeignKey("users.id")) 12 | code = Column(Text) 13 | proof = Column(Text) 14 | proof2 = Column(Text, nullable=True) 15 | is_correct = Column(Boolean, default=False) 16 | is_correct2 = Column(Boolean, default=False) 17 | feedback = Column(Text) 18 | feedback2 = Column(Text, nullable=True) 19 | submitted_at = Column(DateTime(timezone=True), server_default=func.now()) 20 | 21 | challenge = relationship("Challenge", back_populates="submissions") 22 | user = relationship("User", back_populates="submissions") 23 | 24 | -------------------------------------------------------------------------------- /app/templates/register.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | 3 | {% block content %} 4 |

Register

5 | {% if error %} 6 |

{{ error }}

7 | {% endif %} 8 |
9 |
10 | 11 | 12 |
13 |
14 | 15 | 16 |
17 |
18 | 19 | 20 |
21 |
22 | 23 | 24 |
25 | 26 |
27 |

Already have an account? Login here

28 | {% endblock %} 29 | 30 | -------------------------------------------------------------------------------- /alembic/versions/3284fb1b9b67_add_theorem2_signature_to_challenges.py: -------------------------------------------------------------------------------- 1 | """Add theorem2_signature to challenges 2 | 3 | Revision ID: 3284fb1b9b67 4 | Revises: 4b777e24b130 5 | Create Date: 2024-11-13 22:38:20.214381 6 | 7 | """ 8 | from typing import Sequence, Union 9 | 10 | from alembic import op 11 | import sqlalchemy as sa 12 | 13 | 14 | # revision identifiers, used by Alembic. 15 | revision: str = '3284fb1b9b67' 16 | down_revision: Union[str, None] = '4b777e24b130' 17 | branch_labels: Union[str, Sequence[str], None] = None 18 | depends_on: Union[str, Sequence[str], None] = None 19 | 20 | 21 | def upgrade() -> None: 22 | # ### commands auto generated by Alembic - please adjust! ### 23 | op.add_column('challenges', sa.Column('theorem2_signature', sa.String(), nullable=True)) 24 | # ### end Alembic commands ### 25 | 26 | 27 | def downgrade() -> None: 28 | # ### commands auto generated by Alembic - please adjust! ### 29 | op.drop_column('challenges', 'theorem2_signature') 30 | # ### end Alembic commands ### 31 | -------------------------------------------------------------------------------- /alembic/versions/1fe89fc6a18f_add_owner_id_to_challenges.py: -------------------------------------------------------------------------------- 1 | """Add owner_id to challenges 2 | 3 | Revision ID: 1fe89fc6a18f 4 | Revises: bb314d1e428a 5 | Create Date: 2024-09-28 07:16:50.405221 6 | 7 | """ 8 | from typing import Sequence, Union 9 | 10 | from alembic import op 11 | import sqlalchemy as sa 12 | 13 | 14 | # revision identifiers, used by Alembic. 15 | revision: str = '1fe89fc6a18f' 16 | down_revision: Union[str, None] = 'bb314d1e428a' 17 | branch_labels: Union[str, Sequence[str], None] = None 18 | depends_on: Union[str, Sequence[str], None] = None 19 | 20 | 21 | def upgrade() -> None: 22 | # ### commands auto generated by Alembic - please adjust! ### 23 | op.add_column('challenges', sa.Column('owner_id', sa.Integer(), nullable=True)) 24 | op.create_foreign_key(None, 'challenges', 'users', ['owner_id'], ['id']) 25 | # ### end Alembic commands ### 26 | 27 | 28 | def downgrade() -> None: 29 | # ### commands auto generated by Alembic - please adjust! ### 30 | op.drop_constraint(None, 'challenges', type_='foreignkey') 31 | op.drop_column('challenges', 'owner_id') 32 | # ### end Alembic commands ### 33 | -------------------------------------------------------------------------------- /app/schemas/submission.py: -------------------------------------------------------------------------------- 1 | from pydantic import BaseModel 2 | from datetime import datetime 3 | from typing import Optional 4 | 5 | class SubmissionBase(BaseModel): 6 | code: str 7 | proof: str 8 | proof2: Optional[str] = None 9 | 10 | class SubmissionCreate(SubmissionBase): 11 | challenge_id: int 12 | 13 | class SubmissionUpdate(SubmissionBase): 14 | is_correct: bool | None = None 15 | is_correct2: bool | None = None 16 | feedback: str | None = None 17 | feedback2: str | None = None 18 | 19 | class SubmissionInDBBase(SubmissionBase): 20 | id: int 21 | challenge_id: int 22 | user_id: int 23 | is_correct: bool 24 | is_correct2: Optional[bool] 25 | feedback: str | None = None 26 | feedback2: str | None = None 27 | submitted_at: datetime 28 | 29 | class Config: 30 | orm_mode = True 31 | 32 | class Submission(SubmissionInDBBase): 33 | pass 34 | 35 | class SubmissionInDB(SubmissionInDBBase): 36 | pass 37 | 38 | class SubmissionResult(BaseModel): 39 | is_correct: bool 40 | is_correct2: Optional[bool] 41 | feedback: str 42 | feedback2: Optional[str] 43 | -------------------------------------------------------------------------------- /app/templates/create_challenge.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | 3 | {% block content %} 4 |

Create New Challenge

5 | {% if error %} 6 |

{{ error }}

7 | {% endif %} 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | {% endblock %} 23 | 24 | -------------------------------------------------------------------------------- /app/templates/base.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | {% block title %}Code with Proof: Arena{% endblock %} 7 | 8 | 9 | 10 |
11 | 23 |
24 |
25 | {% block content %}{% endblock %} 26 |
27 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /alembic/versions/5169b67d6dcc_add_proof2_and_related_fields_to_.py: -------------------------------------------------------------------------------- 1 | """Add proof2 and related fields to submissions 2 | 3 | Revision ID: 5169b67d6dcc 4 | Revises: 3284fb1b9b67 5 | Create Date: 2024-11-13 23:09:42.476701 6 | 7 | """ 8 | from typing import Sequence, Union 9 | 10 | from alembic import op 11 | import sqlalchemy as sa 12 | 13 | 14 | # revision identifiers, used by Alembic. 15 | revision: str = '5169b67d6dcc' 16 | down_revision: Union[str, None] = '3284fb1b9b67' 17 | branch_labels: Union[str, Sequence[str], None] = None 18 | depends_on: Union[str, Sequence[str], None] = None 19 | 20 | 21 | def upgrade() -> None: 22 | # ### commands auto generated by Alembic - please adjust! ### 23 | op.add_column('submissions', sa.Column('proof2', sa.Text(), nullable=True)) 24 | op.add_column('submissions', sa.Column('is_correct2', sa.Boolean(), nullable=True)) 25 | op.add_column('submissions', sa.Column('feedback2', sa.Text(), nullable=True)) 26 | # ### end Alembic commands ### 27 | 28 | 29 | def downgrade() -> None: 30 | # ### commands auto generated by Alembic - please adjust! ### 31 | op.drop_column('submissions', 'feedback2') 32 | op.drop_column('submissions', 'is_correct2') 33 | op.drop_column('submissions', 'proof2') 34 | # ### end Alembic commands ### 35 | -------------------------------------------------------------------------------- /app/templates/submission_detail.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | 3 | {% block content %} 4 |

Submission Details

5 |

Back to Submissions List

6 | 7 |

Challenge: {{ submission.challenge.title }}

8 |

Submitted by: {{ submission.user.display_name }}

9 |

Submitted at: {{ submission.submitted_at.strftime('%Y-%m-%d %H:%M:%S') }}

10 | 11 |

Code:

12 |
{{ submission.challenge.function_signature }}
13 |
{{ submission.code }}
14 | 15 |

First Theorem Proof:

16 |
{{ submission.challenge.theorem_signature }}
17 |
{{ submission.proof }}
18 | 19 |

Status: {{ "Correct" if submission.is_correct else "Incorrect" }}

20 |

Feedback:

21 |
{{ submission.feedback }}
22 | 23 | {% if submission.challenge.theorem2_signature %} 24 |

Second Theorem Proof:

25 |
{{ submission.challenge.theorem2_signature }}
26 |
{{ submission.proof2 }}
27 |

Status: {{ "Correct" if submission.is_correct2 else "Incorrect" }}

28 | {% if submission.feedback2 %} 29 |

Feedback:

30 |
{{ submission.feedback2 }}
31 | {% endif %} 32 | {% endif %} 33 | 34 | {% endblock %} 35 | 36 | -------------------------------------------------------------------------------- /app/templates/edit_challenge.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | 3 | {% block content %} 4 |

Edit Challenge

5 | 6 | {% if error %} 7 |

{{ error }}

8 | {% endif %} 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | Cancel 23 |
24 | {% endblock %} 25 | -------------------------------------------------------------------------------- /app/templates/challenges.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | 3 | {% block content %} 4 |

Challenges

5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | {% for challenge, creator_name, total_submissions, successful_submissions in challenges_data %} 18 | 19 | 20 | 21 | 22 | 23 | 30 | 31 | {% endfor %} 32 | 33 |
TitleCreatorSubmissionsSuccessfulSuccess Rate
{{ challenge.title }}{{ creator_name }}{{ total_submissions }}{{ successful_submissions }} 24 | {% if total_submissions > 0 %} 25 | {{ "%.1f"|format(successful_submissions * 100 / total_submissions) }}% 26 | {% else %} 27 | N/A 28 | {% endif %} 29 |
34 | 35 | {% if not challenges_data %} 36 |

No challenges available.

37 | {% endif %} 38 | 39 | {% if user %} 40 |
41 | Create New Challenge 42 |
43 | {% endif %} 44 | {% endblock %} 45 | 46 | -------------------------------------------------------------------------------- /app/core/security.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime, timedelta 2 | from typing import Any, Union 3 | from fastapi import HTTPException, status 4 | 5 | from jose import jwt, JWTError 6 | from passlib.context import CryptContext 7 | 8 | from app.core.config import settings 9 | 10 | pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") 11 | 12 | ALGORITHM = "HS256" 13 | 14 | def create_access_token(subject: Union[str, Any], expires_delta: timedelta | None = None) -> str: 15 | if expires_delta: 16 | expire = datetime.utcnow() + expires_delta 17 | else: 18 | expire = datetime.utcnow() + timedelta( 19 | minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES 20 | ) 21 | to_encode = {"exp": expire, "sub": str(subject)} 22 | encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=ALGORITHM) 23 | return encoded_jwt 24 | 25 | def decode_access_token(token: str) -> dict: 26 | try: 27 | return jwt.decode(token, settings.SECRET_KEY, algorithms=[ALGORITHM]) 28 | except JWTError: 29 | raise HTTPException( 30 | status_code=status.HTTP_401_UNAUTHORIZED, 31 | detail="Could not validate credentials", 32 | ) 33 | 34 | def verify_password(plain_password: str, hashed_password: str) -> bool: 35 | return pwd_context.verify(plain_password, hashed_password) 36 | 37 | def get_password_hash(password: str) -> str: 38 | return pwd_context.hash(password) 39 | 40 | -------------------------------------------------------------------------------- /app/templates/index.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | 3 | {% block content %} 4 |

Code with Proofs: The Arena

5 |

Test your Lean 4 skills with our coding challenges! 6 | Each problem contains a description, a function sigature to be implemented, and a formal specification in the form of theorem statements to be proved. 7 | You submit code and proof, and suceed if they pass the Lean proof checker.

8 | 9 |

The purpose of this website is to serve as a platform to crowdsource efforts to create data on code-with-proof problems and solutions, including problem-only data as well as problem-with-solution data, both human-created and machine-created. And as a platform to share this data with the open-source community, for the purpose of training open-source coding models. 10 | For more details, check out our essay A Proposal for Safe and Hallucination-free Coding AI.

11 | 12 |

Both web interface and API endpoints are available. API documentation available with Swagger UI at /docs, 13 | with Redoc at /redoc. 14 | The data made available through this site is licenced under Creative Commons Attribution-NonCommercial-ShareAlike (CC BY-NC-SA). 15 | 16 |

The code for this site is open sourced on GitHub.

17 | 18 | View Challenges 19 | {% endblock %} 20 | 21 | -------------------------------------------------------------------------------- /app/crud/user.py: -------------------------------------------------------------------------------- 1 | from typing import Optional 2 | from sqlalchemy.orm import Session 3 | from sqlalchemy.exc import IntegrityError 4 | 5 | from app.core.security import get_password_hash, verify_password 6 | from app.models.user import User 7 | from app.schemas.user import UserCreate 8 | 9 | 10 | def get_user(db: Session, user_id: int): 11 | return db.query(User).filter(User.id == user_id).first() 12 | 13 | def get_user_by_email(db: Session, email: str) -> Optional[User]: 14 | return db.query(User).filter(User.email == email).first() 15 | 16 | def get_users(db: Session, skip: int = 0, limit: int = 100): 17 | return db.query(User).offset(skip).limit(limit).all() 18 | 19 | 20 | def create_user(db: Session, user: UserCreate) -> User: 21 | db_user = User( 22 | email=user.email, 23 | display_name=user.display_name or user.email.split('@')[0], # Use part of email as default display name 24 | hashed_password=get_password_hash(user.password), 25 | is_superuser=False, 26 | ) 27 | db.add(db_user) 28 | try: 29 | db.commit() 30 | db.refresh(db_user) 31 | except IntegrityError: 32 | db.rollback() 33 | raise ValueError("Email already registered") 34 | return db_user 35 | 36 | def authenticate_user(db: Session, email: str, password: str) -> Optional[User]: 37 | user = get_user_by_email(db, email) 38 | if not user: 39 | return None 40 | if not verify_password(password, user.hashed_password): 41 | return None 42 | return user 43 | 44 | 45 | def is_active(user: User) -> bool: 46 | return user.is_active 47 | 48 | def is_superuser(user: User) -> bool: 49 | return user.is_superuser 50 | -------------------------------------------------------------------------------- /alembic/versions/5bd0e0a04e0c_create_submissions_table.py: -------------------------------------------------------------------------------- 1 | """Create submissions table 2 | 3 | Revision ID: 5bd0e0a04e0c 4 | Revises: c8d943b1cdb2 5 | Create Date: 2024-09-28 18:21:11.190538 6 | 7 | """ 8 | from typing import Sequence, Union 9 | 10 | from alembic import op 11 | import sqlalchemy as sa 12 | 13 | 14 | # revision identifiers, used by Alembic. 15 | revision: str = '5bd0e0a04e0c' 16 | down_revision: Union[str, None] = 'c8d943b1cdb2' 17 | branch_labels: Union[str, Sequence[str], None] = None 18 | depends_on: Union[str, Sequence[str], None] = None 19 | 20 | 21 | def upgrade() -> None: 22 | # ### commands auto generated by Alembic - please adjust! ### 23 | op.create_table('submissions', 24 | sa.Column('id', sa.Integer(), nullable=False), 25 | sa.Column('challenge_id', sa.Integer(), nullable=True), 26 | sa.Column('user_id', sa.Integer(), nullable=True), 27 | sa.Column('code', sa.Text(), nullable=True), 28 | sa.Column('proof', sa.Text(), nullable=True), 29 | sa.Column('is_correct', sa.Boolean(), nullable=True), 30 | sa.Column('submitted_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=True), 31 | sa.ForeignKeyConstraint(['challenge_id'], ['challenges.id'], ), 32 | sa.ForeignKeyConstraint(['user_id'], ['users.id'], ), 33 | sa.PrimaryKeyConstraint('id') 34 | ) 35 | op.create_index(op.f('ix_submissions_id'), 'submissions', ['id'], unique=False) 36 | # ### end Alembic commands ### 37 | 38 | 39 | def downgrade() -> None: 40 | # ### commands auto generated by Alembic - please adjust! ### 41 | op.drop_index(op.f('ix_submissions_id'), table_name='submissions') 42 | op.drop_table('submissions') 43 | # ### end Alembic commands ### 44 | -------------------------------------------------------------------------------- /app/templates/challenge_submissions.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | 3 | {% block content %} 4 |

Submissions for Challenge: {{ challenge.title }}

5 |

Back to Challenge

6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | {% if challenge.theorem2_signature %} 15 | 16 | {% endif %} 17 | 18 | 19 | 20 | 21 | {% for submission in submissions %} 22 | 23 | 24 | 25 | 26 | 27 | {% if challenge.theorem2_signature %} 28 | 29 | {% endif %} 30 | 31 | 32 | {% endfor %} 33 | 34 |
Submission IDUserSubmitted AtFirst TheoremSecond TheoremAction
{{ submission.id }}{{ submission.user.display_name }}{{ submission.submitted_at.strftime('%Y-%m-%d %H:%M:%S') }}{{ "Correct" if submission.is_correct else "Incorrect" }}{{ "Correct" if submission.is_correct2 else "Incorrect" }}View Details
35 | 36 | {% if not submissions %} 37 |

No submissions yet for this challenge.

38 | {% else %} 39 | 48 | {% endif %} 49 | 50 | {% endblock %} 51 | 52 | -------------------------------------------------------------------------------- /app/api/endpoints/auth.py: -------------------------------------------------------------------------------- 1 | from datetime import timedelta 2 | from fastapi import APIRouter, Depends, HTTPException, status 3 | from fastapi.security import OAuth2PasswordRequestForm 4 | from sqlalchemy.orm import Session 5 | 6 | from app import crud 7 | from app.api import deps 8 | from app.core import security 9 | from app.core.config import settings 10 | from app.schemas.token import Token 11 | from app.schemas.user import User, UserCreate 12 | 13 | 14 | import logging 15 | 16 | router = APIRouter() 17 | logger = logging.getLogger(__name__) 18 | 19 | @router.post("/register", response_model=User) 20 | def register_user(user: UserCreate, db: Session = Depends(deps.get_db)): 21 | logger.debug(f"Attempting to register user with email: {user.email}") 22 | try: 23 | db_user = crud.user.get_user_by_email(db, email=user.email) 24 | if db_user: 25 | logger.info(f"User with email {user.email} already exists") 26 | raise HTTPException(status_code=400, detail="Email already registered") 27 | return crud.user.create_user(db=db, user=user) 28 | except Exception as e: 29 | logger.error(f"Error during user registration: {str(e)}") 30 | raise HTTPException(status_code=500, detail="Internal server error") 31 | 32 | @router.post("/login", response_model=Token) 33 | def login_for_access_token( 34 | db: Session = Depends(deps.get_db), form_data: OAuth2PasswordRequestForm = Depends() 35 | ): 36 | user = crud.user.authenticate_user(db, form_data.username, form_data.password) 37 | if not user: 38 | raise HTTPException( 39 | status_code=status.HTTP_401_UNAUTHORIZED, 40 | detail="Incorrect username or password", 41 | headers={"WWW-Authenticate": "Bearer"}, 42 | ) 43 | access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES) 44 | access_token = security.create_access_token( 45 | user.id, expires_delta=access_token_expires 46 | ) 47 | return {"access_token": access_token, "token_type": "bearer"} 48 | 49 | -------------------------------------------------------------------------------- /app/api/deps.py: -------------------------------------------------------------------------------- 1 | from typing import Generator 2 | 3 | from fastapi import Depends, HTTPException, status, Request 4 | from fastapi.security import OAuth2PasswordBearer 5 | from jose import jwt 6 | from pydantic import ValidationError 7 | from sqlalchemy.orm import Session 8 | 9 | from app import crud, models, schemas 10 | from app.core import security 11 | from app.core.config import settings 12 | from app.db.session import SessionLocal 13 | 14 | reusable_oauth2 = OAuth2PasswordBearer(tokenUrl="/api/auth/login") 15 | 16 | def get_db() -> Generator: 17 | try: 18 | db = SessionLocal() 19 | yield db 20 | finally: 21 | db.close() 22 | 23 | def get_current_user( 24 | request: Request, 25 | db: Session = Depends(get_db), 26 | token: str = Depends(reusable_oauth2) 27 | ) -> models.User: 28 | 29 | session_token = request.session.get("token") 30 | if session_token: 31 | try: 32 | payload = security.decode_access_token(session_token) 33 | user = crud.user.get_user(db, user_id=payload["sub"]) 34 | if user: 35 | return user 36 | except: 37 | pass # If session token is invalid, fall through to JWT check 38 | 39 | try: 40 | payload = jwt.decode( 41 | token, settings.SECRET_KEY, algorithms=[security.ALGORITHM] 42 | ) 43 | token_data = schemas.TokenPayload(**payload) 44 | except (jwt.JWTError, ValidationError): 45 | raise HTTPException( 46 | status_code=status.HTTP_403_FORBIDDEN, 47 | detail="Could not validate credentials", 48 | ) 49 | user = crud.user.get_user(db, user_id=token_data.sub) 50 | if not user: 51 | raise HTTPException(status_code=404, detail="User not found") 52 | return user 53 | 54 | def get_current_active_user( 55 | current_user: models.User = Depends(get_current_user), 56 | ) -> models.User: 57 | if not current_user.is_active: 58 | raise HTTPException(status_code=400, detail="Inactive user") 59 | return current_user 60 | 61 | -------------------------------------------------------------------------------- /alembic/versions/4701dab251fc_add_user_and_challenge_models.py: -------------------------------------------------------------------------------- 1 | """Add User and Challenge models 2 | 3 | Revision ID: 4701dab251fc 4 | Revises: 5 | Create Date: 2024-09-28 02:35:48.289123 6 | 7 | """ 8 | from typing import Sequence, Union 9 | 10 | from alembic import op 11 | import sqlalchemy as sa 12 | 13 | 14 | # revision identifiers, used by Alembic. 15 | revision: str = '4701dab251fc' 16 | down_revision: Union[str, None] = None 17 | branch_labels: Union[str, Sequence[str], None] = None 18 | depends_on: Union[str, Sequence[str], None] = None 19 | 20 | 21 | def upgrade() -> None: 22 | # ### commands auto generated by Alembic - please adjust! ### 23 | op.create_table('challenges', 24 | sa.Column('id', sa.Integer(), nullable=False), 25 | sa.Column('title', sa.String(), nullable=True), 26 | sa.Column('description', sa.Text(), nullable=True), 27 | sa.Column('function_signature', sa.String(), nullable=True), 28 | sa.Column('theorem_signature', sa.String(), nullable=True), 29 | sa.PrimaryKeyConstraint('id') 30 | ) 31 | op.create_index(op.f('ix_challenges_id'), 'challenges', ['id'], unique=False) 32 | op.create_index(op.f('ix_challenges_title'), 'challenges', ['title'], unique=False) 33 | op.create_table('users', 34 | sa.Column('id', sa.Integer(), nullable=False), 35 | sa.Column('email', sa.String(), nullable=True), 36 | sa.Column('hashed_password', sa.String(), nullable=True), 37 | sa.Column('is_active', sa.Boolean(), nullable=True), 38 | sa.Column('is_superuser', sa.Boolean(), nullable=True), 39 | sa.PrimaryKeyConstraint('id') 40 | ) 41 | op.create_index(op.f('ix_users_email'), 'users', ['email'], unique=True) 42 | op.create_index(op.f('ix_users_id'), 'users', ['id'], unique=False) 43 | # ### end Alembic commands ### 44 | 45 | 46 | def downgrade() -> None: 47 | # ### commands auto generated by Alembic - please adjust! ### 48 | op.drop_index(op.f('ix_users_id'), table_name='users') 49 | op.drop_index(op.f('ix_users_email'), table_name='users') 50 | op.drop_table('users') 51 | op.drop_index(op.f('ix_challenges_title'), table_name='challenges') 52 | op.drop_index(op.f('ix_challenges_id'), table_name='challenges') 53 | op.drop_table('challenges') 54 | # ### end Alembic commands ### 55 | -------------------------------------------------------------------------------- /app/api/endpoints/submissions.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, Depends, HTTPException 2 | from sqlalchemy.orm import Session 3 | from typing import List 4 | 5 | from app import crud, models, schemas 6 | from app.api import deps 7 | 8 | router = APIRouter() 9 | 10 | @router.post("/", response_model=schemas.Submission) 11 | def create_submission( 12 | submission: schemas.SubmissionCreate, 13 | db: Session = Depends(deps.get_db), 14 | current_user: models.User = Depends(deps.get_current_active_user) 15 | ): 16 | if not current_user: 17 | raise HTTPException(status_code=401, detail="Authentication required") 18 | return crud.submission.create_submission(db=db, submission=submission, user_id=current_user.id) 19 | 20 | @router.get("/challenge/{challenge_id}", response_model=List[schemas.Submission]) 21 | def read_submissions_by_challenge( 22 | challenge_id: int, 23 | skip: int = 0, 24 | limit: int = 100, 25 | db: Session = Depends(deps.get_db), 26 | ): 27 | submissions = crud.submission.get_submissions_by_challenge(db, challenge_id=challenge_id, skip=skip, limit=limit) 28 | return submissions 29 | 30 | @router.get("/user/me", response_model=List[schemas.Submission]) 31 | def read_user_submissions( 32 | skip: int = 0, 33 | limit: int = 100, 34 | db: Session = Depends(deps.get_db), 35 | current_user: models.User = Depends(deps.get_current_active_user) 36 | ): 37 | submissions = crud.submission.get_submissions_by_user(db, user_id=current_user.id, skip=skip, limit=limit) 38 | return submissions 39 | 40 | @router.get("/{submission_id}", response_model=schemas.Submission) 41 | def read_submission( 42 | submission_id: int, 43 | db: Session = Depends(deps.get_db), 44 | ): 45 | submission = crud.submission.get_submission(db, submission_id=submission_id) 46 | if submission is None: 47 | raise HTTPException(status_code=404, detail="Submission not found") 48 | return submission 49 | 50 | @router.get("/{submission_id}/result", response_model=schemas.SubmissionResult) 51 | def read_submission_result( 52 | submission_id: int, 53 | db: Session = Depends(deps.get_db) 54 | ): 55 | submission = crud.submission.get_submission(db, submission_id=submission_id) 56 | if submission is None: 57 | raise HTTPException(status_code=404, detail="Submission not found") 58 | return {"is_correct": submission.is_correct} 59 | -------------------------------------------------------------------------------- /app/crud/submission.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy.orm import Session, joinedload 2 | from sqlalchemy import desc 3 | from app.models.submission import Submission 4 | from app.schemas.submission import SubmissionCreate, SubmissionUpdate 5 | from app import crud 6 | from app.services.judge import check_lean_proof 7 | 8 | def get_submission(db: Session, submission_id: int): 9 | return db.query(Submission).options(joinedload(Submission.user), joinedload(Submission.challenge)).filter(Submission.id == submission_id).first() 10 | def get_submissions_by_challenge(db: Session, challenge_id: int, skip: int = 0, limit: int = 100): 11 | return db.query(Submission).filter(Submission.challenge_id == challenge_id)\ 12 | .options(joinedload(Submission.user))\ 13 | .order_by(desc(Submission.submitted_at))\ 14 | .offset(skip).limit(limit).all() 15 | 16 | def get_submissions_by_user(db: Session, user_id: int, skip: int = 0, limit: int = 100): 17 | return db.query(Submission).filter(Submission.user_id == user_id).offset(skip).limit(limit).all() 18 | 19 | 20 | def create_submission(db: Session, submission: SubmissionCreate, user_id: int): 21 | db_challenge = crud.challenge.get_challenge(db, challenge_id=submission.challenge_id) 22 | if not db_challenge: 23 | raise ValueError("Challenge not found") 24 | 25 | judging_result = check_lean_proof( 26 | {"function_signature": db_challenge.function_signature, "theorem_signature": db_challenge.theorem_signature, "theorem2_signature":db_challenge.theorem2_signature}, 27 | {"code": submission.code, "proof": submission.proof, "proof2": submission.proof2} 28 | ) 29 | 30 | db_submission = Submission( 31 | **submission.dict(), 32 | user_id=user_id, 33 | is_correct=judging_result["is_correct"], 34 | is_correct2=judging_result["is_correct2"], 35 | feedback=judging_result["feedback"], 36 | feedback2=judging_result["feedback2"] 37 | ) 38 | db.add(db_submission) 39 | db.commit() 40 | db.refresh(db_submission) 41 | return db_submission 42 | 43 | def update_submission(db: Session, submission_id: int, submission: SubmissionUpdate): 44 | db_submission = get_submission(db, submission_id) 45 | if db_submission: 46 | update_data = submission.dict(exclude_unset=True) 47 | for key, value in update_data.items(): 48 | setattr(db_submission, key, value) 49 | db.commit() 50 | db.refresh(db_submission) 51 | return db_submission 52 | 53 | -------------------------------------------------------------------------------- /app/templates/challenge_detail.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | 3 | {% block content %} 4 |

{{ challenge.title }}

5 | {% if user and user.id == challenge.owner_id %} 6 |
7 | Edit Challenge 8 |
9 | {% endif %} 10 | 11 |

{{ challenge.description }}

12 |

Function Signature

13 |
{{ challenge.function_signature }}
14 |

Theorem Signature

15 |
{{ challenge.theorem_signature }}
16 | {% if challenge.theorem2_signature %} 17 |

Additional Theorem Signature

18 |
{{ challenge.theorem2_signature }}
19 | {% endif %} 20 |

View All Submissions

21 | 22 | 23 | {% if user %} 24 |

Submit Your Solution

25 |

We recommend you write and edit your code in a Lean 4 environment, e.g. 26 | VS Code with the Lean4 extension, or the 27 | Lean 4 Web playground (with the signatures loaded). 28 |

29 |

You may import additional libraries. The system will scan for lines starting with import and 30 | put them at the beginning when compiling. 31 |

32 |
33 | 34 | 35 | 36 | 39 | 40 | 43 | 44 | {% if challenge.theorem2_signature %} 45 | 48 | 49 | {% endif %} 50 | 51 |
52 | {% else %} 53 |

Please log in or register to submit a solution for this challenge.

54 | {% endif %} 55 | {% endblock %} 56 | -------------------------------------------------------------------------------- /alembic/env.py: -------------------------------------------------------------------------------- 1 | from logging.config import fileConfig 2 | 3 | from sqlalchemy import engine_from_config 4 | from sqlalchemy import pool 5 | 6 | from alembic import context 7 | 8 | # Add these imports at the top 9 | from app.core.config import settings 10 | from app.models.base import Base 11 | 12 | # this is the Alembic Config object, which provides 13 | # access to the values within the .ini file in use. 14 | config = context.config 15 | 16 | 17 | 18 | 19 | # Interpret the config file for Python logging. 20 | # This line sets up loggers basically. 21 | if config.config_file_name is not None: 22 | fileConfig(config.config_file_name) 23 | 24 | # add your model's MetaData object here 25 | # for 'autogenerate' support 26 | # from myapp import mymodel 27 | # target_metadata = mymodel.Base.metadata 28 | 29 | target_metadata = Base.metadata 30 | 31 | # other values from the config, defined by the needs of env.py, 32 | # can be acquired: 33 | # my_important_option = config.get_main_option("my_important_option") 34 | # ... etc. 35 | 36 | 37 | def run_migrations_offline() -> None: 38 | """Run migrations in 'offline' mode. 39 | 40 | This configures the context with just a URL 41 | and not an Engine, though an Engine is acceptable 42 | here as well. By skipping the Engine creation 43 | we don't even need a DBAPI to be available. 44 | 45 | Calls to context.execute() here emit the given string to the 46 | script output. 47 | 48 | """ 49 | url = config.set_main_option("sqlalchemy.url", settings.DATABASE_URL) 50 | 51 | context.configure( 52 | url=url, 53 | target_metadata=target_metadata, 54 | literal_binds=True, 55 | dialect_opts={"paramstyle": "named"}, 56 | ) 57 | 58 | with context.begin_transaction(): 59 | context.run_migrations() 60 | 61 | 62 | def run_migrations_online() -> None: 63 | """Run migrations in 'online' mode. 64 | 65 | In this scenario we need to create an Engine 66 | and associate a connection with the context. 67 | 68 | """ 69 | connectable = engine_from_config( 70 | config.get_section(config.config_ini_section, {}), 71 | prefix="sqlalchemy.", 72 | poolclass=pool.NullPool, 73 | ) 74 | 75 | with connectable.connect() as connection: 76 | context.configure( 77 | connection=connection, target_metadata=target_metadata 78 | ) 79 | 80 | with context.begin_transaction(): 81 | context.run_migrations() 82 | 83 | 84 | if context.is_offline_mode(): 85 | run_migrations_offline() 86 | else: 87 | run_migrations_online() 88 | -------------------------------------------------------------------------------- /app/api/endpoints/challenges.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, Depends, HTTPException, status 2 | from sqlalchemy.orm import Session 3 | from typing import List 4 | 5 | from app import crud, models, schemas 6 | from app.api import deps 7 | 8 | router = APIRouter() 9 | 10 | @router.post("/", response_model=schemas.Challenge) 11 | def create_challenge( 12 | challenge: schemas.ChallengeCreate, 13 | db: Session = Depends(deps.get_db), 14 | current_user: models.User = Depends(deps.get_current_active_user) 15 | ): 16 | return crud.challenge.create_challenge(db=db, challenge=challenge, owner_id=current_user.id) 17 | 18 | @router.get("/", response_model=List[schemas.Challenge]) 19 | def read_challenges( 20 | skip: int = 0, 21 | limit: int = 100, 22 | db: Session = Depends(deps.get_db) 23 | ): 24 | challenges = crud.challenge.get_api_challenges(db, skip=skip, limit=limit) 25 | return challenges 26 | 27 | @router.get("/{challenge_id}", response_model=schemas.Challenge) 28 | def read_challenge( 29 | challenge_id: int, 30 | db: Session = Depends(deps.get_db) 31 | ): 32 | db_challenge = crud.challenge.get_challenge(db, challenge_id=challenge_id) 33 | if db_challenge is None: 34 | raise HTTPException(status_code=404, detail="Challenge not found") 35 | return db_challenge 36 | 37 | @router.put("/{challenge_id}", response_model=schemas.Challenge) 38 | def update_challenge( 39 | challenge_id: int, 40 | challenge: schemas.ChallengeUpdate, 41 | db: Session = Depends(deps.get_db), 42 | current_user: models.User = Depends(deps.get_current_active_user) 43 | ): 44 | db_challenge = crud.challenge.get_challenge(db, challenge_id=challenge_id) 45 | if db_challenge is None: 46 | raise HTTPException(status_code=404, detail="Challenge not found") 47 | if db_challenge.owner_id != current_user.id: 48 | raise HTTPException(status_code=403, detail="Not enough permissions") 49 | return crud.challenge.update_challenge(db=db, challenge_id=challenge_id, challenge=challenge, owner_id=current_user.id) 50 | 51 | @router.delete("/{challenge_id}", response_model=schemas.Challenge) 52 | def delete_challenge( 53 | challenge_id: int, 54 | db: Session = Depends(deps.get_db), 55 | current_user: models.User = Depends(deps.get_current_active_user) 56 | ): 57 | db_challenge = crud.challenge.get_challenge(db, challenge_id=challenge_id) 58 | if db_challenge is None: 59 | raise HTTPException(status_code=404, detail="Challenge not found") 60 | if db_challenge.owner_id != current_user.id: 61 | raise HTTPException(status_code=403, detail="Not enough permissions") 62 | return crud.challenge.delete_challenge(db=db, challenge_id=challenge_id, owner_id=current_user.id) 63 | 64 | -------------------------------------------------------------------------------- /app/crud/challenge.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy.orm import Session, joinedload 2 | from sqlalchemy import func, case, and_, or_ 3 | from app.models.challenge import Challenge 4 | from app.schemas.challenge import ChallengeCreate, ChallengeUpdate 5 | from app.models.submission import Submission 6 | from app.models.user import User 7 | 8 | def get_challenge(db: Session, challenge_id: int): 9 | return db.query(Challenge).filter(Challenge.id == challenge_id).first() 10 | 11 | 12 | def get_api_challenges(db: Session, skip: int = 0, limit: int =100): 13 | return (db.query(Challenge) 14 | .order_by(Challenge.id) 15 | .offset(skip) 16 | .limit(limit) 17 | .all()) 18 | 19 | def get_challenges(db: Session, skip: int = 0, limit: int = 100): 20 | success_case = case( 21 | (and_( 22 | Submission.is_correct.is_(True), 23 | or_( 24 | Challenge.theorem2_signature.is_(None), 25 | Challenge.theorem2_signature == '', 26 | Submission.is_correct2.is_(True) 27 | ) 28 | ), 1), 29 | else_=0 30 | ) 31 | 32 | return (db.query(Challenge, 33 | User.display_name.label('creator_name'), 34 | func.count(Submission.id).label('total_submissions'), 35 | func.coalesce(func.sum(success_case),0).label('successful_submissions') 36 | ) 37 | .join(User, Challenge.owner_id == User.id) 38 | .outerjoin(Submission, Challenge.id == Submission.challenge_id) 39 | .group_by(Challenge.id, User.id, User.display_name) 40 | .order_by(Challenge.id) 41 | .offset(skip) 42 | .limit(limit) 43 | .all()) 44 | 45 | def create_challenge(db: Session, challenge: ChallengeCreate, owner_id: int): 46 | db_challenge = Challenge(**challenge.dict(), owner_id=owner_id) 47 | db.add(db_challenge) 48 | db.commit() 49 | db.refresh(db_challenge) 50 | return db_challenge 51 | 52 | def update_challenge(db: Session, challenge_id: int, challenge: ChallengeUpdate, owner_id: int): 53 | db_challenge = db.query(Challenge).filter(Challenge.id == challenge_id, Challenge.owner_id == owner_id).first() 54 | if db_challenge: 55 | update_data = challenge.dict(exclude_unset=True) 56 | for key, value in update_data.items(): 57 | setattr(db_challenge, key, value) 58 | db.commit() 59 | db.refresh(db_challenge) 60 | return db_challenge 61 | else: 62 | raise ValueError("Challenge not found") 63 | 64 | def delete_challenge(db: Session, challenge_id: int, owner_id: int): 65 | db_challenge = db.query(Challenge).filter(Challenge.id == challenge_id, Challenge.owner_id == owner_id).first() 66 | if db_challenge: 67 | db.delete(db_challenge) 68 | db.commit() 69 | return db_challenge 70 | 71 | -------------------------------------------------------------------------------- /static/css/styles.css: -------------------------------------------------------------------------------- 1 | body { 2 | font-family: Arial, sans-serif; 3 | line-height: 1.6; 4 | margin: 0; 5 | padding: 0; 6 | } 7 | 8 | header { 9 | background-color: #333; 10 | color: #fff; 11 | padding: 1rem; 12 | } 13 | 14 | nav a { 15 | color: #fff; 16 | margin-right: 1rem; 17 | text-decoration: none; 18 | } 19 | 20 | main { 21 | padding: 2rem; 22 | } 23 | 24 | .button { 25 | background-color: #333; 26 | color: #fff; 27 | padding: 0.5rem 1rem; 28 | text-decoration: none; 29 | } 30 | 31 | form { 32 | display: flex; 33 | flex-direction: column; 34 | max-width: 500px; 35 | } 36 | 37 | label, input, textarea { 38 | margin-bottom: 1rem; 39 | } 40 | 41 | table { 42 | width: 100%; 43 | border-collapse: collapse; 44 | } 45 | 46 | th, td { 47 | padding: 0.5rem; 48 | border: 1px solid #ccc; 49 | } 50 | 51 | th { 52 | background-color: #f4f4f4; 53 | } 54 | 55 | input[type="email"], 56 | input[type="password"], 57 | input[type="text"] { 58 | width: 100%; 59 | padding: 0.5rem; 60 | } 61 | button[type="submit"] { 62 | display: block; 63 | width: 100%; 64 | padding: 0.5rem; 65 | background-color: #007bff; 66 | color: white; 67 | border: none; 68 | cursor: pointer; 69 | } 70 | 71 | button[type="submit"]:hover { 72 | background-color: #0056b3; 73 | } 74 | 75 | .pagination { 76 | margin-top: 20px; 77 | text-align: center; 78 | } 79 | 80 | .pagination a, .pagination span { 81 | padding: 5px 10px; 82 | margin: 0 5px; 83 | border: 1px solid #ddd; 84 | color: #007bff; 85 | text-decoration: none; 86 | } 87 | 88 | .pagination a:hover { 89 | background-color: #007bff; 90 | color: white; 91 | } 92 | 93 | .challenges-table { 94 | width: 100%; 95 | border-collapse: collapse; 96 | margin: 20px 0; 97 | } 98 | 99 | .challenges-table th, 100 | .challenges-table td { 101 | padding: 12px; 102 | text-align: left; 103 | border-bottom: 1px solid #ddd; 104 | } 105 | 106 | .challenges-table th { 107 | background-color: #f5f5f5; 108 | font-weight: bold; 109 | } 110 | 111 | .challenges-table tr:hover { 112 | background-color: #f9f9f9; 113 | } 114 | 115 | .challenges-table a { 116 | color: #007bff; 117 | text-decoration: none; 118 | } 119 | 120 | .challenges-table a:hover { 121 | text-decoration: underline; 122 | } 123 | 124 | .create-challenge-button { 125 | margin-top: 20px; 126 | } 127 | 128 | .create-challenge-button .button { 129 | display: inline-block; 130 | padding: 10px 20px; 131 | background-color: #007bff; 132 | color: white; 133 | text-decoration: none; 134 | border-radius: 4px; 135 | } 136 | 137 | .create-challenge-button .button:hover { 138 | background-color: #0056b3; 139 | } 140 | 141 | .admin-controls { 142 | margin: 1rem 0; 143 | } 144 | 145 | .button.secondary { 146 | background-color: #6c757d; 147 | } 148 | 149 | .button:hover { 150 | opacity: 0.9; 151 | } 152 | 153 | form textarea { 154 | width: 100%; 155 | font-family: monospace; 156 | } 157 | 158 | pre { 159 | white-space: pre-wrap; /* Since CSS 2.1 */ 160 | white-space: -moz-pre-wrap; /* Mozilla, since 1999 */ 161 | white-space: -pre-wrap; /* Opera 4-6 */ 162 | white-space: -o-pre-wrap; /* Opera 7 */ 163 | word-wrap: break-word; /* Internet Explorer 5.5+ */ 164 | } 165 | 166 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Code with Proofs: The Arena 2 | 3 | [Demo Site](http://www.codeproofarena.com:8000/) 4 | 5 | Main essay: [A Proposal for Safe and Hallucination-free Coding AI](https://gasstationmanager.github.io/ai/2024/11/04/a-proposal.html) 6 | 7 | This repo implements a website with functionalities similar to online coding challenge sites like LeetCode, HackerRank and CodeForces, where users can submit solutions to coding challenges and be judged on test cases; except here the problems have function signatures with formal theorem statements, users submit code with proofs, and will be judged by the proof checker. Right now the only supported language is Lean, but I hope someone can extend it to other similar languages such as Coq, Idris, Dafny. 8 | 9 | The purpose of this website is to serve as a platform to crowdsource efforts to create data on code-with-proof problems and solutions, including problem-only data as well as problem-with-solution data, both human-created and machine-created. And as a platform to share this data with the open-source community, for the purpose of training open-source models. 10 | 11 | The web app is implemented in Python with the FastAPI library. Both web interface and API endpoints are available to create/manage challenges 12 | and create/manage submissions. Automatic API documentation available; once the app is running 13 | they are served at `/docs` (Swagger UI), and at `/redoc` (Redoc). 14 | 15 | `scripts/import_challenges.py` is a simple script that creates challenges by importing from a JSONL file 16 | in the format of [Code with Proofs Benchmark](https://github.com/GasStationManager/CodeProofBenchmark). 17 | 18 | # Installation 19 | 20 | ## Prerequisites 21 | 22 | 1. Python 3.10 or higher 23 | 2. PostgreSQL. E.g. on Ubuntu/Debian: 24 | ```bash 25 | sudo apt-get update 26 | sudo apt-get install postgresql postgresql-contrib 27 | sudo systemctl start postgresql 28 | sudo systemctl enable postgresql 29 | ``` 30 | 3. Poetry (Python package manager). 31 | ```bash 32 | curl -sSL https://install.python-poetry.org | python3 - 33 | ``` 34 | 4. Lean 4. 35 | ```bash 36 | curl https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh -sSf | sh 37 | ``` 38 | 39 | ## Installation Instructions 40 | 41 | 1. clone the repository. `cd` into the directory. Then `poetry install` to install dependencies 42 | 2. Install dependencies, including Mathlib4 and [SafeVerify](https://github.com/GasStationManager/SafeVerify). 43 | ```bash 44 | curl https://raw.githubusercontent.com/leanprover-community/mathlib4/master/lean-toolchain -o lean-toolchain 45 | lake exe cache get 46 | lake update 47 | lake build safe_verify 48 | ``` 49 | 3. Create a database and user in PostgreSQL. First, log into the server using `psql` as the superuser of the PosgresSQL installation. For Ubuntu: 50 | `sudo -u postgres psql`. For Mac homebrew installation the user `postgres` is not installed; you might try 51 | `psql` with the current user, as suggested by [this StackOverflow](https://stackoverflow.com/questions/70487669/postgres-superuser-is-not-created-upon-installation). 52 | 53 | 54 | 4. In PostgreSQL prompt (replace with your password): 55 | 56 | ``` 57 | CREATE DATABASE coding_challenge_db; 58 | CREATE USER coding_challenge_user WITH PASSWORD 'your_password_here'; 59 | 60 | GRANT CONNECT ON DATABASE coding_challenge_db TO coding_challenge_user; 61 | 62 | \c coding_challenge_db 63 | 64 | GRANT USAGE, CREATE ON SCHEMA public TO coding_challenge_user; 65 | 66 | GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO coding_challenge_user; 67 | 68 | ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON TABLES TO coding_challenge_user; 69 | 70 | \q 71 | ``` 72 | 73 | 5. Then put the password you chose in the previous step (for connection to PostgreSQL) in the following config files: 74 | First modify `dotenv.example` and save it as `.env`, and also in `alembic.ini` (around line 64). 75 | 76 | 6. `poetry run alembic upgrade head` 77 | 78 | 7. `./run.sh` 79 | -------------------------------------------------------------------------------- /lake-manifest.json: -------------------------------------------------------------------------------- 1 | {"version": "1.1.0", 2 | "packagesDir": ".lake/packages", 3 | "packages": 4 | [{"url": "https://github.com/leanprover-community/batteries", 5 | "type": "git", 6 | "subDir": null, 7 | "scope": "leanprover-community", 8 | "rev": "0dc51ac7947ff6aa2c16bcffb64c46c7149d1276", 9 | "name": "batteries", 10 | "manifestFile": "lake-manifest.json", 11 | "inputRev": "main", 12 | "inherited": true, 13 | "configFile": "lakefile.toml"}, 14 | {"url": "https://github.com/leanprover-community/quote4", 15 | "type": "git", 16 | "subDir": null, 17 | "scope": "leanprover-community", 18 | "rev": "303b23fbcea94ac4f96e590c1cad6618fd4f5f41", 19 | "name": "Qq", 20 | "manifestFile": "lake-manifest.json", 21 | "inputRev": "master", 22 | "inherited": true, 23 | "configFile": "lakefile.lean"}, 24 | {"url": "https://github.com/leanprover-community/aesop", 25 | "type": "git", 26 | "subDir": null, 27 | "scope": "leanprover-community", 28 | "rev": "de91b59101763419997026c35a41432ac8691f15", 29 | "name": "aesop", 30 | "manifestFile": "lake-manifest.json", 31 | "inputRev": "master", 32 | "inherited": true, 33 | "configFile": "lakefile.toml"}, 34 | {"url": "https://github.com/leanprover-community/ProofWidgets4", 35 | "type": "git", 36 | "subDir": null, 37 | "scope": "leanprover-community", 38 | "rev": "1383e72b40dd62a566896a6e348ffe868801b172", 39 | "name": "proofwidgets", 40 | "manifestFile": "lake-manifest.json", 41 | "inputRev": "v0.0.46", 42 | "inherited": true, 43 | "configFile": "lakefile.lean"}, 44 | {"url": "https://github.com/leanprover/lean4-cli", 45 | "type": "git", 46 | "subDir": null, 47 | "scope": "leanprover", 48 | "rev": "726b3c9ad13acca724d4651f14afc4804a7b0e4d", 49 | "name": "Cli", 50 | "manifestFile": "lake-manifest.json", 51 | "inputRev": "main", 52 | "inherited": true, 53 | "configFile": "lakefile.toml"}, 54 | {"url": "https://github.com/leanprover-community/import-graph", 55 | "type": "git", 56 | "subDir": null, 57 | "scope": "leanprover-community", 58 | "rev": "119b022b3ea88ec810a677888528e50f8144a26e", 59 | "name": "importGraph", 60 | "manifestFile": "lake-manifest.json", 61 | "inputRev": "main", 62 | "inherited": true, 63 | "configFile": "lakefile.toml"}, 64 | {"url": "https://github.com/leanprover-community/LeanSearchClient", 65 | "type": "git", 66 | "subDir": null, 67 | "scope": "leanprover-community", 68 | "rev": "d7caecce0d0f003fd5e9cce9a61f1dd6ba83142b", 69 | "name": "LeanSearchClient", 70 | "manifestFile": "lake-manifest.json", 71 | "inputRev": "main", 72 | "inherited": true, 73 | "configFile": "lakefile.toml"}, 74 | {"url": "https://github.com/leanprover-community/plausible", 75 | "type": "git", 76 | "subDir": null, 77 | "scope": "leanprover-community", 78 | "rev": "42dc02bdbc5d0c2f395718462a76c3d87318f7fa", 79 | "name": "plausible", 80 | "manifestFile": "lake-manifest.json", 81 | "inputRev": "main", 82 | "inherited": true, 83 | "configFile": "lakefile.toml"}, 84 | {"url": "https://github.com/leanprover-community/mathlib4", 85 | "type": "git", 86 | "subDir": null, 87 | "scope": "leanprover-community", 88 | "rev": "13f8b501146167f8c599e41a7f9b49054a16f6a7", 89 | "name": "mathlib", 90 | "manifestFile": "lake-manifest.json", 91 | "inputRev": "master", 92 | "inherited": false, 93 | "configFile": "lakefile.lean"}, 94 | {"url": "https://github.com/GasStationManager/SafeVerify.git", 95 | "type": "git", 96 | "subDir": null, 97 | "scope": "", 98 | "rev": "672dcbf11b2467a6c4c0a861c8bf33ec007a6222", 99 | "name": "SafeVerify", 100 | "manifestFile": "lake-manifest.json", 101 | "inputRev": null, 102 | "inherited": false, 103 | "configFile": "lakefile.toml"}], 104 | "name": "CodeProofTheArena", 105 | "lakeDir": ".lake"} 106 | -------------------------------------------------------------------------------- /alembic.ini: -------------------------------------------------------------------------------- 1 | # A generic, single database configuration. 2 | 3 | [alembic] 4 | # path to migration scripts 5 | # Use forward slashes (/) also on windows to provide an os agnostic path 6 | script_location = alembic 7 | 8 | # template used to generate migration file names; The default value is %%(rev)s_%%(slug)s 9 | # Uncomment the line below if you want the files to be prepended with date and time 10 | # see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file 11 | # for all available tokens 12 | # file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s 13 | 14 | # sys.path path, will be prepended to sys.path if present. 15 | # defaults to the current working directory. 16 | prepend_sys_path = . 17 | 18 | # timezone to use when rendering the date within the migration file 19 | # as well as the filename. 20 | # If specified, requires the python>=3.9 or backports.zoneinfo library. 21 | # Any required deps can installed by adding `alembic[tz]` to the pip requirements 22 | # string value is passed to ZoneInfo() 23 | # leave blank for localtime 24 | # timezone = 25 | 26 | # max length of characters to apply to the "slug" field 27 | # truncate_slug_length = 40 28 | 29 | # set to 'true' to run the environment during 30 | # the 'revision' command, regardless of autogenerate 31 | # revision_environment = false 32 | 33 | # set to 'true' to allow .pyc and .pyo files without 34 | # a source .py file to be detected as revisions in the 35 | # versions/ directory 36 | # sourceless = false 37 | 38 | # version location specification; This defaults 39 | # to alembic/versions. When using multiple version 40 | # directories, initial revisions must be specified with --version-path. 41 | # The path separator used here should be the separator specified by "version_path_separator" below. 42 | # version_locations = %(here)s/bar:%(here)s/bat:alembic/versions 43 | 44 | # version path separator; As mentioned above, this is the character used to split 45 | # version_locations. The default within new alembic.ini files is "os", which uses os.pathsep. 46 | # If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas. 47 | # Valid values for version_path_separator are: 48 | # 49 | # version_path_separator = : 50 | # version_path_separator = ; 51 | # version_path_separator = space 52 | # version_path_separator = newline 53 | version_path_separator = os # Use os.pathsep. Default configuration used for new projects. 54 | 55 | # set to 'true' to search source files recursively 56 | # in each "version_locations" directory 57 | # new in Alembic version 1.10 58 | # recursive_version_locations = false 59 | 60 | # the output encoding used when revision files 61 | # are written from script.py.mako 62 | # output_encoding = utf-8 63 | 64 | sqlalchemy.url = postgresql://coding_challenge_user:LocalPass@localhost/coding_challenge_db 65 | 66 | 67 | [post_write_hooks] 68 | # post_write_hooks defines scripts or Python functions that are run 69 | # on newly generated revision scripts. See the documentation for further 70 | # detail and examples 71 | 72 | # format using "black" - use the console_scripts runner, against the "black" entrypoint 73 | # hooks = black 74 | # black.type = console_scripts 75 | # black.entrypoint = black 76 | # black.options = -l 79 REVISION_SCRIPT_FILENAME 77 | 78 | # lint with attempts to fix using "ruff" - use the exec runner, execute a binary 79 | # hooks = ruff 80 | # ruff.type = exec 81 | # ruff.executable = %(here)s/.venv/bin/ruff 82 | # ruff.options = --fix REVISION_SCRIPT_FILENAME 83 | 84 | # Logging configuration 85 | [loggers] 86 | keys = root,sqlalchemy,alembic 87 | 88 | [handlers] 89 | keys = console 90 | 91 | [formatters] 92 | keys = generic 93 | 94 | [logger_root] 95 | level = WARN 96 | handlers = console 97 | qualname = 98 | 99 | [logger_sqlalchemy] 100 | level = WARN 101 | handlers = 102 | qualname = sqlalchemy.engine 103 | 104 | [logger_alembic] 105 | level = INFO 106 | handlers = 107 | qualname = alembic 108 | 109 | [handler_console] 110 | class = StreamHandler 111 | args = (sys.stderr,) 112 | level = NOTSET 113 | formatter = generic 114 | 115 | [formatter_generic] 116 | format = %(levelname)-5.5s [%(name)s] %(message)s 117 | datefmt = %H:%M:%S 118 | -------------------------------------------------------------------------------- /scripts/import_challenges.py: -------------------------------------------------------------------------------- 1 | import json 2 | import argparse 3 | import requests 4 | import re 5 | 6 | def extract_function_name(function_signature): 7 | """Extract function name from the function signature.""" 8 | match = re.search(r'def\s+(\w+)', function_signature) 9 | if match: 10 | return match.group(1) 11 | return None 12 | 13 | def create_challenge(challenge_data, api_url, token): 14 | """Create a challenge using the API.""" 15 | headers = { 16 | "Authorization": f"Bearer {token}", 17 | "Content-Type": "application/json" 18 | } 19 | 20 | # Extract or generate title 21 | title = challenge_data.get('title') 22 | if not title: 23 | function_name = extract_function_name(challenge_data['function_signature']) 24 | title = function_name if function_name else "Untitled Challenge" 25 | 26 | 27 | # property def (for FormalizeWithTest outputs) 28 | if 'property_def' in challenge_data: 29 | challenge_data['theorem_signature'] = f"{challenge_data['property_def']}\n{challenge_data['theorem_signature']}" 30 | # Prepare challenge data 31 | challenge = { 32 | "title": title, 33 | "description": challenge_data['description'], 34 | "function_signature": challenge_data['function_signature'], 35 | "theorem_signature": challenge_data['theorem_signature'] if challenge_data['theorem_signature'] else '', 36 | "theorem2_signature": challenge_data.get('theorem2_signature') 37 | } 38 | 39 | try: 40 | response = requests.post(f"{api_url}/api/challenges/", json=challenge, headers=headers) 41 | response.raise_for_status() 42 | print(f"Successfully created challenge: {title}") 43 | return response.json() 44 | except requests.exceptions.RequestException as e: 45 | print(f"Failed to create challenge {title}: {str(e)}") 46 | if hasattr(e.response, 'text'): 47 | print(f"Error details: {e.response.text}") 48 | return None 49 | 50 | def login(api_url, email, password): 51 | """Login and get access token.""" 52 | try: 53 | response = requests.post( 54 | f"{api_url}/api/auth/login", 55 | data={"username": email, "password": password} 56 | ) 57 | response.raise_for_status() 58 | return response.json()["access_token"] 59 | except requests.exceptions.RequestException as e: 60 | print(f"Failed to login: {str(e)}") 61 | if hasattr(e.response, 'text'): 62 | print(f"Error details: {e.response.text}") 63 | return None 64 | 65 | def main(): 66 | parser = argparse.ArgumentParser(description='Import challenges from a JSONL file') 67 | parser.add_argument('file', help='Path to the JSONL file containing challenges') 68 | parser.add_argument('--api-url', default='http://localhost:8000', 69 | help='Base URL of the API (default: http://localhost:8000)') 70 | parser.add_argument('--email', required=True, help='Email for authentication') 71 | parser.add_argument('--password', required=True, help='Password for authentication') 72 | 73 | args = parser.parse_args() 74 | 75 | # Login and get token 76 | token = login(args.api_url, args.email, args.password) 77 | if not token: 78 | print("Failed to authenticate. Exiting.") 79 | return 80 | 81 | # Read and process challenges 82 | successful = 0 83 | failed = 0 84 | 85 | try: 86 | with open(args.file, 'r') as f: 87 | for line_number, line in enumerate(f, 1): 88 | try: 89 | challenge_data = json.loads(line.strip()) 90 | result = create_challenge(challenge_data, args.api_url, token) 91 | if result: 92 | successful += 1 93 | else: 94 | failed += 1 95 | except json.JSONDecodeError as e: 96 | print(f"Error parsing line {line_number}: {str(e)}") 97 | failed += 1 98 | except Exception as e: 99 | print(f"Error processing line {line_number}: {str(e)}") 100 | failed += 1 101 | 102 | except FileNotFoundError: 103 | print(f"File not found: {args.file}") 104 | return 105 | 106 | print(f"\nImport completed:") 107 | print(f"Successfully imported: {successful}") 108 | print(f"Failed: {failed}") 109 | 110 | if __name__ == "__main__": 111 | main() 112 | 113 | -------------------------------------------------------------------------------- /app/services/judge.py: -------------------------------------------------------------------------------- 1 | import subprocess 2 | import tempfile 3 | import os 4 | import re 5 | 6 | 7 | 8 | FUNC_BANNED_WORDS = ['implemented_by', 'noncomputable'] 9 | 10 | 11 | def extract_imports (code:str): 12 | imports='' 13 | rest='' 14 | for line in code.splitlines(): 15 | if line.startswith('import'): 16 | imports+=line+'\n' 17 | else: 18 | rest+=line+'\n' 19 | return imports,rest 20 | 21 | 22 | def check_lean_proof(challenge: dict, submission: dict) -> dict: 23 | for w in FUNC_BANNED_WORDS: 24 | if w in submission['code']: 25 | return { 26 | "is_correct": False, 27 | "is_correct2": False if challenge.get('theorem2_signature') else None, 28 | "feedback": f"{w} is not allowed in the function implementation", 29 | "feedback2": None 30 | } 31 | basedir=os.path.abspath('temp') 32 | print('basedir ',basedir) 33 | with tempfile.TemporaryDirectory(dir=basedir) as tmpdir: 34 | # Create temporary Lean files 35 | print('created temp directory ', tmpdir) 36 | function_sig=challenge['function_signature'] 37 | #if 'import' not in function_sig: 38 | # function_sig='import Mathlib\n\n'+function_sig 39 | 40 | 41 | targf=os.path.join(tmpdir, "target.lean") 42 | if function_sig.strip().endswith(':='): 43 | func_body='sorry\n' 44 | else: 45 | func_body=':=sorry\n' 46 | thm_body=':=sorry\n' 47 | if challenge['theorem_signature'].strip().endswith(':='): thm_body='sorry\n' 48 | with open(targf, "w") as f: 49 | f.write(f""" 50 | {function_sig} 51 | {func_body} 52 | {challenge['theorem_signature']} 53 | {thm_body} 54 | """) 55 | print('finished writing to '+targf) 56 | 57 | prooff=os.path.join(tmpdir, "proof.lean") 58 | codeimp, code=extract_imports(submission['code']) 59 | prfimp,prf=extract_imports(submission['proof']) 60 | with open(prooff, "w") as f: 61 | f.write(f""" 62 | {codeimp} 63 | {prfimp} 64 | {function_sig} 65 | {code} 66 | 67 | {challenge['theorem_signature']} 68 | {prf} 69 | """) 70 | proof2f=None 71 | if challenge.get('theorem2_signature') and submission.get('proof2'): 72 | targ2f=os.path.join(tmpdir, "target2.lean") 73 | thm2_body='sorry\n' if challenge['theorem2_signature'].strip().endswith(':=') else ':=sorry\n' 74 | with open(targ2f,'w') as f: 75 | f.write(f""" 76 | {function_sig} 77 | {func_body} 78 | {challenge['theorem2_signature']} 79 | {thm2_body} 80 | """) 81 | proof2f=os.path.join(tmpdir, "proof2.lean") 82 | prf2imp,prf2=extract_imports(submission['proof2']) 83 | with open(proof2f, "w") as f: 84 | f.write(f""" 85 | {codeimp} 86 | {prf2imp} 87 | {function_sig} 88 | {code} 89 | """) 90 | f.write(f"\n\n{challenge['theorem2_signature']}\n\n{prf2}") 91 | 92 | def compile (fname): 93 | # compile on the temporary file 94 | assert fname.endswith('.lean') 95 | ofname=fname[:-4]+'olean' 96 | result = subprocess.run(["lake","env","lean",'-o',ofname, fname], capture_output=True, text=True) 97 | # Check if Lean 4 succeeded (return code 0 means success) 98 | is_correct = result.returncode == 0 99 | return is_correct, result.stderr + result.stdout 100 | 101 | def compare(targf, subf): 102 | for f in [targf,subf]: 103 | r,err=compile(f) 104 | if not r: 105 | err=f"Compilation error for {f}:\n"+err 106 | return r,err 107 | otarg=targf[:-4]+'olean' 108 | osub=subf[:-4]+'olean' 109 | result=subprocess.run(["lake","env","safe_verify",otarg,osub],capture_output=True,text=True) 110 | is_correct = result.returncode==0 111 | return is_correct, result.stderr+result.stdout 112 | 113 | is_correct, error_message = compare(targf, prooff) 114 | 115 | 116 | is_correct2 = None 117 | error_message2 = None 118 | if challenge.get('theorem2_signature') and submission.get('proof2'): 119 | is_correct2,error_message2=compare(targ2f,proof2f) 120 | 121 | return { 122 | "is_correct": is_correct, 123 | "is_correct2": is_correct2, 124 | "feedback": error_message.strip() if error_message else "Proof checked successfully!", 125 | "feedback2": error_message2.strip() if error_message2 else None 126 | } 127 | -------------------------------------------------------------------------------- /scripts/easy.jsonl: -------------------------------------------------------------------------------- 1 | {"description": "write a function that, given integers a and b, returns an integer x such that a + x = b", "function_signature": "def solveAdd (a b:Int): Int", "test_cases": null, "theorem_signature": "theorem solveAdd_correct (a b: Int): a + (solveAdd a b) =b ", "theorem2_signature": null} 2 | {"description": "write a function that, given integer a, returns an integer x such that a + x = 0", "function_signature": "def solveAdd0(a:Int): Int", "test_cases": null, "theorem_signature": "theorem solveAdd0_correct(a: Int): a +(solveAdd0 a)=0", "theorem2_signature": null} 3 | {"description": "write a function that, given integers a and b, returns an integer x such that a - x = b", "function_signature": "def solveSub(a b:Int): Int", "test_cases": null, "theorem_signature": "theorem solveSub_correct(a b:Int): a - (solveSub a b)=b", "theorem2_signature": null} 4 | {"description": "write a function that, given rationals a and b, return some x such that a*x=b. if no solution exists, return none", "function_signature": "def solve1x1(a b: Rat): Option Rat", "test_cases": null, "theorem_signature": "theorem solve1x1_correct(a b:Rat): (∃ x, a*x=b) -> a * (solve1x1 a b).get! =b", "theorem2_signature": "theorem solve1x1_none(a b:Rat): (Not (∃ x, a*x=b)) -> solve1x1 a b=none"} 5 | {"description": "write a function that, given rational a, returns a rational x such that a*x=1. If no solution exists, return 0.", "function_signature": "def solveMul(a: Rat): Rat", "test_cases": null, "theorem_signature": "theorem solveMul_correct(a:Rat): (∃ x, a*x=1)->a * (solveMul a)=1", "theorem2_signature": "theorem solveMul_nosol (a:Rat): (Not (∃ x, a*x=1)) ->solveMul a =0"} 6 | {"description": "write a function that, given rationals a and b, both not equal to zero, return x such that a/x=b.", "function_signature": "def solveDiv(a b:Rat) (ha: a≠ 0)(hb: b≠ 0): Rat", "test_cases": null, "theorem_signature": "theorem solveDiv_correct(a b:Rat)(ha:a≠ 0)(hb: b≠ 0):\na / (solveDiv a b ha hb)= b", "theorem2_signature": null} 7 | {"description": "write a function isPrime that given a natural number a, returns true if and only if a is prime.", "function_signature": "def isPrime(a: Nat): Bool", "test_cases": null, "theorem_signature": "theorem isPrime_correct(a: Nat): (isPrime a)=True <-> Nat.Prime a", "theorem2_signature": null} 8 | {"description": "write a function that given a natrual number a and a prime number p, returns a natural number x such that (a*x)%p=1. if no solution exists, return none.", "function_signature": "def modInv(a: Nat) (p:Nat)(hp:p.Prime): Option Nat", "test_cases": null, "theorem_signature": "\ntheorem modInv_correct(a:Nat) (p:Nat)(hp:p.Prime):\n (∃ x:Nat, (a*x)%p=1)->(a*(modInv a p hp).get!)%p=1", "theorem2_signature": "theorem modInv_none(a:Nat) (p:Nat)(hp:p.Prime): (Not (∃ x, (a*x)%p=1))-> modInv a p hp=none"} 9 | {"description": "write a function that given a natural number a, a>1, find the minimum factor of a that is not 1. ", "function_signature": "def minFac(a:Nat) (h: a>1): Nat ", "test_cases": null, "theorem_signature": "theorem minFac_isfac(a:Nat)(h: a>1): ( (minFac a h) ∣a) ∧(minFac a h>1)", "theorem2_signature": "theorem minFac_ismin(a:Nat)(h:a>1): Not (∃ y>1,( y ∣ a) ∧y 0)→ ((GCD x y) ∣ x) ∧ ((GCD x y) ∣ y)", "theorem2_signature": "\ntheorem gcd_is_greatest (x y: Nat):\n (x>0) → Not (∃ z: Nat, z∣ x ∧ z∣ y ∧ z> GCD x y )"} 12 | {"description": "write a function that, given natural number t, find the minimum n such that 1+2+…+n>=t.", "function_signature": "def solveProg(t:Nat):Nat", "test_cases": null, "theorem_signature": "theorem solveProg_isgeq(t:Nat): (solveProg t)*((solveProg t)+1) >= t*2", "theorem2_signature": "theorem solveProg_ismin(t:Nat): Not (∃ y< (solveProg t), y*(y+1)>=t*2)"} 13 | {"description": "write a function that, given natural numbers a and t, with a>1, find the minimum n such that a^0+a^1+..a^n >=t.", "function_signature": "def solveGeom(a t:Nat)(h:a>1):Nat", "test_cases": null, "theorem_signature": "theorem solveGeom_isgeq(a t:Nat)(h:a>1): a^((solveGeom a t h)+1)-1 >=t*(a-1)", "theorem2_signature": "theorem solveGeom_ismin(a t:Nat)(h:a>1): Not (∃ y= t*(a-1))"} 14 | {"description": "write a function that, given natural number t, find the minimum n such that n*n>=t.", "function_signature": "def solveSquare(t:Nat): Nat", "test_cases": null, "theorem_signature": "theorem solveSquare_isgeq(t:Nat): (solveSquare t)*(solveSquare t)>=t", "theorem2_signature": "theorem solveSquare_ismin(t:Nat): Not (∃ y< (solveSquare t), y*y>=t)"} 15 | {"description": "Implement the following in lean 4. Given a binary operator op, we define the function f : Nat->Nat to be: f 0 =1; f 1=1; f n = op (f (n-1)) (f (n-2)). Write a lean 4 function that, given the op and the natural number n as arguments, computes f n. Additionally, op returns a value wrapped in a monad. Your function should have the signature def f [Monad m] (op: Nat->Nat->(m Nat)) (n: Nat): (m Nat) :=", "function_signature": "def f[Monad m] (op: Nat->Nat->(m Nat)) (n: Nat): (m Nat)", "test_cases": null, "theorem_signature": "theorem f_base (op : Nat → Nat → Id Nat) :\n (f op 0 = pure 1) ∧ (f op 1 = pure 1)", "theorem2_signature": "theorem f_recursive (op : Nat → Nat → Id Nat) (n : Nat) : f op (n+2) =do {op (← f op (n+1)) (← f op n) }"} 16 | {"description": "write a function that, given a List of integers, return the list in reverse order.", "function_signature": "def rev(xs: List Int): List Int", "test_cases": null, "theorem_signature": "theorem reverse_correct(xs:List Int):\n xs.length=(rev xs).length ∧\n ∀ i= min) ", "theorem2_signature": "theorem findMin_base : findMin [] = none"} 19 | {"description": "write a function that, given an integer x and a List of integers, returns true if and only if x is in the List", "function_signature": "def isIn (x:Int) (xs: List Int):Bool", "test_cases": null, "theorem_signature": "def isIn_correct (x:Int)(xs:List Int):\n isIn x xs = true ↔ x∈ xs", "theorem2_signature": null} 20 | {"description": "write a function that, given an integer x and a List of integers, returns the number of times that x appears in the list.", "function_signature": "\ndef countEq (x:Int)(xs:List Int):Nat", "test_cases": null, "theorem_signature": "def countEq_correct (x:Int)(xs:List Int):\n List.count x xs = countEq x xs", "theorem2_signature": null} 21 | {"description": "write a function that, given a List of integers and a predicate function p that takes an integer and returns a boolean, returns an element of the list x if p x = true. If such x does not exist, return none", "function_signature": "def findIf(xs:List Int)(p:Int->Bool):Option Int", "test_cases": null, "theorem_signature": "\ntheorem findIf_some(xs:List Int)(p:Int->Bool):\n (∃ x∈ xs, p x) -> ∃ y∈ xs, findIf xs p=some y ∧ p y", "theorem2_signature": "\ntheorem findIf_none(xs:List Int)(p:Int->Bool):\n (¬ ∃ y∈ xs, p y =true)-> findIf xs p=none "} 22 | {"description": "write a function that, given a List of integers and a predicate function p that takes an integer and returns a boolean, returns another list consisting of elements x of the original list such that p x = true.", "function_signature": "def filterIf(xs:List Int)(p:Int->Bool):List Int", "test_cases": null, "theorem_signature": "\ntheorem filterIf_correct(xs:List Int)(p:Int->Bool):\n filterIf xs p = List.filter p xs", "theorem2_signature": null} 23 | {"description": "write a function that, given a List of integers xs and a function f:Int->Int, returns a List of integers whose i-th element is f xs[i]", "function_signature": "def mapInt(xs:List Int)(f:Int->Int):List Int", "test_cases": null, "theorem_signature": "theorem mapInt_correct(xs:List Int)(f:Int->Int)\n: (mapInt xs f).length=xs.length\n∧ ∀ i:Fin xs.length, (mapInt xs f)[i]! = f xs[i]", "theorem2_signature": null} 24 | {"description": "Write a function that, given two lists of integers, find their longest common prefix.", "function_signature": "def isPrefix (p xs:List α):=\n List.take p.length xs = p\n\n/- longest common prefix for a pair of lists-/\ndef lcpPair:(xs ys:List Int )\n->{zs:List Int//isPrefix zs xs∧ isPrefix zs ys\n ∧ (∀zz, isPrefix zz xs∧ isPrefix zz ys->zz.length<=zs.length)}", "test_cases": null, "theorem_signature": null, "theorem2_signature": null} -------------------------------------------------------------------------------- /app/main.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from fastapi import FastAPI, Request, Depends, HTTPException, status, Form 3 | #from app.api.api import api_router 4 | 5 | 6 | from fastapi.responses import RedirectResponse 7 | 8 | from fastapi.staticfiles import StaticFiles 9 | from fastapi.templating import Jinja2Templates 10 | 11 | from app.api.endpoints import auth, challenges, submissions 12 | from app.api import deps 13 | from app import crud, models, schemas 14 | from app.core import security 15 | from app.core.config import settings 16 | from app.schemas.user import UserCreate 17 | from app.schemas.challenge import ChallengeCreate 18 | from app.models import User 19 | 20 | from sqlalchemy.orm import Session 21 | from starlette.middleware.sessions import SessionMiddleware 22 | import urllib 23 | 24 | app = FastAPI(title="Lean 4 Coding Challenge Website") 25 | 26 | # Configure logging 27 | logging.basicConfig( 28 | #level=logging.DEBUG, 29 | format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', 30 | handlers=[logging.StreamHandler()] 31 | ) 32 | 33 | logger = logging.getLogger(__name__) 34 | logger.setLevel(logging.DEBUG) 35 | 36 | 37 | # Add SessionMiddleware 38 | app.add_middleware(SessionMiddleware, secret_key=settings.SECRET_KEY) 39 | 40 | app.include_router(auth.router, prefix="/api/auth", tags=["auth"]) 41 | app.include_router(challenges.router, prefix="/api/challenges", tags=["challenges"]) 42 | 43 | app.include_router(submissions.router, prefix="/api/submissions", tags=["submissions"]) 44 | 45 | app.mount("/static", StaticFiles(directory="static"), name="static") 46 | templates = Jinja2Templates(directory="app/templates") 47 | 48 | 49 | 50 | 51 | #app.include_router(api_router) 52 | 53 | # Frontend routes 54 | 55 | @app.get("/login") 56 | async def login_page(request: Request): 57 | return templates.TemplateResponse("login.html", {"request": request}) 58 | 59 | @app.post("/login") 60 | async def login(request: Request, username: str = Form(...), password: str = Form(...), db: Session = Depends(deps.get_db)): 61 | user = crud.user.authenticate_user(db, username, password) 62 | if not user: 63 | return templates.TemplateResponse("login.html", {"request": request, "error": "Invalid username or password"}) 64 | access_token = security.create_access_token(user.id) 65 | request.session["token"] = access_token 66 | return RedirectResponse(url="/", status_code=status.HTTP_302_FOUND) 67 | 68 | @app.get("/logout") 69 | async def logout(request: Request): 70 | request.session.pop("token", None) 71 | return RedirectResponse(url="/", status_code=status.HTTP_302_FOUND) 72 | 73 | 74 | 75 | 76 | 77 | # Add a custom dependency to get the current user 78 | async def get_current_user(request: Request, db: Session = Depends(deps.get_db)): 79 | token = request.session.get("token") 80 | if not token: 81 | return None 82 | try: 83 | payload = security.decode_access_token(token) 84 | user = crud.user.get_user(db, user_id=payload["sub"]) 85 | return user 86 | except: 87 | return None 88 | 89 | 90 | # Update other routes to use the get_current_user dependency 91 | @app.get("/") 92 | async def home(request: Request, current_user: dict = Depends(get_current_user)): 93 | return templates.TemplateResponse("index.html", {"request": request, "user": current_user}) 94 | 95 | @app.get("/challenges") 96 | async def challenges_page(request: Request, db: Session = Depends(deps.get_db), current_user: dict = Depends(get_current_user)): 97 | challenges_data = crud.challenge.get_challenges(db) 98 | #print(f"Found {len(challenges)} challenges") 99 | return templates.TemplateResponse("challenges.html", {"request": request, "challenges_data": challenges_data, "user": current_user}) 100 | 101 | @app.get("/challenges/create") 102 | async def create_challenge_page(request: Request, current_user: User = Depends(get_current_user)): 103 | if not current_user: 104 | return RedirectResponse(url="/login", status_code=status.HTTP_303_SEE_OTHER) 105 | return templates.TemplateResponse("create_challenge.html", {"request": request, "user": current_user}) 106 | 107 | @app.post("/challenges/create") 108 | async def create_challenge( 109 | request: Request, 110 | title: str = Form(...), 111 | description: str = Form(...), 112 | function_signature: str = Form(...), 113 | theorem_signature: str = Form(...), 114 | theorem2_signature: str = Form(None), 115 | db: Session = Depends(deps.get_db), 116 | current_user: User = Depends(get_current_user) 117 | ): 118 | if not current_user: 119 | return RedirectResponse(url="/login", status_code=status.HTTP_303_SEE_OTHER) 120 | 121 | try: 122 | challenge = ChallengeCreate( 123 | title=title, 124 | description=description, 125 | function_signature=function_signature, 126 | theorem_signature=theorem_signature, 127 | theorem2_signature=theorem2_signature 128 | ) 129 | new_challenge = crud.challenge.create_challenge(db, challenge=challenge, owner_id=current_user.id) 130 | except ValueError as e: 131 | return templates.TemplateResponse("create_challenge.html", {"request": request, "user": current_user, "error": str(e)}) 132 | 133 | return RedirectResponse(url=f"/challenges/{new_challenge.id}", status_code=status.HTTP_303_SEE_OTHER) 134 | 135 | 136 | @app.get("/challenges/{challenge_id}") 137 | async def challenge_detail( 138 | request: Request, 139 | challenge_id: int, 140 | db: Session = Depends(deps.get_db), 141 | current_user: dict = Depends(get_current_user) 142 | ): 143 | challenge = crud.challenge.get_challenge(db, challenge_id) 144 | if not challenge: 145 | raise HTTPException(status_code=404, detail="Challenge not found") 146 | code= challenge.function_signature+'\n\n'+challenge.theorem_signature 147 | if challenge.theorem2_signature: 148 | code+='\n\n'+ challenge.theorem2_signature 149 | return templates.TemplateResponse( 150 | "challenge_detail.html", 151 | {"request": request, "challenge": challenge, "code": urllib.parse.quote(code), "user": current_user} 152 | ) 153 | 154 | @app.post("/challenges/{challenge_id}") 155 | async def submit_challenge( 156 | request: Request, 157 | challenge_id: int, 158 | code: str = Form(...), 159 | proof: str = Form(...), 160 | proof2: str = Form(None), 161 | session_token: str = Form(...), 162 | db: Session = Depends(deps.get_db) 163 | ): 164 | logger.debug(f"Session token: {session_token[:10]}...") 165 | if not session_token: 166 | logger.warning("No session token provided") 167 | return RedirectResponse(url="/login", status_code=status.HTTP_302_FOUND) 168 | try: 169 | payload = security.decode_access_token(session_token) 170 | user = crud.user.get_user(db, user_id=payload["sub"]) 171 | if not user: 172 | logger.warning(f"No user found for token payload: {payload}") 173 | return RedirectResponse(url="/login", status_code=status.HTTP_302_FOUND) 174 | except Exception as e: 175 | logger.error(f"Error decoding token: {str(e)}") 176 | return RedirectResponse(url="/login", status_code=status.HTTP_302_FOUND) 177 | 178 | challenge = crud.challenge.get_challenge(db, challenge_id=challenge_id) 179 | if not challenge: 180 | raise HTTPException(status_code=404, detail="Challenge not found") 181 | 182 | # Require proof2 if challenge has theorem2_signature 183 | if challenge.theorem2_signature and not proof2: 184 | return templates.TemplateResponse( 185 | "challenge_detail.html", 186 | { 187 | "request": request, 188 | "challenge": challenge, 189 | "user": current_user, 190 | "error": "Second proof is required for this challenge" 191 | } 192 | ) 193 | 194 | submission = schemas.SubmissionCreate(challenge_id=challenge_id, code=code, proof=proof, proof2=proof2) 195 | try: 196 | crud.submission.create_submission(db=db, submission=submission, user_id=user.id) 197 | logger.info('finished creating submission') 198 | return RedirectResponse(url=f"/challenges/{challenge_id}/submissions", status_code=status.HTTP_302_FOUND) 199 | except Exception as e: 200 | # Log the error 201 | print(f"Error creating submission: {str(e)}") 202 | return templates.TemplateResponse( 203 | "challenge_detail.html", 204 | {"request": request, "challenge": crud.challenge.get_challenge(db, challenge_id), "user": user, "error": "An error occurred while submitting. Please try again."} 205 | ) 206 | 207 | @app.get("/challenges/{challenge_id}/edit") 208 | async def edit_challenge_page( 209 | request: Request, 210 | challenge_id: int, 211 | db: Session = Depends(deps.get_db), 212 | current_user: User = Depends(get_current_user) 213 | ): 214 | if not current_user: 215 | return RedirectResponse(url="/login", status_code=status.HTTP_303_SEE_OTHER) 216 | 217 | challenge = crud.challenge.get_challenge(db, challenge_id) 218 | if not challenge: 219 | raise HTTPException(status_code=404, detail="Challenge not found") 220 | 221 | if challenge.owner_id != current_user.id: 222 | raise HTTPException(status_code=403, detail="Not authorized to edit this challenge") 223 | 224 | return templates.TemplateResponse( 225 | "edit_challenge.html", 226 | { 227 | "request": request, 228 | "challenge": challenge, 229 | "user": current_user 230 | } 231 | ) 232 | 233 | @app.post("/challenges/{challenge_id}/edit") 234 | async def edit_challenge( 235 | request: Request, 236 | challenge_id: int, 237 | title: str = Form(...), 238 | description: str = Form(...), 239 | function_signature: str = Form(...), 240 | theorem_signature: str = Form(...), 241 | theorem2_signature: str = Form(None), 242 | db: Session = Depends(deps.get_db), 243 | current_user: User = Depends(get_current_user) 244 | ): 245 | if not current_user: 246 | return RedirectResponse(url="/login", status_code=status.HTTP_303_SEE_OTHER) 247 | 248 | challenge = crud.challenge.get_challenge(db, challenge_id) 249 | if not challenge: 250 | raise HTTPException(status_code=404, detail="Challenge not found") 251 | 252 | if challenge.owner_id != current_user.id: 253 | raise HTTPException(status_code=403, detail="Not authorized to edit this challenge") 254 | 255 | try: 256 | updated_challenge = crud.challenge.update_challenge( 257 | db, 258 | challenge_id=challenge_id, 259 | challenge=schemas.ChallengeUpdate( 260 | title=title, 261 | description=description, 262 | function_signature=function_signature, 263 | theorem_signature=theorem_signature, 264 | theorem2_signature=theorem2_signature if theorem2_signature else None 265 | ), 266 | owner_id=current_user.id 267 | ) 268 | except ValueError as e: 269 | return templates.TemplateResponse( 270 | "edit_challenge.html", 271 | { 272 | "request": request, 273 | "challenge": challenge, 274 | "user": current_user, 275 | "error": str(e) 276 | } 277 | ) 278 | 279 | return RedirectResponse(url=f"/challenges/{challenge_id}", status_code=status.HTTP_303_SEE_OTHER) 280 | 281 | @app.get("/challenges/{challenge_id}/submissions") 282 | async def challenge_submissions( 283 | request: Request, 284 | challenge_id: int, 285 | page: int = 1, 286 | per_page: int = 20, 287 | db: Session = Depends(deps.get_db), 288 | current_user: dict = Depends(get_current_user) 289 | ): 290 | challenge = crud.challenge.get_challenge(db, challenge_id) 291 | if not challenge: 292 | raise HTTPException(status_code=404, detail="Challenge not found") 293 | 294 | skip = (page - 1) * per_page 295 | submissions = crud.submission.get_submissions_by_challenge(db, challenge_id, skip=skip, limit=per_page) 296 | 297 | return templates.TemplateResponse( 298 | "challenge_submissions.html", 299 | { 300 | "request": request, 301 | "challenge": challenge, 302 | "submissions": submissions, 303 | "page": page, 304 | "per_page": per_page, 305 | "user": current_user 306 | } 307 | ) 308 | 309 | @app.get("/submissions/{submission_id}") 310 | async def submission_detail( 311 | request: Request, 312 | submission_id: int, 313 | db: Session = Depends(deps.get_db), 314 | current_user: dict = Depends(get_current_user) 315 | ): 316 | submission = crud.submission.get_submission(db, submission_id) 317 | if not submission: 318 | raise HTTPException(status_code=404, detail="Submission not found") 319 | 320 | return templates.TemplateResponse( 321 | "submission_detail.html", 322 | { 323 | "request": request, 324 | "submission": submission, 325 | "user": current_user 326 | } 327 | ) 328 | 329 | 330 | @app.get("/register") 331 | async def register_page(request: Request): 332 | return templates.TemplateResponse("register.html", {"request": request}) 333 | 334 | @app.post("/register") 335 | async def register( 336 | request: Request, 337 | email: str = Form(...), 338 | display_name: str = Form(...), 339 | password: str = Form(...), 340 | confirm_password: str = Form(...), 341 | db: Session = Depends(deps.get_db) 342 | ): 343 | if password != confirm_password: 344 | return templates.TemplateResponse("register.html", {"request": request, "error": "Passwords do not match"}) 345 | 346 | try: 347 | user = UserCreate(email=email, display_name=display_name, password=password) 348 | crud.user.create_user(db, user) 349 | except ValueError as e: 350 | return templates.TemplateResponse("register.html", {"request": request, "error": str(e)}) 351 | 352 | return RedirectResponse(url="/login", status_code=status.HTTP_303_SEE_OTHER) 353 | 354 | 355 | 356 | 357 | -------------------------------------------------------------------------------- /scripts/code_contests_sample_passed.jsonl: -------------------------------------------------------------------------------- 1 | {"function_signature": "def beautifulTable (n k : Nat) : List (List Int)", "property_name": "beautifulTable_prop", "property_def": "def all_le (l : List Int) (bound : Int) : Bool :=\n l.all (fun x => x.natAbs ≤ bound)\n\ndef list_sum (l : List Int) : Int :=\n l.foldl (· + ·) 0\n\ndef all_lists_sum_to (lists : List (List Int)) (target : Int) : Bool :=\n lists.all (fun l => list_sum l = target)\n\ndef get_column (matrix : List (List Int)) (j : Nat) : List Int :=\n matrix.map (fun row => row[j]!)\n\ndef get_columns (matrix : List (List Int)) : List (List Int) :=\n let n := matrix[0]!.length\n List.range n |>.map (fun j => get_column matrix j)\n\ndef beautifulTable_prop (n k : Nat) (out : List (List Int)) : Prop :=\n let k_int := Int.ofNat k\n -- Matrix is n×n\n out.length = n ∧ \n out.all (fun row => row.length = n) ∧\n -- All elements ≤ 1000\n out.all (fun row => all_le row 1000) ∧\n -- All rows sum to k\n all_lists_sum_to out k_int ∧\n -- All columns sum to k\n all_lists_sum_to (get_columns out) k_int", "theorem_signature": "theorem beautifulTable_spec (n k : Nat) : beautifulTable_prop n k (beautifulTable n k)", "tests": ["4 7 [[7,0,0,0], [0,7,0,0], [0,0,7,0], [0,0,0,7]]", "2 4 [[4,0], [0,4]]"], "description": "Levko loves tables that consist of n rows and n columns very much. He especially loves beautiful tables. A table is beautiful to Levko if the sum of elements in each row and column of the table equals k.\n\nUnfortunately, he doesn't know any such table. Your task is to help him to find at least one of them. \n\nInput\n\nThe single line contains two integers, n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 1000).\n\nOutput\n\nPrint any beautiful table. Levko doesn't like too big numbers, so all elements of the table mustn't exceed 1000 in their absolute value.\n\nIf there are multiple suitable tables, you are allowed to print any of them.\n\nExamples\n\nInput\n\n2 4\n\n\nOutput\n\n1 3\n3 1\n\n\nInput\n\n4 7\n\n\nOutput\n\n2 1 0 4\n4 0 2 1\n1 3 3 0\n0 3 2 2\n\nNote\n\nIn the first sample the sum in the first row is 1 + 3 = 4, in the second row — 3 + 1 = 4, in the first column — 1 + 3 = 4 and in the second column — 3 + 1 = 4. There are other beautiful tables for this sample.\n\nIn the second sample the sum of elements in each row and each column equals 7. Besides, there are other tables that meet the statement requirements.", "test_results": [{"status": "pass", "feedback": ""}, {"status": "pass", "feedback": ""}], "status": "pass"} 2 | {"function_signature": "def min_shovels (k r : Nat) : Nat", "property_name": "min_shovels_prop", "property_def": "def isPayableWith10sAndR (amount r : Nat) : Bool :=\n let remainder := amount % 10\n remainder == 0 || remainder == r\n\ndef min_shovels_prop (k r out : Nat) : Prop := \n -- out must be positive\n out > 0 ∧ \n -- amount must be payable\n isPayableWith10sAndR (k * out) r ∧\n -- must be minimum\n ∀ n, n > 0 → n < out → ¬(isPayableWith10sAndR (k * n) r)", "theorem_signature": "theorem min_shovels_spec (k r : Nat) (h1 : k > 0) (h2 : r > 0) (h3 : r < 10) : min_shovels_prop k r (min_shovels k r)", "tests": ["237 7 1", "15 2 2", "117 3 9"], "description": "Polycarp urgently needs a shovel! He comes to the shop and chooses an appropriate one. The shovel that Policarp chooses is sold for k burles. Assume that there is an unlimited number of such shovels in the shop.\n\nIn his pocket Polycarp has an unlimited number of \"10-burle coins\" and exactly one coin of r burles (1 ≤ r ≤ 9).\n\nWhat is the minimum number of shovels Polycarp has to buy so that he can pay for the purchase without any change? It is obvious that he can pay for 10 shovels without any change (by paying the requied amount of 10-burle coins and not using the coin of r burles). But perhaps he can buy fewer shovels and pay without any change. Note that Polycarp should buy at least one shovel.\n\nInput\n\nThe single line of input contains two integers k and r (1 ≤ k ≤ 1000, 1 ≤ r ≤ 9) — the price of one shovel and the denomination of the coin in Polycarp's pocket that is different from \"10-burle coins\". \n\nRemember that he has an unlimited number of coins in the denomination of 10, that is, Polycarp has enough money to buy any number of shovels.\n\nOutput\n\nPrint the required minimum number of shovels Polycarp has to buy so that he can pay for them without any change. \n\nExamples\n\nInput\n\n117 3\n\n\nOutput\n\n9\n\n\nInput\n\n237 7\n\n\nOutput\n\n1\n\n\nInput\n\n15 2\n\n\nOutput\n\n2\n\nNote\n\nIn the first example Polycarp can buy 9 shovels and pay 9·117 = 1053 burles. Indeed, he can pay this sum by using 10-burle coins and one 3-burle coin. He can't buy fewer shovels without any change.\n\nIn the second example it is enough for Polycarp to buy one shovel.\n\nIn the third example Polycarp should buy two shovels and pay 2·15 = 30 burles. It is obvious that he can pay this sum without any change. ", "test_results": [{"status": "pass", "feedback": ""}, {"status": "pass", "feedback": ""}, {"status": "pass", "feedback": ""}], "status": "pass"} 3 | {"function_signature": "def vote_result (x y z : Nat) : String", "property_name": "vote_result_prop", "property_def": "def vote_result_prop (x y z : Nat) (out : String) : Prop :=\n (out = \"+\" ∧ ∀ k : Nat, k ≤ z → x + k > y + (z - k)) ∨\n (out = \"-\" ∧ ∀ k : Nat, k ≤ z → y + (z - k) > x + k) ∨\n (out = \"0\" ∧ ∀ k : Nat, k ≤ z → x + k = y + (z - k)) ∨\n (out = \"?\" ∧ ∃ k1 k2 : Nat, k1 ≤ z ∧ k2 ≤ z ∧\n ((x + k1 > y + (z - k1) ∧ x + k2 < y + (z - k2)) ∨\n (x + k1 = y + (z - k1) ∧ x + k2 ≠ y + (z - k2)) ∨\n (x + k1 < y + (z - k1) ∧ x + k2 > y + (z - k2))))", "theorem_signature": "theorem vote_result_spec (x y z : Nat) : vote_result_prop x y z (vote_result x y z)", "tests": ["3 7 0 \"-\"", "1 1 0 \"0\"", "0 0 1 \"?\"", "2 0 1 \"+\""], "description": "Nauuo is a girl who loves writing comments.\n\nOne day, she posted a comment on Codeforces, wondering whether she would get upvotes or downvotes.\n\nIt's known that there were x persons who would upvote, y persons who would downvote, and there were also another z persons who would vote, but you don't know whether they would upvote or downvote. Note that each of the x+y+z people would vote exactly one time.\n\nThere are three different results: if there are more people upvote than downvote, the result will be \"+\"; if there are more people downvote than upvote, the result will be \"-\"; otherwise the result will be \"0\".\n\nBecause of the z unknown persons, the result may be uncertain (i.e. there are more than one possible results). More formally, the result is uncertain if and only if there exist two different situations of how the z persons vote, that the results are different in the two situations.\n\nTell Nauuo the result or report that the result is uncertain.\n\nInput\n\nThe only line contains three integers x, y, z (0≤ x,y,z≤100), corresponding to the number of persons who would upvote, downvote or unknown.\n\nOutput\n\nIf there is only one possible result, print the result : \"+\", \"-\" or \"0\".\n\nOtherwise, print \"?\" to report that the result is uncertain.\n\nExamples\n\nInput\n\n\n3 7 0\n\n\nOutput\n\n\n-\n\nInput\n\n\n2 0 1\n\n\nOutput\n\n\n+\n\nInput\n\n\n1 1 0\n\n\nOutput\n\n\n0\n\nInput\n\n\n0 0 1\n\n\nOutput\n\n\n?\n\nNote\n\nIn the first example, Nauuo would definitely get three upvotes and seven downvotes, so the only possible result is \"-\".\n\nIn the second example, no matter the person unknown downvotes or upvotes, Nauuo would get more upvotes than downvotes. So the only possible result is \"+\".\n\nIn the third example, Nauuo would definitely get one upvote and one downvote, so the only possible result is \"0\".\n\nIn the fourth example, if the only one person upvoted, the result would be \"+\", otherwise, the result would be \"-\". There are two possible results, so the result is uncertain.", "test_results": [{"status": "pass", "feedback": ""}, {"status": "pass", "feedback": ""}, {"status": "pass", "feedback": ""}, {"status": "pass", "feedback": ""}], "status": "pass"} 4 | {"function_signature": "def findWinner (n : Nat) (teams : List String) : String", "property_name": "winner_prop", "property_def": "def countOccurrences (x : String) (xs : List String) : Nat :=\n xs.foldl (fun acc s => if s == x then acc + 1 else acc) 0\n\ndef uniqueTeams (teams : List String) : List String :=\n teams.foldl (fun acc s => if acc.contains s then acc else s::acc) []\n\ndef winner_prop (n : Nat) (teams : List String) (out : String) : Prop :=\n let uniq := uniqueTeams teams\n let counts := uniq.map (fun team => (team, countOccurrences team teams))\n counts.length ≤ 2 ∧ \n counts.length > 0 ∧\n (∃ team count, counts.contains (team, count) ∧ team = out ∧\n ∀ other_team other_count, counts.contains (other_team, other_count) → \n other_count ≤ count)", "theorem_signature": "theorem winner_spec (n : Nat) (teams : List String) : winner_prop n teams (findWinner n teams)", "tests": ["1 [\"ABC\"] \"ABC\"", "5 [\"A\", \"ABA\", \"ABA\", \"A\", \"A\"] \"A\""], "description": "One day Vasya decided to have a look at the results of Berland 1910 Football Championship’s finals. Unfortunately he didn't find the overall score of the match; however, he got hold of a profound description of the match's process. On the whole there are n lines in that description each of which described one goal. Every goal was marked with the name of the team that had scored it. Help Vasya, learn the name of the team that won the finals. It is guaranteed that the match did not end in a tie.\n\nInput\n\nThe first line contains an integer n (1 ≤ n ≤ 100) — the number of lines in the description. Then follow n lines — for each goal the names of the teams that scored it. The names are non-empty lines consisting of uppercase Latin letters whose lengths do not exceed 10 symbols. It is guaranteed that the match did not end in a tie and the description contains no more than two different teams.\n\nOutput\n\nPrint the name of the winning team. We remind you that in football the team that scores more goals is considered the winner.\n\nExamples\n\nInput\n\n1\nABC\n\n\nOutput\n\nABC\n\n\nInput\n\n5\nA\nABA\nABA\nA\nA\n\n\nOutput\n\nA", "test_results": [{"status": "pass", "feedback": "/var/tmp/tmpc2dm908m/true.lean:10:25: warning: unused variable `n`\nnote: this linter can be disabled with `set_option linter.unusedVariables false`"}, {"status": "pass", "feedback": "/var/tmp/tmpb36ftvo_/true.lean:10:25: warning: unused variable `n`\nnote: this linter can be disabled with `set_option linter.unusedVariables false`"}], "status": "pass"} 5 | {"function_signature": "def min_instability (n : Nat) (arr : Array Nat) : Nat", "property_name": "min_instability_prop", "property_def": "def array_max (arr : Array Nat) : Nat :=\n arr.foldl (fun acc x => max acc x) 0\n\ndef array_min (arr : Array Nat) : Nat :=\n arr.foldl (fun acc x => min acc x) (arr[0]!)\n\ndef instability (arr : Array Nat) : Nat :=\n array_max arr - array_min arr\n\ndef remove_at (arr : Array Nat) (i : Nat) : Array Nat :=\n (arr.extract 0 i).append (arr.extract (i+1) arr.size)\n\ndef min_instability_prop (n : Nat) (arr : Array Nat) (out : Nat) : Prop :=\n n = arr.size ∧ \n out = Id.run do\n let mut min_inst := instability (remove_at arr 0)\n for i in [1:n] do\n let curr_inst := instability (remove_at arr i)\n min_inst := min min_inst curr_inst\n min_inst", "theorem_signature": "theorem min_instability_spec (n : Nat) (arr : Array Nat) : min_instability_prop n arr (min_instability n arr)", "tests": ["4 #[1,3,3,7] 2", "2 #[1,100000] 0"], "description": "You are given an array a consisting of n integer numbers.\n\nLet instability of the array be the following value: max_{i = 1}^{n} a_i - min_{i = 1}^{n} a_i.\n\nYou have to remove exactly one element from this array to minimize instability of the resulting (n-1)-elements array. Your task is to calculate the minimum possible instability.\n\nInput\n\nThe first line of the input contains one integer n (2 ≤ n ≤ 10^5) — the number of elements in the array a.\n\nThe second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^5) — elements of the array a.\n\nOutput\n\nPrint one integer — the minimum possible instability of the array if you have to remove exactly one element from the array a.\n\nExamples\n\nInput\n\n\n4\n1 3 3 7\n\n\nOutput\n\n\n2\n\n\nInput\n\n\n2\n1 100000\n\n\nOutput\n\n\n0\n\nNote\n\nIn the first example you can remove 7 then instability of the remaining array will be 3 - 1 = 2.\n\nIn the second example you can remove either 1 or 100000 then instability of the remaining array will be 100000 - 100000 = 0 and 1 - 1 = 0 correspondingly.", "test_results": [{"status": "pass", "feedback": ""}, {"status": "pass", "feedback": ""}], "status": "pass"} 6 | {"function_signature": "def evenOddGame (n : Nat) : String", "property_name": "evenOddGame_prop", "property_def": "def isEven (n : Nat) : Bool := n % 2 = 0\n\ndef isValidMove (n : Nat) (isMahmoudTurn : Bool) (move : Nat) : Bool :=\n move ≤ n && move > 0 && (isMahmoudTurn = isEven move)\n\ndef hasValidMove (n : Nat) (isMahmoudTurn : Bool) : Prop :=\n ∃ m, isValidMove n isMahmoudTurn m = true\n\ndef isWinningPosition (n : Nat) (isMahmoudTurn : Bool) : Prop :=\n n > 0 ∧ hasValidMove n isMahmoudTurn\n\ndef evenOddGame_prop (n : Nat) (result : String) : Prop :=\n (result = \"Mahmoud\" ∧ isWinningPosition n true) ∨\n (result = \"Ehab\" ∧ ¬isWinningPosition n true)", "theorem_signature": "theorem evenOddGame_spec (n : Nat) : evenOddGame_prop n (evenOddGame n)", "tests": ["1 \"Ehab\"", "2 \"Mahmoud\""], "description": "Mahmoud and Ehab play a game called the even-odd game. Ehab chooses his favorite integer n and then they take turns, starting from Mahmoud. In each player's turn, he has to choose an integer a and subtract it from n such that:\n\n * 1 ≤ a ≤ n. \n * If it's Mahmoud's turn, a has to be even, but if it's Ehab's turn, a has to be odd. \n\n\n\nIf the current player can't choose any number satisfying the conditions, he loses. Can you determine the winner if they both play optimally?\n\nInput\n\nThe only line contains an integer n (1 ≤ n ≤ 109), the number at the beginning of the game.\n\nOutput\n\nOutput \"Mahmoud\" (without quotes) if Mahmoud wins and \"Ehab\" (without quotes) otherwise.\n\nExamples\n\nInput\n\n1\n\n\nOutput\n\nEhab\n\nInput\n\n2\n\n\nOutput\n\nMahmoud\n\nNote\n\nIn the first sample, Mahmoud can't choose any integer a initially because there is no positive even integer less than or equal to 1 so Ehab wins.\n\nIn the second sample, Mahmoud has to choose a = 2 and subtract it from n. It's Ehab's turn and n = 0. There is no positive odd integer less than or equal to 0 so Mahmoud wins.", "test_results": [{"status": "pass", "feedback": ""}, {"status": "pass", "feedback": ""}], "status": "pass"} 7 | {"function_signature": "def countRoomsForTwo (rooms: List (Nat × Nat)) : Nat", "property_name": "countRoomsForTwo_prop", "property_def": "def hasSpaceForTwo (room: Nat × Nat) : Bool :=\n let (current, capacity) := room\n capacity - current ≥ 2\n\ndef countRoomsForTwo_prop (rooms: List (Nat × Nat)) (out: Nat) : Prop := \n out = (rooms.filter hasSpaceForTwo).length", "theorem_signature": "theorem countRoomsForTwo_spec (rooms: List (Nat × Nat)) : countRoomsForTwo_prop rooms (countRoomsForTwo rooms)", "tests": ["[(1,1), (2,2), (3,3)] 0", "[(1,10), (0,10), (10,10)] 2"], "description": "George has recently entered the BSUCP (Berland State University for Cool Programmers). George has a friend Alex who has also entered the university. Now they are moving into a dormitory. \n\nGeorge and Alex want to live in the same room. The dormitory has n rooms in total. At the moment the i-th room has pi people living in it and the room can accommodate qi people in total (pi ≤ qi). Your task is to count how many rooms has free place for both George and Alex.\n\nInput\n\nThe first line contains a single integer n (1 ≤ n ≤ 100) — the number of rooms.\n\nThe i-th of the next n lines contains two integers pi and qi (0 ≤ pi ≤ qi ≤ 100) — the number of people who already live in the i-th room and the room's capacity.\n\nOutput\n\nPrint a single integer — the number of rooms where George and Alex can move in.\n\nExamples\n\nInput\n\n3\n1 1\n2 2\n3 3\n\n\nOutput\n\n0\n\n\nInput\n\n3\n1 10\n0 10\n10 10\n\n\nOutput\n\n2", "test_results": [{"status": "pass", "feedback": ""}, {"status": "pass", "feedback": ""}], "status": "pass"} 8 | {"function_signature": "def race_winner (s v1 v2 t1 t2 : Nat) : String", "property_name": "race_winner_prop", "property_def": "def get_total_time (s v t : Nat) : Nat :=\n t + s * v + t\n\ndef winner_to_string (time1 time2 : Nat) : String :=\n if time1 < time2 then \"First\"\n else if time2 < time1 then \"Second\"\n else \"Friendship\"\n\ndef race_winner_prop (s v1 v2 t1 t2 : Nat) (out : String) : Prop :=\n let time1 := get_total_time s v1 t1\n let time2 := get_total_time s v2 t2\n out = winner_to_string time1 time2", "theorem_signature": "theorem race_winner_spec (s v1 v2 t1 t2 : Nat) : race_winner_prop s v1 v2 t1 t2 (race_winner s v1 v2 t1 t2)", "tests": ["5 1 2 1 2 \"First\"", "3 3 1 1 1 \"Second\"", "4 5 3 1 5 \"Friendship\""], "description": "Two boys decided to compete in text typing on the site \"Key races\". During the competition, they have to type a text consisting of s characters. The first participant types one character in v1 milliseconds and has ping t1 milliseconds. The second participant types one character in v2 milliseconds and has ping t2 milliseconds.\n\nIf connection ping (delay) is t milliseconds, the competition passes for a participant as follows: \n\n 1. Exactly after t milliseconds after the start of the competition the participant receives the text to be entered. \n 2. Right after that he starts to type it. \n 3. Exactly t milliseconds after he ends typing all the text, the site receives information about it. \n\n\n\nThe winner is the participant whose information on the success comes earlier. If the information comes from both participants at the same time, it is considered that there is a draw.\n\nGiven the length of the text and the information about participants, determine the result of the game.\n\nInput\n\nThe first line contains five integers s, v1, v2, t1, t2 (1 ≤ s, v1, v2, t1, t2 ≤ 1000) — the number of characters in the text, the time of typing one character for the first participant, the time of typing one character for the the second participant, the ping of the first participant and the ping of the second participant.\n\nOutput\n\nIf the first participant wins, print \"First\". If the second participant wins, print \"Second\". In case of a draw print \"Friendship\".\n\nExamples\n\nInput\n\n5 1 2 1 2\n\n\nOutput\n\nFirst\n\n\nInput\n\n3 3 1 1 1\n\n\nOutput\n\nSecond\n\n\nInput\n\n4 5 3 1 5\n\n\nOutput\n\nFriendship\n\nNote\n\nIn the first example, information on the success of the first participant comes in 7 milliseconds, of the second participant — in 14 milliseconds. So, the first wins.\n\nIn the second example, information on the success of the first participant comes in 11 milliseconds, of the second participant — in 5 milliseconds. So, the second wins.\n\nIn the third example, information on the success of the first participant comes in 22 milliseconds, of the second participant — in 22 milliseconds. So, it is be a draw.", "test_results": [{"status": "pass", "feedback": ""}, {"status": "pass", "feedback": ""}, {"status": "pass", "feedback": ""}], "status": "pass"} 9 | {"function_signature": "def findPoint (n k : Nat) (squares : Array Nat) : Option (Nat × Nat × Bool)", "property_name": "findPoint_prop", "property_def": "def inSquare (x y a : Nat) : Bool :=\n x <= a && y <= a\n\ndef countSquares (x y : Nat) (squares : Array Nat) : Nat :=\n squares.foldl (fun count a => if inSquare x y a then count + 1 else count) 0\n\ndef findPoint_prop (n k : Nat) (squares : Array Nat) (res : Option (Nat × Nat × Bool)) : Prop :=\n match res with\n | none => ∀ x y : Nat, countSquares x y squares ≠ k\n | some (x, y, false) => countSquares x y squares = k ∧ \n x ≤ 1000000000 ∧ y ≤ 1000000000\n | some (_, _, true) => false", "theorem_signature": "theorem findPoint_spec (n k : Nat) (squares : Array Nat) : findPoint_prop n k squares (findPoint n k squares)", "tests": ["3 1 #[2,4,1] (some (4,0,false))", "4 3 #[5,1,3,4] (some (2,1,false))", "4 50 #[5,1,10,2] none"], "description": "Vasya has found a piece of paper with a coordinate system written on it. There are n distinct squares drawn in this coordinate system. Let's number the squares with integers from 1 to n. It turned out that points with coordinates (0, 0) and (ai, ai) are the opposite corners of the i-th square.\n\nVasya wants to find such integer point (with integer coordinates) of the plane, that belongs to exactly k drawn squares. We'll say that a point belongs to a square, if the point is located either inside the square, or on its boundary. \n\nHelp Vasya find a point that would meet the described limits.\n\nInput\n\nThe first line contains two space-separated integers n, k (1 ≤ n, k ≤ 50). The second line contains space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109).\n\nIt is guaranteed that all given squares are distinct.\n\nOutput\n\nIn a single line print two space-separated integers x and y (0 ≤ x, y ≤ 109) — the coordinates of the point that belongs to exactly k squares. If there are multiple answers, you are allowed to print any of them. \n\nIf there is no answer, print \"-1\" (without the quotes).\n\nExamples\n\nInput\n\n4 3\n5 1 3 4\n\n\nOutput\n\n2 1\n\n\nInput\n\n3 1\n2 4 1\n\n\nOutput\n\n4 0\n\n\nInput\n\n4 50\n5 1 10 2\n\n\nOutput\n\n-1", "test_results": [{"status": "pass", "feedback": "/var/tmp/tmp02l9gy7b/true.lean:10:28: warning: unused variable `n`\nnote: this linter can be disabled with `set_option linter.unusedVariables false`"}, {"status": "pass", "feedback": "/var/tmp/tmpre2kfqgo/true.lean:10:28: warning: unused variable `n`\nnote: this linter can be disabled with `set_option linter.unusedVariables false`"}, {"status": "pass", "feedback": "/var/tmp/tmpro6pftk4/true.lean:10:28: warning: unused variable `n`\nnote: this linter can be disabled with `set_option linter.unusedVariables false`"}], "status": "pass"} 10 | {"function_signature": "def dice_game (a b : Nat) : Nat × Nat × Nat", "property_name": "count_outcomes_prop", "property_def": "def abs_diff (x y : Nat) : Nat :=\n if x ≥ y then x - y else y - x\n\ndef is_closer (player other dice : Nat) : Bool :=\n abs_diff player dice < abs_diff other dice\n\ndef is_equal_dist (player other dice : Nat) : Bool :=\n abs_diff player dice = abs_diff other dice\n\ndef count_outcomes_prop (a b first draw second : Nat) : Prop :=\n first + draw + second = 6 ∧\n first = ((List.range 6).filter (fun d => is_closer a b (d+1))).length ∧\n draw = ((List.range 6).filter (fun d => is_equal_dist a b (d+1))).length ∧\n second = ((List.range 6).filter (fun d => is_closer b a (d+1))).length", "theorem_signature": "theorem dice_game_spec (a b : Nat) : let (first, draw, second) := dice_game a b; count_outcomes_prop a b first draw second", "tests": ["2 5 3 0 3", "2 4 2 1 3"], "description": "Two players are playing a game. First each of them writes an integer from 1 to 6, and then a dice is thrown. The player whose written number got closer to the number on the dice wins. If both payers have the same difference, it's a draw.\n\nThe first player wrote number a, the second player wrote number b. How many ways to throw a dice are there, at which the first player wins, or there is a draw, or the second player wins?\n\nInput\n\nThe single line contains two integers a and b (1 ≤ a, b ≤ 6) — the numbers written on the paper by the first and second player, correspondingly.\n\nOutput\n\nPrint three integers: the number of ways to throw the dice at which the first player wins, the game ends with a draw or the second player wins, correspondingly.\n\nExamples\n\nInput\n\n2 5\n\n\nOutput\n\n3 0 3\n\n\nInput\n\n2 4\n\n\nOutput\n\n2 1 3\n\nNote\n\nThe dice is a standard cube-shaped six-sided object with each side containing a number from 1 to 6, and where all numbers on all sides are distinct.\n\nYou can assume that number a is closer to number x than number b, if |a - x| < |b - x|.", "test_results": [{"status": "pass", "feedback": ""}, {"status": "pass", "feedback": ""}], "status": "pass"} 11 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------