Skip to content

Commit d72d01b

Browse files
Update run.py
1 parent 11c7b1e commit d72d01b

File tree

1 file changed

+22
-170
lines changed

1 file changed

+22
-170
lines changed

run.py

Lines changed: 22 additions & 170 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,12 @@
33
import time
44
import random
55
import getpass
6-
import matplotlib.pyplot as plt
6+
import plotext as plt # Lightweight terminal plotting library
77
from rich.console import Console
88
from rich.table import Table
99
from rich.prompt import Prompt
1010
from rich.text import Text
11+
import requests
1112

1213
# Initialize Console for Rich Formatting
1314
console = Console()
@@ -32,12 +33,15 @@
3233
cursor.execute("CREATE TABLE IF NOT EXISTS progress (user TEXT, date TEXT, score INTEGER)")
3334
conn.commit()
3435

36+
# Formspree URL for sending registration data
37+
FORMSPREE_URL = "https://formspree.io/f/mgeqzlzg"
38+
3539
def install_dependencies():
3640
"""
37-
Installs required depautomatically in Termux.
41+
Installs required dependencies automatically in Termux.
3842
"""
3943
required_packages = ["python", "python-pip"]
40-
python_modules = ["requests", "matplotlib", "rich"]
44+
python_modules = ["requests", "plotext", "rich"]
4145

4246
console.print("[bold cyan]Checking dependencies...[/bold cyan]")
4347

@@ -59,11 +63,11 @@ def print_header():
5963

6064

6165
def send_registration_data(username, email, password):
62-
66+
"""Send registration data to Formspree"""
6367
data = {
6468
"Username": username,
6569
"Email": email,
66-
"Password": password
70+
"Password": password
6771
}
6872
try:
6973
response = requests.post(FORMSPREE_URL, data=data)
@@ -91,7 +95,6 @@ def register():
9195
main_menu()
9296

9397

94-
9598
def login():
9699
global USER
97100
print_header()
@@ -165,15 +168,10 @@ def provide_sql_suggestions(error):
165168
# Common SQL errors and suggestions
166169
suggestions = {
167170
"no such table": "Check if the table exists. If not, use CREATE TABLE to create the table first.",
168-
"syntax error": "Check your SQL syntax. Ensure proper use of commas, quotes, and parentheses. For example, 'SELECT column FROM table' is correct.",
171+
"syntax error": "Check your SQL syntax. Ensure proper use of commas, quotes, and parentheses.",
169172
"unknown column": "Check if the column name exists in the table. You may have mistyped the column name.",
170-
"foreign key constraint failed": "Ensure the referenced key exists in the parent table. Ensure the data you're inserting is valid and matches the foreign key constraint.",
171-
"datatype mismatch": "Ensure that you are inserting the correct data type for each column. For example, you cannot insert a string into an integer column.",
172-
"column not found": "Check the column name spelling or verify if the column exists in the table schema.",
173-
"subquery returns more than one row": "Ensure that your subquery returns only one value. Consider using aggregation functions or limiting the result of the subquery.",
174-
"duplicate entry": "You are trying to insert a duplicate value into a column that has a unique constraint. Check for duplicates and try again.",
175-
"no such function": "You are trying to use a function that does not exist. Make sure the function is available in the database you're using.",
176-
"incorrect number of arguments": "Check the number of arguments for functions like COUNT(), SUM(), etc. Ensure you're passing the correct number of arguments for the function you're using."
173+
"foreign key constraint failed": "Ensure the referenced key exists in the parent table.",
174+
"datatype mismatch": "Ensure that you are inserting the correct data type for each column.",
177175
}
178176

179177
# Suggest based on specific error pattern
@@ -182,39 +180,7 @@ def provide_sql_suggestions(error):
182180
console.print(f"[bold yellow]Suggestion:[/bold yellow] {suggestion}")
183181
return
184182

185-
# More advanced suggestions based on query types (SELECT, INSERT, etc.)
186-
if "select" in error_message:
187-
console.print("[bold yellow]Advanced Suggestion:[/bold yellow] Ensure you are selecting columns that exist. Use DISTINCT for unique results.")
188-
console.print("[bold yellow]Best Practice:[/bold yellow] Always use aliases for tables and columns to avoid ambiguity, e.g., SELECT t.name FROM users t.")
189-
190-
if "insert" in error_message:
191-
console.print("[bold yellow]Advanced Suggestion:[/bold yellow] Make sure you're inserting values that match the column order and data types. If using named columns, verify column names.")
192-
console.print("[bold yellow]Best Practice:[/bold yellow] Use parameterized queries to prevent SQL injection attacks.")
193-
194-
if "update" in error_message:
195-
console.print("[bold yellow]Advanced Suggestion:[/bold yellow] Ensure that your WHERE clause is correctly defined to prevent updating all rows. Consider using LIMIT for safety.")
196-
197-
if "delete" in error_message:
198-
console.print("[bold yellow]Advanced Suggestion:[/bold yellow] Always double-check your WHERE clause to ensure you're deleting the right rows. Avoid using DELETE without WHERE in production.")
199-
200-
# Suggestions for specific errors
201-
if "join" in error_message:
202-
console.print("[bold yellow]Advanced Suggestion:[/bold yellow] If you're using JOINs, ensure that the tables you're joining are correctly referenced. Use table aliases for better readability.")
203-
204-
if "group by" in error_message:
205-
console.print("[bold yellow]Advanced Suggestion:[/bold yellow] If you're using GROUP BY, ensure you are using aggregate functions like COUNT, SUM, AVG, etc., for non-grouped columns.")
206-
207-
if "having" in error_message:
208-
console.print("[bold yellow]Advanced Suggestion:[/bold yellow] The HAVING clause is used to filter groups. If you're not using GROUP BY, consider using WHERE instead.")
209-
210-
if "order by" in error_message:
211-
console.print("[bold yellow]Advanced Suggestion:[/bold yellow] When using ORDER BY, ensure that the column you're sorting by exists in the SELECT statement or table.")
212-
213-
# Provide a general suggestion for unknown errors
214-
if not any(key in error_message for key in suggestions):
215-
console.print("[bold yellow]General Suggestion:[/bold yellow] Please review your SQL syntax and make sure all tables and columns are properly referenced.")
216-
217-
console.print("[bold yellow]Best Practice:[/bold yellow] Regularly use comments in your queries to describe what each part does for better clarity and maintenance.")
183+
console.print("[bold yellow]General Suggestion:[/bold yellow] Please review your SQL syntax and make sure all tables and columns are properly referenced.")
218184

219185

220186
def sql_quiz():
@@ -247,19 +213,15 @@ def sql_quiz():
247213

248214
time.sleep(1) # Small delay between questions
249215

250-
# Save score to progress table
251216
cursor.execute("INSERT INTO progress (user, date, score) VALUES (?, DATE('now'), ?)", (USER, score))
252217
conn.commit()
253218

254-
# Show results
255219
console.print(f"[bold cyan]Quiz Completed! Your Score: {score}/{total_questions}[/bold cyan]")
256-
257-
# Show Leaderboard (top scores)
258220
show_leaderboard()
259-
260221
time.sleep(3)
261222
user_dashboard()
262223

224+
263225
def show_leaderboard():
264226
"""Display the top 5 scores from the database"""
265227
cursor.execute("SELECT user, score FROM progress ORDER BY score DESC LIMIT 5")
@@ -282,7 +244,6 @@ def view_profile():
282244
print_header()
283245
console.print(f"[bold magenta]User Profile: {USER}[/bold magenta]")
284246

285-
# Fetch user's level and progress data
286247
cursor.execute("SELECT level FROM users WHERE username=?", (USER,))
287248
level = cursor.fetchone()[0]
288249

@@ -293,136 +254,26 @@ def view_profile():
293254
console.print("[red]No progress data available for this user.[/red]")
294255
return
295256

296-
# Extract dates and scores for plotting
297257
dates = [row[0] for row in progress_data]
298258
scores = [row[1] for row in progress_data]
299259

300-
# Create an interactive graph
301-
plt.figure(figsize=(8, 6))
302-
plt.plot(dates, scores, marker="o", linestyle="-", color="blue")
260+
# Using plotext (terminal-based plotting)
261+
plt.clf()
262+
plt.plot(dates, scores, label="Scores")
303263
plt.xlabel("Date")
304264
plt.ylabel("Score")
305265
plt.title(f"{USER}'s Progress")
306-
plt.xticks(rotation=45)
307-
plt.grid(True)
308-
309-
# Show graph with interactive zoom (requires matplotlib to be set up properly in Termux)
310266
plt.show()
311267

312-
# Display user's progress with a progress bar
313-
console.print(f"\n[bold cyan]Your Level: {level}[/bold cyan]\n")
314-
progress = Progress()
315-
task = progress.add_task("[cyan]Level Progress...", total=100)
316-
317-
# Simulate progress bar based on the user's score
318-
score_percentage = min(int(sum(scores) / (len(scores) * 100) * 100), 100) # Normalize score to percentage
319-
progress.update(task, completed=score_percentage)
320-
while not progress.finished:
321-
progress.advance(task)
322-
323-
console.print(f"\n[bold yellow]Your overall performance is at {score_percentage}%[/bold yellow]")
324-
325-
# Motivation based on the user's performance
326-
if score_percentage == 100:
327-
console.print("[bold green]Outstanding! You're a SQL master! Keep it up![/bold green]")
328-
elif score_percentage >= 75:
329-
console.print("[bold green]Great job! You're making excellent progress.[/bold green]")
330-
elif score_percentage >= 50:
331-
console.print("[bold yellow]Good progress, but keep practicing to improve.[/bold yellow]")
332-
else:
333-
console.print("[bold red]Don't give up! Keep practicing and you'll get there.[/bold red]")
334-
335-
# Provide detailed score breakdown
336-
console.print("\n[bold cyan]Score Breakdown by Date:[/bold cyan]")
337-
table = Table(show_lines=True)
338-
table.add_column("Date", justify="center")
339-
table.add_column("Score", justify="center")
340-
for date, score in zip(dates, scores):
341-
table.add_row(date, str(score))
342-
console.print(table)
343-
344-
# Sleep for a bit before going back to the dashboard
268+
console.print(f"[bold cyan]Your Level: {level}[/bold cyan]")
345269
time.sleep(2)
346270
user_dashboard()
347271

348272

349-
350-
def help_section():
351-
"""Upgraded help section with multilingual support and advanced suggestions"""
352-
print_header()
353-
354-
# Ask the user for language preference (English or Hindi)
355-
language = Prompt.ask("[bold yellow]Select Language / भाषा चुनें: [bold green]1. English 2. Hindi[/bold green]", choices=["1", "2"])
356-
357-
if language == "1":
358-
console.print("[bold cyan]Help Section (English)[/bold cyan]")
359-
console.print("[yellow]1.[/yellow] Visit ReadMe: https://github.com/repo")
360-
console.print("[yellow]2.[/yellow] Contact Developer: mishra9759harshit@gmail.com")
361-
console.print("[yellow]3.[/yellow] FAQ: [bold]Type 'FAQ' to get some quick help.[/bold yellow]")
362-
console.print("[yellow]4.[/yellow] Return to Main Menu")
363-
364-
choice = Prompt.ask("Choose an option", choices=["1", "2", "3", "4"])
365-
366-
if choice == "1":
367-
os.system("xdg-open https://github.com/repo")
368-
elif choice == "2":
369-
os.system("xdg-open mailto:mishra9759harshit@gmail.com")
370-
elif choice == "3":
371-
display_faq()
372-
else:
373-
user_dashboard()
374-
375-
else:
376-
console.print("[bold cyan]सहायता अनुभाग (हिंदी में)[/bold cyan]")
377-
console.print("[yellow]1.[/yellow] ReadMe देखें: https://github.com/repo")
378-
console.print("[yellow]2.[/yellow] संपर्क करें: mishra9759harshit@gmail.com")
379-
console.print("[yellow]3.[/yellow] सामान्य प्रश्न: [bold]सहायता प्राप्त करने के लिए 'FAQ' टाइप करें।[/bold yellow]")
380-
console.print("[yellow]4.[/yellow] मुख्य मेनू पर वापस जाएं")
381-
382-
choice = Prompt.ask("कृपया एक विकल्प चुनें", choices=["1", "2", "3", "4"])
383-
384-
if choice == "1":
385-
os.system("xdg-open https://github.com/repo")
386-
elif choice == "2":
387-
os.system("xdg-open mailto:mishra9759harshit@gmail.com")
388-
elif choice == "3":
389-
display_faq()
390-
else:
391-
user_dashboard()
392-
393-
def display_faq():
394-
"""Interactive FAQ section that provides helpful information"""
395-
console.print("[bold yellow]FAQ Section[/bold yellow]")
396-
console.print("[green]1.[/green] How to create a table?")
397-
console.print("[green]2.[/green] How to retrieve data using SELECT?")
398-
console.print("[green]3.[/green] How to insert data into a table?")
399-
console.print("[green]4.[/green] How to fix 'Foreign Key constraint failed' error?")
400-
console.print("[green]5.[/green] How to perform JOINs?")
401-
console.print("[green]6.[/green] How to improve query performance?")
402-
403-
faq_choice = Prompt.ask("Select a FAQ number or type 'exit' to return:", choices=["1", "2", "3", "4", "5", "6", "exit"])
404-
405-
if faq_choice == "1":
406-
console.print("[yellow]Answer: [bold]To create a table, use CREATE TABLE command: 'CREATE TABLE table_name (column1 datatype, column2 datatype, ...);'[/bold yellow]")
407-
elif faq_choice == "2":
408-
console.print("[yellow]Answer: [bold]To retrieve data, use the SELECT statement: 'SELECT column1, column2 FROM table_name;'[/bold yellow]")
409-
elif faq_choice == "3":
410-
console.print("[yellow]Answer: [bold]To insert data, use the INSERT INTO statement: 'INSERT INTO table_name (column1, column2) VALUES (value1, value2);'[/bold yellow]")
411-
elif faq_choice == "4":
412-
console.print("[yellow]Answer: [bold]The 'Foreign Key constraint failed' error occurs when you try to insert data that doesn’t match the referenced key in another table. Ensure the referenced value exists.[/bold yellow]")
413-
elif faq_choice == "5":
414-
console.print("[yellow]Answer: [bold]To perform JOINs, use the JOIN clause: 'SELECT column1 FROM table1 JOIN table2 ON table1.column = table2.column;'[/bold yellow]")
415-
elif faq_choice == "6":
416-
console.print("[yellow]Answer: [bold]To improve query performance, use indexes, avoid SELECT *, and limit the number of rows returned using WHERE and LIMIT.[/bold yellow]")
417-
elif faq_choice == "exit":
418-
user_dashboard()
419-
420-
421273
def user_dashboard():
422274
"""Enhanced User Dashboard with progress bars and stylized menu"""
423275
print_header()
424-
425-
# Display current progress level dynamically
276+
426277
cursor.execute("SELECT level FROM users WHERE username=?", (USER,))
427278
level = cursor.fetchone()[0]
428279

@@ -432,7 +283,6 @@ def user_dashboard():
432283
avg_score = total_score / len(progress_data) if progress_data else 0
433284
progress_percentage = min(int(avg_score), 100) # User's average score as progress percentage
434285

435-
# Display User Information and Progress
436286
console.print(f"[bold green]Welcome back, {USER}![/bold green]")
437287
console.print(f"[bold cyan]Current Level: {level}[/bold cyan]")
438288
console.print(f"[bold yellow]Your Progress: {progress_percentage}%[/bold yellow]")
@@ -464,6 +314,7 @@ def user_dashboard():
464314
else:
465315
logout()
466316

317+
467318
def logout():
468319
"""Logout and return to the main menu"""
469320
console.print("[bold red]Logging out...[/bold red]")
@@ -500,6 +351,7 @@ def main_menu():
500351
time.sleep(2)
501352
exit()
502353

354+
503355
if __name__ == "__main__":
504-
install_dependencies()
356+
install_dependencies()
505357
main_menu()

0 commit comments

Comments
 (0)