From cf7273999dc2429aa57ff053e5f16f3c3ae14cf2 Mon Sep 17 00:00:00 2001 From: Pathompum Jirakarnpaisan <107536914+Saannddy@users.noreply.github.com> Date: Sat, 4 Apr 2026 00:09:18 +0700 Subject: [PATCH 1/6] refactor: update Java snippet descriptions to use descriptive, human-readable instructions --- src/scripts/data/java/hallway/chunks.json | 30 +++++++++++------------ 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/src/scripts/data/java/hallway/chunks.json b/src/scripts/data/java/hallway/chunks.json index 3825be2..e62a23d 100644 --- a/src/scripts/data/java/hallway/chunks.json +++ b/src/scripts/data/java/hallway/chunks.json @@ -8,9 +8,9 @@ "name": "Java Implementation", "template_code": "import java.util.*;\n\npublic class Solution {\n public static void main(String[] args) {\n Scanner scanner = new Scanner(System.in);\n int core_temp = scanner.hasNextInt() ? scanner.nextInt() : 0;\n int access_code = scanner.hasNextInt() ? scanner.nextInt() : 0;\n String main_grid = scanner.hasNext() ? scanner.next() : \"\";\n int battery_level = scanner.hasNextInt() ? scanner.nextInt() : 0;\n \n boolean coolant = false;\n String vault_door = \"LOCKED\";\n String backup_power = \"OFF\";\n\n //TASK 1: COOLING LOGIC\n{{{snippet_1}}}\n coolant = true;\n}\n//TASK 2: VAULT ACCESS\n{{{snippet_2}}}\n vault_door = \"OPEN\";\n}\n//TASK 3: POWER FAILSAFE (ADVANCED)\n{{{snippet_3}}}\n backup_power = \"ON\";\n}\n \n System.out.print(coolant + \"|\" + vault_door + \"|\" + backup_power);\n }\n}", "snippets": { - "snippet_1": "if (core_temp >= 90) {", - "snippet_2": "if (access_code == 7734) {", - "snippet_3": "if (main_grid == \"OFF\" && battery_level < 20) {" + "snippet_1": "Safety Protocol: The cooling system must activate (coolant = true) only if the core_temp reaches or exceeds 90.", + "snippet_2": "Security Override: The room_321_door should remain LOCKED unless the access_code provided is exactly 7734.", + "snippet_3": "Power Management: Emergency backup_power must be ON if the main_grid is OFF AND the battery_level is below 20." } } }, @@ -28,9 +28,9 @@ "name": "Java Implementation", "template_code": "import java.util.*;\n\npublic class Solution {\n public static void main(String[] args) {\n Scanner scanner = new Scanner(System.in);\n int core_temp = scanner.hasNextInt() ? scanner.nextInt() : 0;\n int access_code = scanner.hasNextInt() ? scanner.nextInt() : 0;\n String main_grid = scanner.hasNext() ? scanner.next() : \"\";\n int battery_level = scanner.hasNextInt() ? scanner.nextInt() : 0;\n \n boolean coolant = false;\n String vault_door = \"LOCKED\";\n String backup_power = \"OFF\";\n\n //TASK 1: GATEWAY OVERRIDE\n {{{snippet_1}}}\ngateway = \"OPEN\";\n}\n//TASK 2: PACKET FILTER\n {{{snippet_2}}}\ndrop_packet = true;\n}\n//TASK 3: SSL HANDSHAKE\n {{{snippet_3}}}\nsecure_connection = true;\n}\n \n System.out.print(coolant + \"|\" + vault_door + \"|\" + backup_power);\n }\n}", "snippets": { - "snippet_1": "if (ip_address == \"192.168.1.1\") {", - "snippet_2": "if (protocol == \"UDP\" && port == 80) {", - "snippet_3": "if (cert_expiry > 2026) {" + "snippet_1": "Gateway Override: The gateway will only open if the incoming ip_address is exactly \"192.168.1.1\"", + "snippet_2": "Packet Filter: Packet should be dropped if port is 80 and protocol is UDP", + "snippet_3": "SSL Handshake: Only create connection when the cert expiration date is over 2026" } } }, @@ -48,9 +48,9 @@ "name": "Java Implementation", "template_code": "import java.util.*;\n\npublic class Solution {\n public static void main(String[] args) {\n Scanner scanner = new Scanner(System.in);\n int core_temp = scanner.hasNextInt() ? scanner.nextInt() : 0;\n int access_code = scanner.hasNextInt() ? scanner.nextInt() : 0;\n String main_grid = scanner.hasNext() ? scanner.next() : \"\";\n int battery_level = scanner.hasNextInt() ? scanner.nextInt() : 0;\n \n boolean coolant = false;\n String vault_door = \"LOCKED\";\n String backup_power = \"OFF\";\n\n // TASK 1: AI OUTPUT SANITIZATION\n{{{snippet_1}}}\n ai_output = \"CONTAINED\";\n}\n// TASK 2: CONTAINMENT FIELD LOGIC\n{{{snippet_2}}}\n containment_field = \"ACTIVE\";\n}\n// TASK 3: ENCRYPTION CHECK (ADVANCED)\n{{{snippet_3}}}\n access_granted = true;\n}\n \n System.out.print(coolant + \"|\" + vault_door + \"|\" + backup_power);\n }\n}", "snippets": { - "snippet_1": "if (ai_response_string == \"CRITICAL ERROR\") {", - "snippet_2": "if (core_stability < 0.2 && core_temperature > 500) {", - "snippet_3": "if (encryption_type == \"RSA\" || encryption_type == \"AES\") {" + "snippet_1": "Output Sanitization: If the ai_response_string is a \"CRITICAL ERROR\", the output must be set to \"CONTAINED\".", + "snippet_2": "Field Logic: The containment_field must be set to \"ACTIVE\" if the core_stability drops below 0.2 AND the core_temperature is over 500 degrees.", + "snippet_3": "Advanced Protocol: Access is granted (access_granted = true) only if the provided encryption_type is exactly \"RSA\" OR exactly \"AES\"." } } }, @@ -68,9 +68,9 @@ "name": "Java Implementation", "template_code": "import java.util.*;\n\npublic class Solution {\n public static void main(String[] args) {\n Scanner scanner = new Scanner(System.in);\n int core_temp = scanner.hasNextInt() ? scanner.nextInt() : 0;\n int access_code = scanner.hasNextInt() ? scanner.nextInt() : 0;\n String main_grid = scanner.hasNext() ? scanner.next() : \"\";\n int battery_level = scanner.hasNextInt() ? scanner.nextInt() : 0;\n \n boolean coolant = false;\n String vault_door = \"LOCKED\";\n String backup_power = \"OFF\";\n\n //TASK 1: OXYGEN RECLAMATION\n{{{snippet_1}}}\nscrubber_status = \"MAX\";\n}\n//TASK 2: THERMAL REGULATION\n{{{snippet_2}}}\nheater = \"ON\";\n}\n//TASK 3: WATER FILTRATION (ADVANCED)\n{{{snippet_3}}}\nflush_filter = true;\n}\n \n System.out.print(coolant + \"|\" + vault_door + \"|\" + backup_power);\n }\n}", "snippets": { - "snippet_1": "if (co2_level > 0.05) {", - "snippet_2": "if (ambient_temp < 18) {", - "snippet_3": "if (psi >= 60 && turbidity > 5) {" + "snippet_1": "Atmospheric Safety: If the co2_level exceeds 0.05, the carbon scrubbers must be set to \"MAX\".", + "snippet_2": "Thermal regulation: The heater should be on when the ambient temp is lower than 18", + "snippet_3": "Maintenance Cycle: The filter must flush (true) only if the pressure (psi) is 60 or higher AND turbidity is above 5." } } }, @@ -88,9 +88,9 @@ "name": "Java Implementation", "template_code": "import java.util.*;\n\npublic class Solution {\n public static void main(String[] args) {\n Scanner scanner = new Scanner(System.in);\n int core_temp = scanner.hasNextInt() ? scanner.nextInt() : 0;\n int access_code = scanner.hasNextInt() ? scanner.nextInt() : 0;\n String main_grid = scanner.hasNext() ? scanner.next() : \"\";\n int battery_level = scanner.hasNextInt() ? scanner.nextInt() : 0;\n \n boolean coolant = false;\n String vault_door = \"LOCKED\";\n String backup_power = \"OFF\";\n\n //TASK 1: PERIMETER SCAN\n{{{snippet_1}}}\nalarm_siren = true;\n}\n//TASK 2: TURRET CALIBRATION\n{{{snippet_2}}}\ntarget_lock = \"LOCKED\";\n}\n//TASK 3: BIOMETRIC OVERRIDE\n{{{snippet_3}}}\ngate_bypass = true;\n}\n \n System.out.print(coolant + \"|\" + vault_door + \"|\" + backup_power);\n }\n}", "snippets": { - "snippet_1": "if (motion_detected == true && authorized == false) {", - "snippet_2": "if (distance <= 500 && visibility == \"CLEAR\") {", - "snippet_3": "if (admin_key == 99) {" + "snippet_1": "Intruder Alert: Sound the alarm only if motion_detected is true AND the target is NOT authorized.", + "snippet_2": "Targeting System: The target_lock should engage if the distance is 500 or less and visibility is \"CLEAR\".", + "snippet_3": "Biometric Override: If the admin key is exactly 99, the gate bypass should be activated." } } }, From 7315d899554cfe82b62db363edf6d21b3819ce40 Mon Sep 17 00:00:00 2001 From: Pathompum Jirakarnpaisan <107536914+Saannddy@users.noreply.github.com> Date: Sat, 4 Apr 2026 00:25:18 +0700 Subject: [PATCH 2/6] refactor: update Java chunk schema to use object-based templates and remove hardcoded solution snippets --- bruno/local/Chunk/Execute Java Chunk.bru | 23 +++++ src/scripts/data/java/lockerroom/chunks.json | 94 ++++++-------------- src/scripts/data/java/temp/chunks.json | 22 +++++ src/scripts/seeders/seed_lockerroom_java.py | 8 +- 4 files changed, 76 insertions(+), 71 deletions(-) create mode 100644 bruno/local/Chunk/Execute Java Chunk.bru diff --git a/bruno/local/Chunk/Execute Java Chunk.bru b/bruno/local/Chunk/Execute Java Chunk.bru new file mode 100644 index 0000000..ae92fd4 --- /dev/null +++ b/bruno/local/Chunk/Execute Java Chunk.bru @@ -0,0 +1,23 @@ +meta { + name: Execute Java Chunk + type: http + seq: 8 +} + +post { + url: http://localhost:3000/chunk/execute/22e04d50-3aea-43ac-9a89-32daea0cc9f8?lang=java + body: json + auth: none +} + +params:query { + lang: java +} + +body:json { + { + "snippets": { + "logic": "return x * y" + } + } +} diff --git a/src/scripts/data/java/lockerroom/chunks.json b/src/scripts/data/java/lockerroom/chunks.json index d3633a8..79c872b 100644 --- a/src/scripts/data/java/lockerroom/chunks.json +++ b/src/scripts/data/java/lockerroom/chunks.json @@ -3,19 +3,15 @@ "title": "LCK-CHUNK-001: Internal Subnet Check", "difficulty": "Medium", "category": "Java Basics", - "templates": [ - { - "lang": "java", + "templates": { + "java": { "name": "Java Implementation", - "code": "import java.util.*;\n\npublic class Solution {\n public static void main(String[] args) {\n Scanner scanner = new Scanner(System.in);\n String ipAddress = scanner.nextLine();\n \n /* The faculty's strict firewall is blocking all of your external traffic. \n * To run your escape script, you need to spoof the routing so it looks like \n * it's coming from the internal student network. The internal subnet ALWAYS \n * begins with \"192.168.\".\n */\n \n // Return true if the IP address starts with the internal subnet\n {{{player_code}}}\n \n System.out.println(isInternal);\n }\n}", - "snippets": [ - [ - "player_code", - "boolean isInternal = ipAddress.startsWith(\"192.168.\");" - ] - ] + "template_code": "import java.util.*;\n\npublic class Solution {\n public static void main(String[] args) {\n Scanner scanner = new Scanner(System.in);\n String ipAddress = scanner.nextLine();\n \n /* The faculty's strict firewall is blocking all of your external traffic. \n * To run your escape script, you need to spoof the routing so it looks like \n * it's coming from the internal student network. The internal subnet ALWAYS \n * begins with \"192.168.\".\n */\n \n // Return true if the IP address starts with the internal subnet\n {{{player_code}}}\n \n System.out.println(isInternal);\n }\n}", + "snippets": { + "player_code": "no clue provided here" + } } - ], + }, "expectation": { "input": "192.168.1.1", "output": "true" @@ -25,63 +21,33 @@ "title": "LCK-CHUNK-002: Backdoor Account Detection", "difficulty": "Medium", "category": "Java Basics", - "templates": [ - { - "lang": "java", + "templates": { + "java": { "name": "Java Implementation", - "code": "import java.util.*;\n\npublic class Solution {\n public static void main(String[] args) {\n Scanner scanner = new Scanner(System.in);\n String username = scanner.nextLine();\n \n /* The corrupt SysAdmin leaves hidden backdoor accounts on every faculty server. \n * You intercepted the user logs. You know their naming convention always includes \n * the word \"admin\", but they try to hide it by mixing uppercase and lowercase \n * letters (like \"SysAdMin42\" or \"rootADMIN\").\n */\n \n // Return true if the username contains \"admin\" (ignoring case!)\n {{{find_backdoor}}}\n \n System.out.println(isBackdoor);\n }\n}", - "snippets": [ - [ - "find_backdoor", - "boolean isBackdoor = username.toLowerCase().contains(\"admin\");" - ] - ] + "template_code": "import java.util.*;\n\npublic class Solution {\n public static void main(String[] args) {\n Scanner scanner = new Scanner(System.in);\n String username = scanner.nextLine();\n \n /* The corrupt SysAdmin leaves hidden backdoor accounts on every faculty server. \n * You intercepted the user logs. You know their naming convention always includes \n * the word \"admin\", but they try to hide it by mixing uppercase and lowercase \n * letters (like \"SysAdMin42\" or \"rootADMIN\").\n */\n \n // Return true if the username contains \"admin\" (ignoring case!)\n {{{find_backdoor}}}\n \n System.out.println(isBackdoor);\n }\n}", + "snippets": { + "find_backdoor": "no clue provided here" + } } - ], + }, "expectation": { "input": "admin", "output": "true" } }, - { - "title": "LCK-CHUNK-003: URL Protocol Upgrade", - "difficulty": "Medium", - "category": "Java Basics", - "templates": [ - { - "lang": "java", - "name": "Java Implementation", - "code": "import java.util.*;\n\n\n\npublic class Solution {\n\n public static void main(String[] args) {\n\n Scanner scanner = new Scanner(System.in);\n\n String legacyUrl = scanner.nextLine();\n\n \n\n /* * LORE: The faculty's student database still uses an outdated, \n\n * unencrypted API for internal requests. Your data extraction script \n\n * will be immediately blocked by the modern outbound proxy unless \n\n * the URL strictly uses \"https://\" instead of \"http://\".\n\n */\n\n \n\n // Replace \"http://\" with \"https://\" in the provided URL string\n\n {{{upgrade_protocol}}}\n\n \n\n System.out.println(secureUrl);\n\n }\n\n}", - "snippets": [ - [ - "upgrade_protocol", - "String secureUrl = legacyUrl.replace(\"http://\", \"https://\");" - ] - ] - } - ], - "expectation": { - "input": "http://example.com", - "output": "https://example.com" - } - }, { "title": "LCK-CHUNK-004: Storage Capacity Check", "difficulty": "Medium", "category": "Java Basics", - "templates": [ - { - "lang": "java", + "templates": { + "java": { "name": "Java Implementation", - "code": "import java.util.*;\n\n\n\npublic class Solution {\n\n public static void main(String[] args) {\n\n Scanner scanner = new Scanner(System.in);\n\n int driveCapacityMB = scanner.nextInt();\n\n int fileSizeKB = scanner.nextInt();\n\n \n\n /* * LORE: You've accessed the Dean's terminal and are trying to download the \n\n * digital blueprints of the faculty building onto a smuggled thumb drive. \n\n * The system gives you the file size in Kilobytes (KB), but you only know \n\n * your drive's remaining capacity in Megabytes (MB).\n\n */\n\n \n\n // Check if the file will fit on the drive (Remember: 1024 KB in 1 MB)\n\n {{{check_storage}}}\n\n \n\n System.out.println(hasEnoughSpace);\n\n }\n\n}", - "snippets": [ - [ - "check_storage", - "boolean hasEnoughSpace = (fileSizeKB / 1024) <= driveCapacityMB;" - ] - ] + "template_code": "import java.util.*;\n\n\n\npublic class Solution {\n\n public static void main(String[] args) {\n\n Scanner scanner = new Scanner(System.in);\n\n int driveCapacityMB = scanner.nextInt();\n\n int fileSizeKB = scanner.nextInt();\n\n \n\n /* * LORE: You've accessed the Dean's terminal and are trying to download the \n\n * digital blueprints of the faculty building onto a smuggled thumb drive. \n\n * The system gives you the file size in Kilobytes (KB), but you only know \n\n * your drive's remaining capacity in Megabytes (MB).\n\n */\n\n \n\n // Check if the file will fit on the drive (Remember: 1024 KB in 1 MB)\n\n {{{check_storage}}}\n\n \n\n System.out.println(hasEnoughSpace);\n\n }\n\n}", + "snippets": { + "check_storage": "no clue provided here" + } } - ], + }, "expectation": { "input": "1024\n2048", "output": "true" @@ -91,19 +57,15 @@ "title": "LCK-CHUNK-005: Password Validation", "difficulty": "Medium", "category": "Java Basics", - "templates": [ - { - "lang": "java", + "templates": { + "java": { "name": "Java Implementation", - "code": "import java.util.*;\n\n\n\npublic class Solution {\n\n public static void main(String[] args) {\n\n Scanner scanner = new Scanner(System.in);\n\n String username = scanner.nextLine();\n\n String password = scanner.nextLine();\n\n \n\n /* The Teaching Assistant used a notoriously weak password policy \n\n * for the gradebook server. To crack into the system and find the security \n\n * bypass key, you need to write a quick validation script. A valid password \n\n * must be at least 8 characters long and MUST NOT be exactly the same as the username.\n\n */\n\n \n\n // Return true if the password is 8+ characters and doesn't match the username\n\n {{{validate_password}}}\n\n \n\n System.out.println(isValid);\n\n }\n\n}", - "snippets": [ - [ - "validate_password", - "boolean isValid = password.length() >= 8 && !password.equals(username);" - ] - ] + "template_code": "import java.util.*;\n\n\n\npublic class Solution {\n\n public static void main(String[] args) {\n\n Scanner scanner = new Scanner(System.in);\n\n String username = scanner.nextLine();\n\n String password = scanner.nextLine();\n\n \n\n /* The Teaching Assistant used a notoriously weak password policy \n\n * for the gradebook server. To crack into the system and find the security \n\n * bypass key, you need to write a quick validation script. A valid password \n\n * must be at least 8 characters long and MUST NOT be exactly the same as the username.\n\n */\n\n \n\n // Return true if the password is 8+ characters and doesn't match the username\n\n {{{validate_password}}}\n\n \n\n System.out.println(isValid);\n\n }\n\n}", + "snippets": { + "validate_password": "no clue provided here" + } } - ], + }, "expectation": { "input": "password\nusername", "output": "false" diff --git a/src/scripts/data/java/temp/chunks.json b/src/scripts/data/java/temp/chunks.json index 7cac3e9..e32cbe3 100644 --- a/src/scripts/data/java/temp/chunks.json +++ b/src/scripts/data/java/temp/chunks.json @@ -21,6 +21,28 @@ "output": "[2, 4, 6]" } }, + { + "title": "LCK-CHUNK-003: URL Protocol Upgrade -- removed due to blacklist detected", + "difficulty": "Medium", + "category": "Java Basics", + "templates": [ + { + "lang": "java", + "name": "Java Implementation", + "code": "import java.util.*;\n\n\n\npublic class Solution {\n\n public static void main(String[] args) {\n\n Scanner scanner = new Scanner(System.in);\n\n String legacyUrl = scanner.nextLine();\n\n \n\n /* * LORE: The faculty's student database still uses an outdated, \n\n * unencrypted API for internal requests. Your data extraction script \n\n * will be immediately blocked by the modern outbound proxy unless \n\n * the URL strictly uses \"https://\" instead of \"http://\".\n\n */\n\n \n\n // Replace \"http://\" with \"https://\" in the provided URL string\n\n {{{upgrade_protocol}}}\n\n \n\n System.out.println(secureUrl);\n\n }\n\n}", + "snippets": [ + [ + "upgrade_protocol", + "String secureUrl = legacyUrl.replace(\"http://\", \"https://\");" + ] + ] + } + ], + "expectation": { + "input": "http://example.com", + "output": "https://example.com" + } + }, { "title": "Java Lambda Comparator", "difficulty": "Medium", diff --git a/src/scripts/seeders/seed_lockerroom_java.py b/src/scripts/seeders/seed_lockerroom_java.py index de80fda..73999dc 100644 --- a/src/scripts/seeders/seed_lockerroom_java.py +++ b/src/scripts/seeders/seed_lockerroom_java.py @@ -141,20 +141,18 @@ def get_or_create_tag(name): session.delete(t) session.flush() - for t_data in c_data["templates"]: - lang = t_data["lang"] + for lang, t_data in c_data["templates"].items(): template = ChunkTemplate( chunk_id=chunk.id, language=lang, name=t_data["name"], - template_code=t_data["code"], + template_code=t_data["template_code"], description=t_data.get("description", f"Standard {lang} boilerplate") ) session.add(template) session.flush() - for snippet in t_data.get("snippets", []): - key, content = snippet + for key, content in t_data.get("snippets", {}).items(): s = Snippet(template_id=template.id, placeholder_key=key, code_content=content) session.add(s) From a450c844fa5a4b9cab431a57b3f06785b77174c9 Mon Sep 17 00:00:00 2001 From: Pathompum Jirakarnpaisan <107536914+Saannddy@users.noreply.github.com> Date: Sat, 4 Apr 2026 01:15:06 +0700 Subject: [PATCH 3/6] feat: add category support to chunk retrieval and implement Elevator Hall data processing and seeding scripts --- src/handlers/chunk_handler.py | 3 +- src/repositories/chunk_repository.py | 27 +- .../data/java/elevatorhall/chunks.json | 162 +++++++ .../data/java/elevatorhall/problems.json | 403 ++++++++++++++++++ src/scripts/process_elevatorhall.py | 114 +++++ src/scripts/seed.py | 16 + src/scripts/seeders/__init__.py | 4 + src/scripts/seeders/seed_elevatorhall_java.py | 159 +++++++ src/services/chunk_service.py | 4 +- 9 files changed, 880 insertions(+), 12 deletions(-) create mode 100644 src/scripts/data/java/elevatorhall/chunks.json create mode 100644 src/scripts/data/java/elevatorhall/problems.json create mode 100644 src/scripts/process_elevatorhall.py create mode 100644 src/scripts/seeders/seed_elevatorhall_java.py diff --git a/src/handlers/chunk_handler.py b/src/handlers/chunk_handler.py index 17caec1..f064701 100644 --- a/src/handlers/chunk_handler.py +++ b/src/handlers/chunk_handler.py @@ -23,9 +23,10 @@ def get_chunk(self, chunk_id): def get_random_chunks(self): limit = request.args.get('limit', default=1, type=int) lang = request.args.get('lang') + category = request.args.get('category') tags = request.args.get('tags') if tags: tags = [tag.strip() for tag in tags.split(',')] - chunks = self.service.get_random_chunks(limit=limit, lang=lang, tags=tags) + chunks = self.service.get_random_chunks(limit=limit, lang=lang, tags=tags, category=category) return jsonify(status="success", data=chunks), 200 diff --git a/src/repositories/chunk_repository.py b/src/repositories/chunk_repository.py index a5c7162..dfdd09f 100644 --- a/src/repositories/chunk_repository.py +++ b/src/repositories/chunk_repository.py @@ -78,23 +78,22 @@ def get_details(self, chunk_id, lang=None): return self._serialize_chunk(chunk, lang) - def find_random(self, limit=1, lang=None, tags=None): - """Fetch random N chunks with their implementation details. Filters by language and tags if provided.""" + def find_random(self, limit=1, lang=None, tags=None, category=None): + """Fetch random N chunks with their implementation details. Filters by language, tags, and category if provided.""" with self._get_session() as session: statement = select(Chunk).options( joinedload(Chunk.templates).joinedload(ChunkTemplate.snippets), - joinedload(Chunk.tags) + joinedload(Chunk.tags), + joinedload(Chunk.categories) ).order_by(func.random()) # If language is specified, filter chunks that HAVE at least one template in that language if lang: statement = statement.join(Chunk.templates).where(ChunkTemplate.language == lang) - # If tags are specified, we need chunks that have ALL specified tags - if tags: - from models import Tag - # For simplicity, fetch more and filter in Python - fetch_limit = limit * 10 # Fetch more to account for filtering + # If tags or category are specified, we might need more to filter in Python + if tags or category: + fetch_limit = limit * 20 # Fetch more to account for filtering statement = statement.limit(fetch_limit) else: statement = statement.limit(limit * 2) # Some buffer @@ -105,12 +104,22 @@ def find_random(self, limit=1, lang=None, tags=None): chunks = [] for chunk in results: - if lang and lang not in chunk.config.get("templates", {}): + # Basic language check (redundant but safe) + if lang and lang not in [t.language for t in chunk.templates]: continue + + # Tag check if tags: chunk_tag_names = [t.name for t in chunk.tags] if not all(tag in chunk_tag_names for tag in tags): continue + + # Category check + if category: + chunk_category_names = [c.name for c in chunk.categories] + if category not in chunk_category_names: + continue + chunks.append(self._serialize_chunk(chunk, lang)) if len(chunks) >= limit: break diff --git a/src/scripts/data/java/elevatorhall/chunks.json b/src/scripts/data/java/elevatorhall/chunks.json new file mode 100644 index 0000000..257e8f7 --- /dev/null +++ b/src/scripts/data/java/elevatorhall/chunks.json @@ -0,0 +1,162 @@ +[ + { + "title": "ELV-P4-CHUNK-001", + "difficulty": "Medium", + "category": "ELV-P4", + "templates": { + "java": { + "name": "Java Implementation", + "template_code": "// [NULL] stripped the exception handling from the ID scanner.\n// It now crashes on any non-integer input and floods the audit log with errors.\n// Restore the three blocks. Every scan must be logged, pass or fail.\n\npublic class CheckpointScanner {\n\n public static String parseStudentID(String input) {\n try {\n // TASK 1: Parse input. Return \"VALID:\" + id if 10000\u201399999, else \"INVALID:OUT_OF_RANGE\".\n {{{snippet_1}}}\n } catch (NumberFormatException e) {\n // TASK 2: Return \"INVALID:NOT_A_NUMBER\".\n {{{snippet_2}}}\n } finally {\n // TASK 3: Always print \"scan attempt logged\".\n {{{snippet_3}}}\n }\n }\n}", + "snippets": { + "snippet_1": "int id = Integer.parseInt(input);\nif (id >= 10000 && id <= 99999) {\n return \"VALID:\" + id;\n} else {\n return \"INVALID:OUT_OF_RANGE\";\n}", + "snippet_2": "return \"INVALID:NOT_A_NUMBER\";", + "snippet_3": "System.out.println(\"scan attempt logged\");" + } + } + }, + "expectation": { + "input": "", + "output": "" + } + }, + { + "title": "ELV-P4-CHUNK-002", + "difficulty": "Medium", + "category": "ELV-P4", + "templates": { + "java": { + "name": "Java Implementation", + "template_code": "// The room code scanner is throwing unhandled exceptions on every bad input.\n// [NULL] knew exactly which lines to delete to break the audit trail.\n// Restore all three exception blocks.\n\npublic class CheckpointScanner {\n\n public static String parseRoomCode(String input) {\n try {\n // TASK 1: Parse input. Return \"ROOM:\" + code if 100\u2013999, else \"INVALID:NOT_A_ROOM\".\n {{{snippet_1}}}\n } catch (NumberFormatException e) {\n // TASK 2: Return \"INVALID:FORMAT_ERROR\".\n {{{snippet_2}}}\n } finally {\n // TASK 3: Always print \"door scan logged\".\n {{{snippet_3}}}\n }\n }\n}", + "snippets": { + "snippet_1": "int code = Integer.parseInt(input);\nif (code >= 100 && code <= 999) {\n return \"ROOM:\" + code;\n} else {\n return \"INVALID:NOT_A_ROOM\";\n}", + "snippet_2": "return \"INVALID:FORMAT_ERROR\";", + "snippet_3": "System.out.println(\"door scan logged\");" + } + } + }, + "expectation": { + "input": "", + "output": "" + } + }, + { + "title": "ELV-P4-CHUNK-003", + "difficulty": "Medium", + "category": "ELV-P4", + "templates": { + "java": { + "name": "Java Implementation", + "template_code": "// The port scanner crashes on anything that is not a clean integer.\n// Without proper exception handling the network audit trail is blind.\n// Restore it.\n\npublic class CheckpointScanner {\n\n public static String parsePort(String input) {\n try {\n // TASK 1: Parse input. Return \"PORT:\" + number if 1\u201365535, else \"INVALID:PORT_OUT_OF_RANGE\".\n {{{snippet_1}}}\n } catch (NumberFormatException e) {\n // TASK 2: Return \"INVALID:NOT_A_PORT\".\n {{{snippet_2}}}\n } finally {\n // TASK 3: Always print \"connection attempt logged\".\n {{{snippet_3}}}\n }\n }\n}", + "snippets": { + "snippet_1": "int port = Integer.parseInt(input);\nif (port >= 1 && port <= 65535) {\n return \"PORT:\" + port;\n} else {\n return \"INVALID:PORT_OUT_OF_RANGE\";\n}", + "snippet_2": "return \"INVALID:NOT_A_PORT\";", + "snippet_3": "System.out.println(\"connection attempt logged\");" + } + } + }, + "expectation": { + "input": "", + "output": "" + } + }, + { + "title": "ELV-P4-CHUNK-004", + "difficulty": "Medium", + "category": "ELV-P4", + "templates": { + "java": { + "name": "Java Implementation", + "template_code": "// The elevator rejects every floor request because the parser throws on bad input.\n// [NULL] removed the safety net. Restore the exception blocks.\n// The finally block is not optional \u2014 the lift log must always write.\n\npublic class CheckpointScanner {\n\n public static String parseFloor(String input) {\n try {\n // TASK 1: Parse input. Return \"FLOOR:\" + number if 1\u201310, else \"INVALID:NO_SUCH_FLOOR\".\n {{{snippet_1}}}\n } catch (NumberFormatException e) {\n // TASK 2: Return \"INVALID:NOT_A_NUMBER\".\n {{{snippet_2}}}\n } finally {\n // TASK 3: Always print \"elevator request logged\".\n {{{snippet_3}}}\n }\n }\n}", + "snippets": { + "snippet_1": "int floor = Integer.parseInt(input);\nif (floor >= 1 && floor <= 10) {\n return \"FLOOR:\" + floor;\n} else {\n return \"INVALID:NO_SUCH_FLOOR\";\n}", + "snippet_2": "return \"INVALID:NOT_A_NUMBER\";", + "snippet_3": "System.out.println(\"elevator request logged\");" + } + } + }, + "expectation": { + "input": "", + "output": "" + } + }, + { + "title": "ELV-P5-CHUNK-001", + "difficulty": "Medium", + "category": "ELV-P5", + "templates": { + "java": { + "name": "Java Implementation", + "template_code": "// 4,847 log entries. The threat filter is gone \u2014 [NULL] deleted it first.\n// Without it the emergency system cannot assess severity.\n// Find the threats. The building needs this report before it can act.\n\nimport java.util.ArrayList;\n\npublic class ThreatAnalyser {\n\n public static String analyzeLogs(ArrayList logs) {\n\n // TASK 1: Declare a counter and an ArrayList for threat descriptions.\n {{{snippet_1}}}\n\n for (String entry : logs) {\n // TASK 2: If entry starts with \"THREAT:\", increment and collect the description (after 8 chars).\n {{{snippet_2}}}\n }\n\n // TASK 3: Return \"THREATS:0|none\" if clean, else \"THREATS:\" + count + \"|\" + descriptions joined by \",\".\n {{{snippet_3}}}\n }\n\n public static void main(String[] args) {\n ArrayList logs1 = new ArrayList<>();\n logs1.add(\"INFO: door opened\");\n logs1.add(\"THREAT: brute force\");\n logs1.add(\"INFO: scan ok\");\n logs1.add(\"THREAT: port scan\");\n logs1.add(\"THREAT: login fail\");\n System.out.println(analyzeLogs(logs1));\n\n ArrayList logs2 = new ArrayList<>();\n logs2.add(\"INFO: all clear\");\n System.out.println(analyzeLogs(logs2));\n }\n}", + "snippets": { + "snippet_1": "int count = 0;\nArrayList threats = new ArrayList<>();", + "snippet_2": "if (entry.startsWith(\"THREAT:\")) {\n count++;\n threats.add(entry.substring(8));\n}", + "snippet_3": "if (count == 0) return \"THREATS:0|none\";\nreturn \"THREATS:\" + count + \"|\" + String.join(\",\", threats);" + } + } + }, + "expectation": { + "input": "", + "output": "" + } + }, + { + "title": "ELV-P5-CHUNK-002", + "difficulty": "Medium", + "category": "ELV-P5", + "templates": { + "java": { + "name": "Java Implementation", + "template_code": "// The server error filter was wiped along with the intrusion logs.\n// Critical errors are invisible to the monitoring system.\n// Restore the filter \u2014 find every ERROR entry and report the count.\n\nimport java.util.ArrayList;\n\npublic class ThreatAnalyser {\n\n public static String filterErrors(ArrayList logs) {\n\n // TASK 1: Declare a counter and an ArrayList for error messages.\n {{{snippet_1}}}\n\n for (String entry : logs) {\n // TASK 2: If entry starts with \"ERROR:\", increment and collect the message (after 7 chars).\n {{{snippet_2}}}\n }\n\n // TASK 3: Return \"ERRORS:0|none\" if clean, else \"ERRORS:\" + count + \"|\" + messages joined by \",\".\n {{{snippet_3}}}\n }\n\n public static void main(String[] args) {\n ArrayList logs1 = new ArrayList<>();\n logs1.add(\"INFO: server started\");\n logs1.add(\"ERROR: disk full\");\n logs1.add(\"ERROR: null pointer\");\n logs1.add(\"INFO: backup ok\");\n System.out.println(filterErrors(logs1));\n\n ArrayList logs2 = new ArrayList<>();\n logs2.add(\"INFO: running\");\n System.out.println(filterErrors(logs2));\n }\n}", + "snippets": { + "snippet_1": "int count = 0;\nArrayList errors = new ArrayList<>();", + "snippet_2": "if (entry.startsWith(\"ERROR:\")) {\n count++;\n errors.add(entry.substring(7));\n}", + "snippet_3": "if (count == 0) return \"ERRORS:0|none\";\nreturn \"ERRORS:\" + count + \"|\" + String.join(\",\", errors);" + } + } + }, + "expectation": { + "input": "", + "output": "" + } + }, + { + "title": "ELV-P5-CHUNK-003", + "difficulty": "Medium", + "category": "ELV-P5", + "templates": { + "java": { + "name": "Java Implementation", + "template_code": "// The badge access log is full of denied entries \u2014 someone was probing every door.\n// The scanner that should have flagged them is offline.\n// Find every DENIED entry before [NULL] makes another move.\n\nimport java.util.ArrayList;\n\npublic class ThreatAnalyser {\n\n public static String findDenied(ArrayList entries) {\n\n // TASK 1: Declare a counter and an ArrayList for denied entries.\n {{{snippet_1}}}\n\n for (String entry : entries) {\n // TASK 2: If entry contains \"DENIED\" anywhere, increment and collect the full entry.\n {{{snippet_2}}}\n }\n\n // TASK 3: Return \"DENIED:0|none\" if none, else \"DENIED:\" + count + \"|\" + entries joined by \",\".\n {{{snippet_3}}}\n }\n\n public static void main(String[] args) {\n ArrayList e1 = new ArrayList<>();\n e1.add(\"Student 001: GRANTED\");\n e1.add(\"Student 002: DENIED low clearance\");\n e1.add(\"Student 003: GRANTED\");\n e1.add(\"Visitor 01: DENIED no badge\");\n System.out.println(findDenied(e1));\n\n ArrayList e2 = new ArrayList<>();\n e2.add(\"Staff 001: GRANTED\");\n System.out.println(findDenied(e2));\n }\n}", + "snippets": { + "snippet_1": "int count = 0;\nArrayList denied = new ArrayList<>();", + "snippet_2": "if (entry.contains(\"DENIED\")) {\n count++;\n denied.add(entry);\n}", + "snippet_3": "if (count == 0) return \"DENIED:0|none\";\nreturn \"DENIED:\" + count + \"|\" + String.join(\",\", denied);" + } + } + }, + "expectation": { + "input": "", + "output": "" + } + }, + { + "title": "ELV-P5-CHUNK-004", + "difficulty": "Medium", + "category": "ELV-P5", + "templates": { + "java": { + "name": "Java Implementation", + "template_code": "// Elevator requests are piling up but the floor filter is down.\n// Security needs to know exactly how many calls are going to each floor.\n// Restore the filter \u2014 match by floor number, report the count.\n\nimport java.util.ArrayList;\n\npublic class ThreatAnalyser {\n\n public static String findFloorRequests(ArrayList logs, int floor) {\n\n // TASK 1: Declare a counter and an ArrayList for matching requests.\n {{{snippet_1}}}\n\n for (String entry : logs) {\n // TASK 2: If entry ends with \":\" + floor, increment and collect the full entry.\n {{{snippet_2}}}\n }\n\n // TASK 3: Return \"FLOOR\" + floor + \":0|none\" if none,\n // else \"FLOOR\" + floor + \":\" + count + \"|\" + entries joined by \",\".\n {{{snippet_3}}}\n }\n\n public static void main(String[] args) {\n ArrayList logs = new ArrayList<>();\n logs.add(\"User A requested floor:2\");\n logs.add(\"User B requested floor:3\");\n logs.add(\"User C requested floor:2\");\n logs.add(\"User D requested floor:1\");\n System.out.println(findFloorRequests(logs, 2));\n System.out.println(findFloorRequests(logs, 5));\n }\n}", + "snippets": { + "snippet_1": "int count = 0;\nArrayList matches = new ArrayList<>();", + "snippet_2": "if (entry.endsWith(\":\" + floor)) {\n count++;\n matches.add(entry);\n}", + "snippet_3": "if (count == 0) return \"FLOOR\" + floor + \":0|none\";\nreturn \"FLOOR\" + floor + \":\" + count + \"|\" + String.join(\",\", matches);" + } + } + }, + "expectation": { + "input": "", + "output": "" + } + } +] \ No newline at end of file diff --git a/src/scripts/data/java/elevatorhall/problems.json b/src/scripts/data/java/elevatorhall/problems.json new file mode 100644 index 0000000..94be9ac --- /dev/null +++ b/src/scripts/data/java/elevatorhall/problems.json @@ -0,0 +1,403 @@ +[ + { + "title": "ELV-P1-PROB-001", + "description": "// [NULL] destroyed the auth daemon's recursive checksum.\n// Without a base case, every badge scan crashes the stack.\n// Restore it. The first fragment unlocks when it runs clean.\n\npublic class AuthDaemon {\n\n public static int hashPassword(String s) {\n // Recursively sum the ASCII value of each character.\n {PLAYER CODE}\n }\n\n public static void main(String[] args) {\n System.out.println(hashPassword(\"DOOR\"));\n System.out.println(hashPassword(\"KEY\"));\n System.out.println(hashPassword(\"\"));\n }\n}", + "difficulty": "Hard", + "category": "ELV-P1", + "templates": { + "java": "// [NULL] destroyed the auth daemon's recursive checksum.\n// Without a base case, every badge scan crashes the stack.\n// Restore it. The first fragment unlocks when it runs clean.\n\npublic class AuthDaemon {\n\n public static int hashPassword(String s) {\n // Recursively sum the ASCII value of each character.\n {PLAYER CODE}\n }\n\n public static void main(String[] args) {\n System.out.println(hashPassword(\"DOOR\"));\n System.out.println(hashPassword(\"KEY\"));\n System.out.println(hashPassword(\"\"));\n }\n}" + }, + "test_cases": [ + { + "input": "\"DOOR\"", + "output": "289", + "is_hidden": false + }, + { + "input": "\"KEY\"", + "output": "236", + "is_hidden": true + }, + { + "input": "\"\"", + "output": "0", + "is_hidden": true + } + ] + }, + { + "title": "ELV-P1-PROB-002", + "description": "// The badge scanner counts security characters in access codes recursively.\n// [NULL] gutted the logic. Restore it before the auth layer rejects every card.\n\npublic class AuthDaemon {\n\n public static int countChar(String s, char target) {\n // Recursively count how many times target appears in s.\n {PLAYER CODE}\n }\n\n public static void main(String[] args) {\n System.out.println(countChar(\"ESCALATE\", 'E'));\n System.out.println(countChar(\"ACCESS\", 'S'));\n System.out.println(countChar(\"DOOR\", 'Z'));\n }\n}", + "difficulty": "Hard", + "category": "ELV-P1", + "templates": { + "java": "// The badge scanner counts security characters in access codes recursively.\n// [NULL] gutted the logic. Restore it before the auth layer rejects every card.\n\npublic class AuthDaemon {\n\n public static int countChar(String s, char target) {\n // Recursively count how many times target appears in s.\n {PLAYER CODE}\n }\n\n public static void main(String[] args) {\n System.out.println(countChar(\"ESCALATE\", 'E'));\n System.out.println(countChar(\"ACCESS\", 'S'));\n System.out.println(countChar(\"DOOR\", 'Z'));\n }\n}" + }, + "test_cases": [ + { + "input": "\"ESCALATE\", 'E'", + "output": "2", + "is_hidden": false + }, + { + "input": "\"ACCESS\", 'S'", + "output": "2", + "is_hidden": true + }, + { + "input": "\"DOOR\", 'Z'", + "output": "0", + "is_hidden": true + } + ] + }, + { + "title": "ELV-P1-PROB-003", + "description": "// [NULL] reversed every exit label in the CCTV registry to cover their tracks.\n// This recursive function reverses them back. It is broken. Fix it.\n\npublic class AuthDaemon {\n\n public static String reverseCode(String s) {\n // Recursively reverse the string.\n {PLAYER CODE}\n }\n\n public static void main(String[] args) {\n System.out.println(reverseCode(\"TIXE\"));\n System.out.println(reverseCode(\"EDOC\"));\n System.out.println(reverseCode(\"\"));\n }\n}", + "difficulty": "Hard", + "category": "ELV-P1", + "templates": { + "java": "// [NULL] reversed every exit label in the CCTV registry to cover their tracks.\n// This recursive function reverses them back. It is broken. Fix it.\n\npublic class AuthDaemon {\n\n public static String reverseCode(String s) {\n // Recursively reverse the string.\n {PLAYER CODE}\n }\n\n public static void main(String[] args) {\n System.out.println(reverseCode(\"TIXE\"));\n System.out.println(reverseCode(\"EDOC\"));\n System.out.println(reverseCode(\"\"));\n }\n}" + }, + "test_cases": [ + { + "input": "\"TIXE\"", + "output": "EXIT", + "is_hidden": false + }, + { + "input": "\"EDOC\"", + "output": "CODE", + "is_hidden": true + }, + { + "input": "\"\"", + "output": "", + "is_hidden": true + } + ] + }, + { + "title": "ELV-P1-PROB-004", + "description": "// Floor access codes are validated by a recursive digit checksum.\n// The module is down. Restore it before the elevator rejects every request.\n\npublic class AuthDaemon {\n\n public static int sumDigits(int n) {\n // Recursively sum each digit of n.\n {PLAYER CODE}\n }\n\n public static void main(String[] args) {\n System.out.println(sumDigits(4821));\n System.out.println(sumDigits(9));\n System.out.println(sumDigits(0));\n }\n}", + "difficulty": "Hard", + "category": "ELV-P1", + "templates": { + "java": "// Floor access codes are validated by a recursive digit checksum.\n// The module is down. Restore it before the elevator rejects every request.\n\npublic class AuthDaemon {\n\n public static int sumDigits(int n) {\n // Recursively sum each digit of n.\n {PLAYER CODE}\n }\n\n public static void main(String[] args) {\n System.out.println(sumDigits(4821));\n System.out.println(sumDigits(9));\n System.out.println(sumDigits(0));\n }\n}" + }, + "test_cases": [ + { + "input": "4821", + "output": "15", + "is_hidden": false + }, + { + "input": "9", + "output": "9", + "is_hidden": true + }, + { + "input": "0", + "output": "0", + "is_hidden": true + } + ] + }, + { + "title": "ELV-P2-PROB-001", + "description": "// The corridor heat sensor grid feeds into this machine.\n// [NULL] broke the scan function so it never flags anomalies.\n// Restore it, the security relay needs a clean threat report.\n\nimport java.util.ArrayList;\n\npublic class GridScanner {\n\n public static String findHotCells(int[][] grid) {\n ArrayList hits = new ArrayList<>();\n // Scan every cell. Flag readings above 80 as \"[row,col]=value\".\n // Return hits joined by \", \" or \"none\" if the grid is clean.\n {PLAYER CODE}\n }\n\n public static void main(String[] args) {\n int[][] grid = {\n {12, 45, 88, 23},\n {91, 34, 56, 77},\n {10, 82, 19, 95},\n {60, 55, 33, 84}\n };\n System.out.println(findHotCells(grid));\n\n int[][] grid2 = {{10, 20}, {30, 40}};\n System.out.println(findHotCells(grid2));\n }\n}", + "difficulty": "Hard", + "category": "ELV-P2", + "templates": { + "java": "// The corridor heat sensor grid feeds into this machine.\n// [NULL] broke the scan function so it never flags anomalies.\n// Restore it, the security relay needs a clean threat report.\n\nimport java.util.ArrayList;\n\npublic class GridScanner {\n\n public static String findHotCells(int[][] grid) {\n ArrayList hits = new ArrayList<>();\n // Scan every cell. Flag readings above 80 as \"[row,col]=value\".\n // Return hits joined by \", \" or \"none\" if the grid is clean.\n {PLAYER CODE}\n }\n\n public static void main(String[] args) {\n int[][] grid = {\n {12, 45, 88, 23},\n {91, 34, 56, 77},\n {10, 82, 19, 95},\n {60, 55, 33, 84}\n };\n System.out.println(findHotCells(grid));\n\n int[][] grid2 = {{10, 20}, {30, 40}};\n System.out.println(findHotCells(grid2));\n }\n}" + }, + "test_cases": [ + { + "input": "", + "output": "[0,2]=88, [1,0]=91, [2,1]=82, [2,3]=95, [3,3]=84", + "is_hidden": false + }, + { + "input": "", + "output": "none", + "is_hidden": true + } + ] + }, + { + "title": "ELV-P2-PROB-002", + "description": "// [NULL] is hiding in wireless dead zones to avoid detection.\n// The signal map is a grid, find every cell below strength 10.\n// Expose the dead zones and the relay comes back online.\n\nimport java.util.ArrayList;\n\npublic class GridScanner {\n\n public static String findDeadZones(int[][] signal) {\n ArrayList hits = new ArrayList<>();\n // Flag every cell where signal strength is below 10 as \"[row,col]=value\".\n // Return hits joined by \", \" or \"none\" if coverage is full.\n {PLAYER CODE}\n }\n\n public static void main(String[] args) {\n int[][] signal = {\n {55, 3, 80, 7},\n {90, 42, 8, 60},\n { 5, 70, 33, 2}\n };\n System.out.println(findDeadZones(signal));\n\n int[][] signal2 = {{50, 60}, {70, 80}};\n System.out.println(findDeadZones(signal2));\n }\n}", + "difficulty": "Hard", + "category": "ELV-P2", + "templates": { + "java": "// [NULL] is hiding in wireless dead zones to avoid detection.\n// The signal map is a grid, find every cell below strength 10.\n// Expose the dead zones and the relay comes back online.\n\nimport java.util.ArrayList;\n\npublic class GridScanner {\n\n public static String findDeadZones(int[][] signal) {\n ArrayList hits = new ArrayList<>();\n // Flag every cell where signal strength is below 10 as \"[row,col]=value\".\n // Return hits joined by \", \" or \"none\" if coverage is full.\n {PLAYER CODE}\n }\n\n public static void main(String[] args) {\n int[][] signal = {\n {55, 3, 80, 7},\n {90, 42, 8, 60},\n { 5, 70, 33, 2}\n };\n System.out.println(findDeadZones(signal));\n\n int[][] signal2 = {{50, 60}, {70, 80}};\n System.out.println(findDeadZones(signal2));\n }\n}" + }, + "test_cases": [ + { + "input": "", + "output": "[0,1]=3, [0,3]=7, [1,2]=8, [2,0]=5, [2,3]=2", + "is_hidden": false + }, + { + "input": "", + "output": "none", + "is_hidden": true + } + ] + }, + { + "title": "ELV-P2-PROB-003", + "description": "// Security needs a headcount to confirm the building is clear.\n// The attendance grid uses 1 for present, 0 for absent.\n// Count the occupied cells and report the total.\n\npublic class GridScanner {\n\n public static int countPresent(int[][] attendance) {\n // Count every cell equal to 1 and return the total.\n {PLAYER CODE}\n }\n\n public static void main(String[] args) {\n int[][] a = {\n {1, 0, 1, 1},\n {0, 0, 1, 0},\n {1, 1, 0, 1}\n };\n System.out.println(countPresent(a));\n\n int[][] b = {{0, 0}, {0, 0}};\n System.out.println(countPresent(b));\n }\n}", + "difficulty": "Hard", + "category": "ELV-P2", + "templates": { + "java": "// Security needs a headcount to confirm the building is clear.\n// The attendance grid uses 1 for present, 0 for absent.\n// Count the occupied cells and report the total.\n\npublic class GridScanner {\n\n public static int countPresent(int[][] attendance) {\n // Count every cell equal to 1 and return the total.\n {PLAYER CODE}\n }\n\n public static void main(String[] args) {\n int[][] a = {\n {1, 0, 1, 1},\n {0, 0, 1, 0},\n {1, 1, 0, 1}\n };\n System.out.println(countPresent(a));\n\n int[][] b = {{0, 0}, {0, 0}};\n System.out.println(countPresent(b));\n }\n}" + }, + "test_cases": [ + { + "input": "", + "output": "6", + "is_hidden": false + }, + { + "input": "", + "output": "0", + "is_hidden": true + } + ] + }, + { + "title": "ELV-P2-PROB-004", + "description": "// One server rack is running [NULL]'s process and overheating the room.\n// Find the single hottest cell in the thermal grid.\n// Return its location and temperature, then we know where to cut power.\n\npublic class GridScanner {\n\n public static String findHotspot(int[][] temps) {\n // Find the cell with the maximum value. Return \"[row,col]=value\".\n {PLAYER CODE}\n }\n\n public static void main(String[] args) {\n int[][] t = {\n {40, 72, 55},\n {88, 61, 47},\n {33, 95, 70}\n };\n System.out.println(findHotspot(t));\n\n int[][] t2 = {{10, 20}, {30, 25}};\n System.out.println(findHotspot(t2));\n }\n}", + "difficulty": "Hard", + "category": "ELV-P2", + "templates": { + "java": "// One server rack is running [NULL]'s process and overheating the room.\n// Find the single hottest cell in the thermal grid.\n// Return its location and temperature, then we know where to cut power.\n\npublic class GridScanner {\n\n public static String findHotspot(int[][] temps) {\n // Find the cell with the maximum value. Return \"[row,col]=value\".\n {PLAYER CODE}\n }\n\n public static void main(String[] args) {\n int[][] t = {\n {40, 72, 55},\n {88, 61, 47},\n {33, 95, 70}\n };\n System.out.println(findHotspot(t));\n\n int[][] t2 = {{10, 20}, {30, 25}};\n System.out.println(findHotspot(t2));\n }\n}" + }, + "test_cases": [ + { + "input": "", + "output": "[2,1]=95", + "is_hidden": false + }, + { + "input": "", + "output": "[1,0]=30", + "is_hidden": true + } + ] + }, + { + "title": "ELV-P3-PROB-001", + "description": "// [NULL] wiped both card subclasses from the clearance system.\n// Every card now returns UNKNOWN and every door stays locked.\n// The base class survived. Restore both card types from scratch.\n\npublic class ClearanceManager {\n\n static class AccessCard {\n protected String ownerName;\n protected int accessLevel;\n public AccessCard(String name, int level) {\n this.ownerName = name;\n this.accessLevel = level;\n }\n public String identify() {\n return \"CARD[\" + ownerName + \"] Level:\" + accessLevel;\n }\n }\n\n // TASK 1: StudentCard extends AccessCard. Level always 1. Appends \" [STUDENT]\".\n {TASK 1: STUDENT CARD}\n\n // TASK 2: StaffCard extends AccessCard. Level always 5. Appends \" [STAFF]\".\n {TASK 2: STAFF CARD}\n\n public static void main(String[] args) {\n AccessCard s = new StudentCard(\"Azri\");\n AccessCard t = new StaffCard(\"Dr.Lim\");\n System.out.println(s.identify());\n System.out.println(t.identify());\n System.out.println(s.accessLevel);\n System.out.println(t.accessLevel);\n }\n}", + "difficulty": "Hard", + "category": "ELV-P3", + "templates": { + "java": "// [NULL] wiped both card subclasses from the clearance system.\n// Every card now returns UNKNOWN and every door stays locked.\n// The base class survived. Restore both card types from scratch.\n\npublic class ClearanceManager {\n\n static class AccessCard {\n protected String ownerName;\n protected int accessLevel;\n public AccessCard(String name, int level) {\n this.ownerName = name;\n this.accessLevel = level;\n }\n public String identify() {\n return \"CARD[\" + ownerName + \"] Level:\" + accessLevel;\n }\n }\n\n // TASK 1: StudentCard extends AccessCard. Level always 1. Appends \" [STUDENT]\".\n {TASK 1: STUDENT CARD}\n\n // TASK 2: StaffCard extends AccessCard. Level always 5. Appends \" [STAFF]\".\n {TASK 2: STAFF CARD}\n\n public static void main(String[] args) {\n AccessCard s = new StudentCard(\"Azri\");\n AccessCard t = new StaffCard(\"Dr.Lim\");\n System.out.println(s.identify());\n System.out.println(t.identify());\n System.out.println(s.accessLevel);\n System.out.println(t.accessLevel);\n }\n}" + }, + "test_cases": [ + { + "input": "", + "output": "CARD[Azri] Level:1 [STUDENT]", + "is_hidden": false + }, + { + "input": "", + "output": "CARD[Dr.Lim] Level:5 [STAFF]", + "is_hidden": true + }, + { + "input": "", + "output": "1", + "is_hidden": true + }, + { + "input": "", + "output": "5", + "is_hidden": true + } + ] + }, + { + "title": "ELV-P3-PROB-002", + "description": "// The alert system cannot classify severity anymore \u2014 [NULL] deleted the subclasses.\n// Minor and critical alerts both come back blank. Restore both types.\n\npublic class ClearanceManager {\n\n static class SystemAlert {\n protected String message;\n protected int severity;\n public SystemAlert(String message, int severity) {\n this.message = message;\n this.severity = severity;\n }\n public String describe() {\n return \"ALERT[\" + message + \"] Sev:\" + severity;\n }\n }\n\n // TASK 1: MinorAlert extends SystemAlert. Severity always 1. Appends \" [MINOR]\".\n {TASK 1: MINOR ALERT}\n\n // TASK 2: CriticalAlert extends SystemAlert. Severity always 9. Appends \" [CRITICAL]\".\n {TASK 2: CRITICAL ALERT}\n\n public static void main(String[] args) {\n SystemAlert a = new MinorAlert(\"door left open\");\n SystemAlert b = new CriticalAlert(\"server breach\");\n System.out.println(a.describe());\n System.out.println(b.describe());\n System.out.println(a.severity);\n System.out.println(b.severity);\n }\n}", + "difficulty": "Hard", + "category": "ELV-P3", + "templates": { + "java": "// The alert system cannot classify severity anymore \u2014 [NULL] deleted the subclasses.\n// Minor and critical alerts both come back blank. Restore both types.\n\npublic class ClearanceManager {\n\n static class SystemAlert {\n protected String message;\n protected int severity;\n public SystemAlert(String message, int severity) {\n this.message = message;\n this.severity = severity;\n }\n public String describe() {\n return \"ALERT[\" + message + \"] Sev:\" + severity;\n }\n }\n\n // TASK 1: MinorAlert extends SystemAlert. Severity always 1. Appends \" [MINOR]\".\n {TASK 1: MINOR ALERT}\n\n // TASK 2: CriticalAlert extends SystemAlert. Severity always 9. Appends \" [CRITICAL]\".\n {TASK 2: CRITICAL ALERT}\n\n public static void main(String[] args) {\n SystemAlert a = new MinorAlert(\"door left open\");\n SystemAlert b = new CriticalAlert(\"server breach\");\n System.out.println(a.describe());\n System.out.println(b.describe());\n System.out.println(a.severity);\n System.out.println(b.severity);\n }\n}" + }, + "test_cases": [ + { + "input": "", + "output": "ALERT[door left open] Sev:1 [MINOR]", + "is_hidden": false + }, + { + "input": "", + "output": "ALERT[server breach] Sev:9 [CRITICAL]", + "is_hidden": true + }, + { + "input": "", + "output": "1", + "is_hidden": true + }, + { + "input": "", + "output": "9", + "is_hidden": true + } + ] + }, + { + "title": "ELV-P3-PROB-003", + "description": "// The network device registry lost both its concrete types.\n// Wired and wireless devices both report as unknown hardware.\n// Restore them so the building network can come back online.\n\npublic class ClearanceManager {\n\n static class NetworkDevice {\n protected String id;\n protected int bandwidth;\n public NetworkDevice(String id, int bandwidth) {\n this.id = id;\n this.bandwidth = bandwidth;\n }\n public String report() {\n return \"DEV[\" + id + \"] BW:\" + bandwidth;\n }\n }\n\n // TASK 1: WiredDevice extends NetworkDevice. Bandwidth always 1000. Appends \" [WIRED]\".\n {TASK 1: WIRED DEVICE}\n\n // TASK 2: WirelessDevice extends NetworkDevice. Bandwidth always 300. Appends \" [WIRELESS]\".\n {TASK 2: WIRELESS DEVICE}\n\n public static void main(String[] args) {\n NetworkDevice w = new WiredDevice(\"ETH-01\");\n NetworkDevice x = new WirelessDevice(\"WIFI-02\");\n System.out.println(w.report());\n System.out.println(x.report());\n System.out.println(w.bandwidth);\n System.out.println(x.bandwidth);\n }\n}", + "difficulty": "Hard", + "category": "ELV-P3", + "templates": { + "java": "// The network device registry lost both its concrete types.\n// Wired and wireless devices both report as unknown hardware.\n// Restore them so the building network can come back online.\n\npublic class ClearanceManager {\n\n static class NetworkDevice {\n protected String id;\n protected int bandwidth;\n public NetworkDevice(String id, int bandwidth) {\n this.id = id;\n this.bandwidth = bandwidth;\n }\n public String report() {\n return \"DEV[\" + id + \"] BW:\" + bandwidth;\n }\n }\n\n // TASK 1: WiredDevice extends NetworkDevice. Bandwidth always 1000. Appends \" [WIRED]\".\n {TASK 1: WIRED DEVICE}\n\n // TASK 2: WirelessDevice extends NetworkDevice. Bandwidth always 300. Appends \" [WIRELESS]\".\n {TASK 2: WIRELESS DEVICE}\n\n public static void main(String[] args) {\n NetworkDevice w = new WiredDevice(\"ETH-01\");\n NetworkDevice x = new WirelessDevice(\"WIFI-02\");\n System.out.println(w.report());\n System.out.println(x.report());\n System.out.println(w.bandwidth);\n System.out.println(x.bandwidth);\n }\n}" + }, + "test_cases": [ + { + "input": "", + "output": "DEV[ETH-01] BW:1000 [WIRED]", + "is_hidden": false + }, + { + "input": "", + "output": "DEV[WIFI-02] BW:300 [WIRELESS]", + "is_hidden": true + }, + { + "input": "", + "output": "1000", + "is_hidden": true + }, + { + "input": "", + "output": "300", + "is_hidden": true + } + ] + }, + { + "title": "ELV-P3-PROB-004", + "description": "// Lab equipment tagging is broken \u2014 safe and hazardous items look identical.\n// [NULL] deleted both subclasses. One wrong label and the evacuation fails.\n// Restore them.\n\npublic class ClearanceManager {\n\n static class LabItem {\n protected String code;\n protected int riskLevel;\n public LabItem(String code, int riskLevel) {\n this.code = code;\n this.riskLevel = riskLevel;\n }\n public String label() {\n return \"ITEM[\" + code + \"] Risk:\" + riskLevel;\n }\n }\n\n // TASK 1: SafeEquipment extends LabItem. RiskLevel always 1. Appends \" [SAFE]\".\n {TASK 1: SAFE EQUIPMENT}\n\n // TASK 2: HazardEquipment extends LabItem. RiskLevel always 5. Appends \" [HAZARD]\".\n {TASK 2: HAZARD EQUIPMENT}\n\n public static void main(String[] args) {\n LabItem s = new SafeEquipment(\"CHAIR-04\");\n LabItem h = new HazardEquipment(\"LASER-09\");\n System.out.println(s.label());\n System.out.println(h.label());\n System.out.println(s.riskLevel);\n System.out.println(h.riskLevel);\n }\n}", + "difficulty": "Hard", + "category": "ELV-P3", + "templates": { + "java": "// Lab equipment tagging is broken \u2014 safe and hazardous items look identical.\n// [NULL] deleted both subclasses. One wrong label and the evacuation fails.\n// Restore them.\n\npublic class ClearanceManager {\n\n static class LabItem {\n protected String code;\n protected int riskLevel;\n public LabItem(String code, int riskLevel) {\n this.code = code;\n this.riskLevel = riskLevel;\n }\n public String label() {\n return \"ITEM[\" + code + \"] Risk:\" + riskLevel;\n }\n }\n\n // TASK 1: SafeEquipment extends LabItem. RiskLevel always 1. Appends \" [SAFE]\".\n {TASK 1: SAFE EQUIPMENT}\n\n // TASK 2: HazardEquipment extends LabItem. RiskLevel always 5. Appends \" [HAZARD]\".\n {TASK 2: HAZARD EQUIPMENT}\n\n public static void main(String[] args) {\n LabItem s = new SafeEquipment(\"CHAIR-04\");\n LabItem h = new HazardEquipment(\"LASER-09\");\n System.out.println(s.label());\n System.out.println(h.label());\n System.out.println(s.riskLevel);\n System.out.println(h.riskLevel);\n }\n}" + }, + "test_cases": [ + { + "input": "", + "output": "ITEM[CHAIR-04] Risk:1 [SAFE]", + "is_hidden": false + }, + { + "input": "", + "output": "ITEM[LASER-09] Risk:5 [HAZARD]", + "is_hidden": true + }, + { + "input": "", + "output": "1", + "is_hidden": true + }, + { + "input": "", + "output": "5", + "is_hidden": true + } + ] + }, + { + "title": "ELV-P6-PROB-001", + "description": "// The elevator queue manager is down \u2014 [NULL] wiped the sort logic.\n// The lift now skips floors at random. You are one floor from the exit.\n// Sort the queue manually. Get it moving in the right order.\n\nimport java.util.Arrays;\n\npublic class ElevatorQueue {\n\n public static void sortFloors(int[] floors) {\n int n = floors.length;\n // Sort floors ascending in place. No Arrays.sort() or library sort allowed.\n {PLAYER CODE}\n }\n\n public static void main(String[] args) {\n int[] a = {4, 1, 3, 2, 5};\n sortFloors(a);\n System.out.println(Arrays.toString(a));\n\n int[] b = {9, 2, 7, 1};\n sortFloors(b);\n System.out.println(Arrays.toString(b));\n\n int[] c = {3, 3, 1};\n sortFloors(c);\n System.out.println(Arrays.toString(c));\n }\n}", + "difficulty": "Hard", + "category": "ELV-P6", + "templates": { + "java": "// The elevator queue manager is down \u2014 [NULL] wiped the sort logic.\n// The lift now skips floors at random. You are one floor from the exit.\n// Sort the queue manually. Get it moving in the right order.\n\nimport java.util.Arrays;\n\npublic class ElevatorQueue {\n\n public static void sortFloors(int[] floors) {\n int n = floors.length;\n // Sort floors ascending in place. No Arrays.sort() or library sort allowed.\n {PLAYER CODE}\n }\n\n public static void main(String[] args) {\n int[] a = {4, 1, 3, 2, 5};\n sortFloors(a);\n System.out.println(Arrays.toString(a));\n\n int[] b = {9, 2, 7, 1};\n sortFloors(b);\n System.out.println(Arrays.toString(b));\n\n int[] c = {3, 3, 1};\n sortFloors(c);\n System.out.println(Arrays.toString(c));\n }\n}" + }, + "test_cases": [ + { + "input": "", + "output": "[1, 2, 3, 4, 5]", + "is_hidden": false + }, + { + "input": "", + "output": "[1, 2, 7, 9]", + "is_hidden": true + }, + { + "input": "", + "output": "[1, 3, 3]", + "is_hidden": true + } + ] + }, + { + "title": "ELV-P6-PROB-002", + "description": "// Critical floors need service first \u2014 highest priority number wins.\n// The priority sorter is gone. The lift is serving the wrong floors first.\n// Restore the sort. Descending order. No library methods.\n\nimport java.util.Arrays;\n\npublic class ElevatorQueue {\n\n public static void sortByPriority(int[] priorities) {\n int n = priorities.length;\n // Sort priorities descending in place. No Arrays.sort() or library sort allowed.\n {PLAYER CODE}\n }\n\n public static void main(String[] args) {\n int[] a = {3, 1, 4, 2};\n sortByPriority(a);\n System.out.println(Arrays.toString(a));\n\n int[] b = {5, 5, 2, 8};\n sortByPriority(b);\n System.out.println(Arrays.toString(b));\n }\n}", + "difficulty": "Hard", + "category": "ELV-P6", + "templates": { + "java": "// Critical floors need service first \u2014 highest priority number wins.\n// The priority sorter is gone. The lift is serving the wrong floors first.\n// Restore the sort. Descending order. No library methods.\n\nimport java.util.Arrays;\n\npublic class ElevatorQueue {\n\n public static void sortByPriority(int[] priorities) {\n int n = priorities.length;\n // Sort priorities descending in place. No Arrays.sort() or library sort allowed.\n {PLAYER CODE}\n }\n\n public static void main(String[] args) {\n int[] a = {3, 1, 4, 2};\n sortByPriority(a);\n System.out.println(Arrays.toString(a));\n\n int[] b = {5, 5, 2, 8};\n sortByPriority(b);\n System.out.println(Arrays.toString(b));\n }\n}" + }, + "test_cases": [ + { + "input": "", + "output": "[4, 3, 2, 1]", + "is_hidden": false + }, + { + "input": "", + "output": "[8, 5, 5, 2]", + "is_hidden": true + } + ] + }, + { + "title": "ELV-P6-PROB-003", + "description": "// Lab booking slots include duplicates \u2014 multiple people queued for the same floor.\n// The sorter has to handle that cleanly. [NULL] knew it wouldn't.\n// Fix it. Handle the duplicates. Get the queue sorted.\n\nimport java.util.Arrays;\n\npublic class ElevatorQueue {\n\n public static void sortSlots(int[] slots) {\n int n = slots.length;\n // Sort slots ascending in place. Duplicates must be handled correctly.\n // No Arrays.sort() or library sort allowed.\n {PLAYER CODE}\n }\n\n public static void main(String[] args) {\n int[] a = {3, 1, 3, 2, 1};\n sortSlots(a);\n System.out.println(Arrays.toString(a));\n\n int[] b = {7, 7, 7};\n sortSlots(b);\n System.out.println(Arrays.toString(b));\n }\n}", + "difficulty": "Hard", + "category": "ELV-P6", + "templates": { + "java": "// Lab booking slots include duplicates \u2014 multiple people queued for the same floor.\n// The sorter has to handle that cleanly. [NULL] knew it wouldn't.\n// Fix it. Handle the duplicates. Get the queue sorted.\n\nimport java.util.Arrays;\n\npublic class ElevatorQueue {\n\n public static void sortSlots(int[] slots) {\n int n = slots.length;\n // Sort slots ascending in place. Duplicates must be handled correctly.\n // No Arrays.sort() or library sort allowed.\n {PLAYER CODE}\n }\n\n public static void main(String[] args) {\n int[] a = {3, 1, 3, 2, 1};\n sortSlots(a);\n System.out.println(Arrays.toString(a));\n\n int[] b = {7, 7, 7};\n sortSlots(b);\n System.out.println(Arrays.toString(b));\n }\n}" + }, + "test_cases": [ + { + "input": "", + "output": "[1, 1, 2, 3, 3]", + "is_hidden": false + }, + { + "input": "", + "output": "[7, 7, 7]", + "is_hidden": true + } + ] + }, + { + "title": "ELV-P6-PROB-004", + "description": "// The emergency system needs the three highest-risk floor scores to prioritise response.\n// Sort the scores yourself, then return the top three in a new array.\n// No shortcuts. Write the algorithm from scratch.\n\nimport java.util.Arrays;\n\npublic class ElevatorQueue {\n\n public static int[] topThreeScores(int[] scores) {\n int n = scores.length;\n // Sort scores, then return a new int[] containing only the top 3 values.\n // No Arrays.sort() or library sort allowed.\n {PLAYER CODE}\n }\n\n public static void main(String[] args) {\n System.out.println(Arrays.toString(topThreeScores(new int[]{88, 55, 72, 91, 60})));\n System.out.println(Arrays.toString(topThreeScores(new int[]{100, 50, 75})));\n }\n}", + "difficulty": "Hard", + "category": "ELV-P6", + "templates": { + "java": "// The emergency system needs the three highest-risk floor scores to prioritise response.\n// Sort the scores yourself, then return the top three in a new array.\n// No shortcuts. Write the algorithm from scratch.\n\nimport java.util.Arrays;\n\npublic class ElevatorQueue {\n\n public static int[] topThreeScores(int[] scores) {\n int n = scores.length;\n // Sort scores, then return a new int[] containing only the top 3 values.\n // No Arrays.sort() or library sort allowed.\n {PLAYER CODE}\n }\n\n public static void main(String[] args) {\n System.out.println(Arrays.toString(topThreeScores(new int[]{88, 55, 72, 91, 60})));\n System.out.println(Arrays.toString(topThreeScores(new int[]{100, 50, 75})));\n }\n}" + }, + "test_cases": [ + { + "input": "", + "output": "[91, 88, 72]", + "is_hidden": false + }, + { + "input": "", + "output": "[100, 75, 50]", + "is_hidden": true + } + ] + } +] \ No newline at end of file diff --git a/src/scripts/process_elevatorhall.py b/src/scripts/process_elevatorhall.py new file mode 100644 index 0000000..42dd51f --- /dev/null +++ b/src/scripts/process_elevatorhall.py @@ -0,0 +1,114 @@ +import pandas as pd +import json +import os +import re + +def process_excel(): + xl = pd.ExcelFile('Level 4 Puzzles.xlsx') + chunks = [] + problems = [] + + for name in xl.sheet_names: + df = xl.parse(name) + # Extract Px from L4_Px + match_p = re.search(r'L4_(P\d+)', name) + category_id = f"ELV-{match_p.group(1)}" if match_p else "Elevator Hall" + + if '(Chunk)' in name: + for i, row in df.iterrows(): + template_code = str(row.get('Problem', row.get('Template', ''))) + snippet_block = str(row.get('Expected Input', row.get('Expected Snippet', ''))) + + placeholders = re.findall(r'\{TASK\s*(\d+):[^\}]+\}', template_code) + s_dict = {} + + new_template = template_code + for p_num in placeholders: + placeholder_search = re.search(rf'\{{TASK\s*{p_num}:[^\}}]+\}}', new_template) + if placeholder_search: + placeholder_str = placeholder_search.group(0) + new_template = new_template.replace(placeholder_str, f'{{{{{{snippet_{p_num}}}}}}}') + + pattern = rf'TASK\s*{p_num}\s*\([^\)]+\):\s*(.*?)(?=TASK\s*\d+\s*\(|$)' + match = re.search(pattern, snippet_block, re.DOTALL) + if match: + s_dict[f"snippet_{p_num}"] = match.group(1).strip() + else: + s_dict[f"snippet_{p_num}"] = f"// Missing snippet for Task {p_num}" + + chunk_data = { + "title": f"{category_id}-CHUNK-{i+1:03d}", + "difficulty": str(row.get('Difficulty', "Medium")), + "category": category_id, + "templates": { + "java": { + "name": "Java Implementation", + "template_code": new_template, + "snippets": s_dict + } + }, + "expectation": { + "input": str(row.get('Input', '')), + "output": str(row.get('Expected Output', '')) + } + } + chunks.append(chunk_data) + elif '(Problem)' in name: + for i, row in df.iterrows(): + template_code = str(row.get('Problem', row.get('Template', ''))) + expected_output = str(row.get('Expected Output', '')) + + outputs = [o.strip() for o in expected_output.split('\n') if o.strip()] + + method_match = re.search(r'public\s+static\s+(?:\w+(?:\[\])?)\s+(\w+)\(', template_code) + method_name = method_match.group(1) if method_match else "" + + inputs = [] + if method_name: + # Look only inside the main method + main_match = re.search(r'public\s+static\s+void\s+main\s*\(.*?\)\s*\{(.*?)\}', template_code, re.DOTALL) + if main_match: + main_content = main_match.group(1) + # Look for calls: method_name(...) + # We want the arguments between the first "(" and last ")" for this call + matches = re.finditer(rf'{method_name}\((.*?)\)', main_content) + for m in matches: + inputs.append(m.group(1)) + + test_cases = [] + # Use whichever count is larger, but match them up + count = max(len(inputs), len(outputs)) + for j in range(count): + inp = inputs[j] if j < len(inputs) else "" + out = outputs[j] if j < len(outputs) else "" + test_cases.append({ + "input": inp, + "output": out, + "is_hidden": j > 0 + }) + + problem_data = { + "title": f"{category_id}-PROB-{i+1:03d}", + "description": template_code, + "difficulty": str(row.get('Difficulty', "Hard")), + "category": category_id, + "templates": { + "java": template_code + }, + "test_cases": test_cases + } + problems.append(problem_data) + + out_dir = 'src/scripts/data/java/elevatorhall' + os.makedirs(out_dir, exist_ok=True) + + with open(os.path.join(out_dir, 'chunks.json'), 'w') as f: + json.dump(chunks, f, indent=4) + + with open(os.path.join(out_dir, 'problems.json'), 'w') as f: + json.dump(problems, f, indent=4) + + print(f"Processed {len(chunks)} chunks and {len(problems)} problems with category mapping.") + +if __name__ == "__main__": + process_excel() diff --git a/src/scripts/seed.py b/src/scripts/seed.py index c02fdb6..20b8eec 100644 --- a/src/scripts/seed.py +++ b/src/scripts/seed.py @@ -11,6 +11,13 @@ RiddleTagLink, QuestionTagLink, QuestionCategoryLink, ChunkTemplate, Chunk, Snippet, ChunkCategoryLink, ChunkTagLink, Expectation ) +from scripts.seeders import ( + seed_hallway_java, + seed_lockerroom_java, + seed_restroom_java, + seed_elevatorhall_java +) + logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s') @@ -411,5 +418,14 @@ def add_problem(title, description, difficulty, category_list, tag_list, config= session.commit() logging.info("Chunk seeding process completed.") + # Seed local regional data + logging.info("Seeding regional data...") + seed_hallway_java() + seed_lockerroom_java() + seed_restroom_java() + seed_elevatorhall_java() + logging.info("Regional seeding process completed.") + + if __name__ == "__main__": seed_data() diff --git a/src/scripts/seeders/__init__.py b/src/scripts/seeders/__init__.py index e69de29..49cac23 100644 --- a/src/scripts/seeders/__init__.py +++ b/src/scripts/seeders/__init__.py @@ -0,0 +1,4 @@ +from .seed_hallway_java import seed_hallway_java +from .seed_lockerroom_java import seed_lockerroom_java +from .seed_restroom_java import seed_restroom_java +from .seed_elevatorhall_java import seed_elevatorhall_java diff --git a/src/scripts/seeders/seed_elevatorhall_java.py b/src/scripts/seeders/seed_elevatorhall_java.py new file mode 100644 index 0000000..ce9a72d --- /dev/null +++ b/src/scripts/seeders/seed_elevatorhall_java.py @@ -0,0 +1,159 @@ +import logging +import uuid +import json +import os +from datetime import datetime, timezone +from sqlmodel import Session, select +from infrastructure import engine +from models import ( + Category, Tag, Question, Choice, Chunk, ChunkTemplate, Snippet, Expectation, Problem, TestCase +) +from sqlalchemy.orm.attributes import flag_modified + +logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s') + +NAMESPACE = uuid.NAMESPACE_DNS + +def get_uuid(name: str) -> uuid.UUID: + """Generate a deterministic UUID based on a string name.""" + return uuid.uuid5(NAMESPACE, name) + +def load_json(filename): + base_path = os.path.join(os.path.dirname(__file__), "..", "data", "java", "elevatorhall") + filepath = os.path.join(base_path, filename) + if not os.path.exists(filepath): + logging.warning(f"File not found: {filepath}") + return [] + with open(filepath, "r") as f: + return json.load(f) + +def seed_elevatorhall_java(): + if not engine: + logging.error("No database engine found. Skipping seeding.") + return + + CHUNKS = load_json("chunks.json") + PROBLEMS = load_json("problems.json") + + with Session(engine) as session: + logging.info("Starting JAV_ELVHALL JSON-based seeding process...") + + def get_or_create_category(name): + cat_id = get_uuid(f"cat_{name}") + cat = session.exec(select(Category).where(Category.id == cat_id)).first() + if not cat: + cat = Category(id=cat_id, name=name) + session.add(cat) + session.commit() + session.refresh(cat) + return cat + + def get_or_create_tag(name): + tag_id = get_uuid(f"tag_{name}") + tag = session.exec(select(Tag).where(Tag.id == tag_id)).first() + if not tag: + tag = Tag(id=tag_id, name=name) + session.add(tag) + session.commit() + session.refresh(tag) + return tag + + elv_hall_tag = get_or_create_tag("JAV_ELVHALL") + java_cat = get_or_create_category("Java") + + # 1. Seed Chunks + logging.info(f"Seeding {len(CHUNKS)} Java chunks...") + for c_data in CHUNKS: + c_id = get_uuid(f"jav_elvhall_chunk_{c_data['title']}") + chunk = session.exec(select(Chunk).where(Chunk.id == c_id)).first() + if not chunk: + chunk = Chunk( + id=c_id, + title=c_data["title"], + difficulty=c_data["difficulty"], + created_at=datetime.now(timezone.utc) + ) + chunk.categories = [get_or_create_category(c_data.get("category", "Java Basics"))] + chunk.tags = [elv_hall_tag] + session.add(chunk) + session.flush() + else: + chunk.difficulty = c_data["difficulty"] + for t in chunk.templates: + session.delete(t) + session.flush() + + for lang, t_data in c_data["templates"].items(): + template = ChunkTemplate( + chunk_id=chunk.id, + language=lang, + name=t_data["name"], + template_code=t_data["template_code"], + description=t_data.get("description", f"Standard {lang} boilerplate") + ) + session.add(template) + session.flush() + + for key, content in t_data.get("snippets", {}).items(): + s = Snippet(template_id=template.id, placeholder_key=key, code_content=content) + session.add(s) + + if "expectation" in c_data: + for ex in chunk.expectations: + session.delete(ex) + session.flush() + ex = Expectation( + chunk_id=chunk.id, + input=c_data["expectation"]["input"], + output=c_data["expectation"]["output"] + ) + session.add(ex) + + # 2. Seed Problems + logging.info(f"Seeding {len(PROBLEMS)} Java problems...") + for p_data in PROBLEMS: + p_id = get_uuid(f"jav_elvhall_prob_{p_data['title']}") + problem = session.exec(select(Problem).where(Problem.id == p_id)).first() + if not problem: + problem = Problem( + id=p_id, + title=p_data["title"], + description=p_data["description"], + difficulty=p_data["difficulty"], + config={"templates": p_data.get("templates", {})} + ) + problem.categories = [get_or_create_category(p_data.get("category", "Java Algorithms"))] + problem.tags = [elv_hall_tag] + session.add(problem) + else: + problem.description = p_data["description"] + problem.difficulty = p_data["difficulty"] + config = problem.config or {} + config["templates"] = p_data.get("templates", {}) + problem.config = config + flag_modified(problem, "config") + session.add(problem) + session.flush() + + if "test_cases" in p_data: + for tc in problem.test_cases: + session.delete(tc) + session.flush() + + for i, tc_data in enumerate(p_data["test_cases"]): + tc_id = get_uuid(f"jav_elvhall_tc_{p_data['title']}_{i}") + tc = TestCase( + id=tc_id, + problem_id=p_id, + input=str(tc_data["input"]), + output=str(tc_data["output"]), + is_hidden=tc_data.get("is_hidden", True), + sort_order=i + 1 + ) + session.add(tc) + + session.commit() + logging.info("JAV_ELVHALL JSON-based seeding completed successfully.") + +if __name__ == "__main__": + seed_elevatorhall_java() diff --git a/src/services/chunk_service.py b/src/services/chunk_service.py index 114c0c7..c756591 100644 --- a/src/services/chunk_service.py +++ b/src/services/chunk_service.py @@ -59,6 +59,6 @@ def get_chunk(self, chunk_id, lang=None): return self._process_chunk(chunk) return None - def get_random_chunks(self, limit=1, lang=None, tags=None): - chunks = self.repo.find_random(limit=limit, lang=lang, tags=tags) + def get_random_chunks(self, limit=1, lang=None, tags=None, category=None): + chunks = self.repo.find_random(limit=limit, lang=lang, tags=tags, category=category) return [self._process_chunk(c) for c in chunks] From 070823ef358485c07ee776aef178b7d0cd277583 Mon Sep 17 00:00:00 2001 From: Pathompum Jirakarnpaisan <107536914+Saannddy@users.noreply.github.com> Date: Sat, 4 Apr 2026 01:24:06 +0700 Subject: [PATCH 4/6] refactor: update seeder imports to avoid circular dependency warnings by removing package-level exports --- src/scripts/seed.py | 10 ++++------ src/scripts/seeders/__init__.py | 6 ++---- 2 files changed, 6 insertions(+), 10 deletions(-) diff --git a/src/scripts/seed.py b/src/scripts/seed.py index 20b8eec..8e646b8 100644 --- a/src/scripts/seed.py +++ b/src/scripts/seed.py @@ -11,12 +11,10 @@ RiddleTagLink, QuestionTagLink, QuestionCategoryLink, ChunkTemplate, Chunk, Snippet, ChunkCategoryLink, ChunkTagLink, Expectation ) -from scripts.seeders import ( - seed_hallway_java, - seed_lockerroom_java, - seed_restroom_java, - seed_elevatorhall_java -) +from scripts.seeders.seed_hallway_java import seed_hallway_java +from scripts.seeders.seed_lockerroom_java import seed_lockerroom_java +from scripts.seeders.seed_restroom_java import seed_restroom_java +from scripts.seeders.seed_elevatorhall_java import seed_elevatorhall_java diff --git a/src/scripts/seeders/__init__.py b/src/scripts/seeders/__init__.py index 49cac23..4794268 100644 --- a/src/scripts/seeders/__init__.py +++ b/src/scripts/seeders/__init__.py @@ -1,4 +1,2 @@ -from .seed_hallway_java import seed_hallway_java -from .seed_lockerroom_java import seed_lockerroom_java -from .seed_restroom_java import seed_restroom_java -from .seed_elevatorhall_java import seed_elevatorhall_java +# This file makes seeders a Python package. +# Modules are not imported here to avoid RuntimeWarning when run individually with -m. From 85a614069434a5d47c27b51f0c8d16feaf21f305 Mon Sep 17 00:00:00 2001 From: Pathompum Jirakarnpaisan <107536914+Saannddy@users.noreply.github.com> Date: Sat, 4 Apr 2026 01:24:29 +0700 Subject: [PATCH 5/6] chore: remove package initialization comment from scripts module --- src/scripts/__init__.py | 1 - 1 file changed, 1 deletion(-) diff --git a/src/scripts/__init__.py b/src/scripts/__init__.py index 3210928..e69de29 100644 --- a/src/scripts/__init__.py +++ b/src/scripts/__init__.py @@ -1 +0,0 @@ -# This file makes the folder a Python package. From 8519a77b0c766479d720497a0a571ae305e74f94 Mon Sep 17 00:00:00 2001 From: Pathompum Jirakarnpaisan <107536914+Saannddy@users.noreply.github.com> Date: Sun, 5 Apr 2026 17:04:08 +0700 Subject: [PATCH 6/6] feat: add level 4 Java coding challenges and update chunk retrieval configuration --- bruno/local/Chunk/Get Random Chunks.bru | 5 +- .../data/java/elevatorhall/chunks.json | 64 +++---- src/scripts/data/java/temp/chunks.lvl4.json | 162 ++++++++++++++++++ 3 files changed, 197 insertions(+), 34 deletions(-) create mode 100644 src/scripts/data/java/temp/chunks.lvl4.json diff --git a/bruno/local/Chunk/Get Random Chunks.bru b/bruno/local/Chunk/Get Random Chunks.bru index c650339..d017533 100644 --- a/bruno/local/Chunk/Get Random Chunks.bru +++ b/bruno/local/Chunk/Get Random Chunks.bru @@ -5,11 +5,12 @@ meta { } get { - url: {{base_url}}/chunk/random?tags=JAV_LOCKERROOM + url: {{base_url}}/chunk/random?tags=JAV_ELVHALL&category=ELV-P5 body: none auth: none } params:query { - tags: JAV_LOCKERROOM + tags: JAV_ELVHALL + category: ELV-P5 } diff --git a/src/scripts/data/java/elevatorhall/chunks.json b/src/scripts/data/java/elevatorhall/chunks.json index 257e8f7..c408967 100644 --- a/src/scripts/data/java/elevatorhall/chunks.json +++ b/src/scripts/data/java/elevatorhall/chunks.json @@ -8,15 +8,15 @@ "name": "Java Implementation", "template_code": "// [NULL] stripped the exception handling from the ID scanner.\n// It now crashes on any non-integer input and floods the audit log with errors.\n// Restore the three blocks. Every scan must be logged, pass or fail.\n\npublic class CheckpointScanner {\n\n public static String parseStudentID(String input) {\n try {\n // TASK 1: Parse input. Return \"VALID:\" + id if 10000\u201399999, else \"INVALID:OUT_OF_RANGE\".\n {{{snippet_1}}}\n } catch (NumberFormatException e) {\n // TASK 2: Return \"INVALID:NOT_A_NUMBER\".\n {{{snippet_2}}}\n } finally {\n // TASK 3: Always print \"scan attempt logged\".\n {{{snippet_3}}}\n }\n }\n}", "snippets": { - "snippet_1": "int id = Integer.parseInt(input);\nif (id >= 10000 && id <= 99999) {\n return \"VALID:\" + id;\n} else {\n return \"INVALID:OUT_OF_RANGE\";\n}", - "snippet_2": "return \"INVALID:NOT_A_NUMBER\";", - "snippet_3": "System.out.println(\"scan attempt logged\");" + "snippet_1": "None to be shown here", + "snippet_2": "None to be shown here", + "snippet_3": "None to be shown here" } } }, "expectation": { - "input": "", - "output": "" + "input": "12345", + "output": "VALID:12345" } }, { @@ -28,15 +28,15 @@ "name": "Java Implementation", "template_code": "// The room code scanner is throwing unhandled exceptions on every bad input.\n// [NULL] knew exactly which lines to delete to break the audit trail.\n// Restore all three exception blocks.\n\npublic class CheckpointScanner {\n\n public static String parseRoomCode(String input) {\n try {\n // TASK 1: Parse input. Return \"ROOM:\" + code if 100\u2013999, else \"INVALID:NOT_A_ROOM\".\n {{{snippet_1}}}\n } catch (NumberFormatException e) {\n // TASK 2: Return \"INVALID:FORMAT_ERROR\".\n {{{snippet_2}}}\n } finally {\n // TASK 3: Always print \"door scan logged\".\n {{{snippet_3}}}\n }\n }\n}", "snippets": { - "snippet_1": "int code = Integer.parseInt(input);\nif (code >= 100 && code <= 999) {\n return \"ROOM:\" + code;\n} else {\n return \"INVALID:NOT_A_ROOM\";\n}", - "snippet_2": "return \"INVALID:FORMAT_ERROR\";", - "snippet_3": "System.out.println(\"door scan logged\");" + "snippet_1": "None to be shown here", + "snippet_2": "None to be shown here", + "snippet_3": "None to be shown here" } } }, "expectation": { - "input": "", - "output": "" + "input": "123", + "output": "ROOM:123" } }, { @@ -48,15 +48,15 @@ "name": "Java Implementation", "template_code": "// The port scanner crashes on anything that is not a clean integer.\n// Without proper exception handling the network audit trail is blind.\n// Restore it.\n\npublic class CheckpointScanner {\n\n public static String parsePort(String input) {\n try {\n // TASK 1: Parse input. Return \"PORT:\" + number if 1\u201365535, else \"INVALID:PORT_OUT_OF_RANGE\".\n {{{snippet_1}}}\n } catch (NumberFormatException e) {\n // TASK 2: Return \"INVALID:NOT_A_PORT\".\n {{{snippet_2}}}\n } finally {\n // TASK 3: Always print \"connection attempt logged\".\n {{{snippet_3}}}\n }\n }\n}", "snippets": { - "snippet_1": "int port = Integer.parseInt(input);\nif (port >= 1 && port <= 65535) {\n return \"PORT:\" + port;\n} else {\n return \"INVALID:PORT_OUT_OF_RANGE\";\n}", - "snippet_2": "return \"INVALID:NOT_A_PORT\";", - "snippet_3": "System.out.println(\"connection attempt logged\");" + "snippet_1": "None to be shown here", + "snippet_2": "None to be shown here", + "snippet_3": "None to be shown here" } } }, "expectation": { - "input": "", - "output": "" + "input": "80", + "output": "PORT:80" } }, { @@ -68,15 +68,15 @@ "name": "Java Implementation", "template_code": "// The elevator rejects every floor request because the parser throws on bad input.\n// [NULL] removed the safety net. Restore the exception blocks.\n// The finally block is not optional \u2014 the lift log must always write.\n\npublic class CheckpointScanner {\n\n public static String parseFloor(String input) {\n try {\n // TASK 1: Parse input. Return \"FLOOR:\" + number if 1\u201310, else \"INVALID:NO_SUCH_FLOOR\".\n {{{snippet_1}}}\n } catch (NumberFormatException e) {\n // TASK 2: Return \"INVALID:NOT_A_NUMBER\".\n {{{snippet_2}}}\n } finally {\n // TASK 3: Always print \"elevator request logged\".\n {{{snippet_3}}}\n }\n }\n}", "snippets": { - "snippet_1": "int floor = Integer.parseInt(input);\nif (floor >= 1 && floor <= 10) {\n return \"FLOOR:\" + floor;\n} else {\n return \"INVALID:NO_SUCH_FLOOR\";\n}", - "snippet_2": "return \"INVALID:NOT_A_NUMBER\";", - "snippet_3": "System.out.println(\"elevator request logged\");" + "snippet_1": "None to be shown here", + "snippet_2": "None to be shown here", + "snippet_3": "None to be shown here" } } }, "expectation": { - "input": "", - "output": "" + "input": "5", + "output": "FLOOR:5" } }, { @@ -88,9 +88,9 @@ "name": "Java Implementation", "template_code": "// 4,847 log entries. The threat filter is gone \u2014 [NULL] deleted it first.\n// Without it the emergency system cannot assess severity.\n// Find the threats. The building needs this report before it can act.\n\nimport java.util.ArrayList;\n\npublic class ThreatAnalyser {\n\n public static String analyzeLogs(ArrayList logs) {\n\n // TASK 1: Declare a counter and an ArrayList for threat descriptions.\n {{{snippet_1}}}\n\n for (String entry : logs) {\n // TASK 2: If entry starts with \"THREAT:\", increment and collect the description (after 8 chars).\n {{{snippet_2}}}\n }\n\n // TASK 3: Return \"THREATS:0|none\" if clean, else \"THREATS:\" + count + \"|\" + descriptions joined by \",\".\n {{{snippet_3}}}\n }\n\n public static void main(String[] args) {\n ArrayList logs1 = new ArrayList<>();\n logs1.add(\"INFO: door opened\");\n logs1.add(\"THREAT: brute force\");\n logs1.add(\"INFO: scan ok\");\n logs1.add(\"THREAT: port scan\");\n logs1.add(\"THREAT: login fail\");\n System.out.println(analyzeLogs(logs1));\n\n ArrayList logs2 = new ArrayList<>();\n logs2.add(\"INFO: all clear\");\n System.out.println(analyzeLogs(logs2));\n }\n}", "snippets": { - "snippet_1": "int count = 0;\nArrayList threats = new ArrayList<>();", - "snippet_2": "if (entry.startsWith(\"THREAT:\")) {\n count++;\n threats.add(entry.substring(8));\n}", - "snippet_3": "if (count == 0) return \"THREATS:0|none\";\nreturn \"THREATS:\" + count + \"|\" + String.join(\",\", threats);" + "snippet_1": "None to be shown here", + "snippet_2": "None to be shown here", + "snippet_3": "None to be shown here" } } }, @@ -108,9 +108,9 @@ "name": "Java Implementation", "template_code": "// The server error filter was wiped along with the intrusion logs.\n// Critical errors are invisible to the monitoring system.\n// Restore the filter \u2014 find every ERROR entry and report the count.\n\nimport java.util.ArrayList;\n\npublic class ThreatAnalyser {\n\n public static String filterErrors(ArrayList logs) {\n\n // TASK 1: Declare a counter and an ArrayList for error messages.\n {{{snippet_1}}}\n\n for (String entry : logs) {\n // TASK 2: If entry starts with \"ERROR:\", increment and collect the message (after 7 chars).\n {{{snippet_2}}}\n }\n\n // TASK 3: Return \"ERRORS:0|none\" if clean, else \"ERRORS:\" + count + \"|\" + messages joined by \",\".\n {{{snippet_3}}}\n }\n\n public static void main(String[] args) {\n ArrayList logs1 = new ArrayList<>();\n logs1.add(\"INFO: server started\");\n logs1.add(\"ERROR: disk full\");\n logs1.add(\"ERROR: null pointer\");\n logs1.add(\"INFO: backup ok\");\n System.out.println(filterErrors(logs1));\n\n ArrayList logs2 = new ArrayList<>();\n logs2.add(\"INFO: running\");\n System.out.println(filterErrors(logs2));\n }\n}", "snippets": { - "snippet_1": "int count = 0;\nArrayList errors = new ArrayList<>();", - "snippet_2": "if (entry.startsWith(\"ERROR:\")) {\n count++;\n errors.add(entry.substring(7));\n}", - "snippet_3": "if (count == 0) return \"ERRORS:0|none\";\nreturn \"ERRORS:\" + count + \"|\" + String.join(\",\", errors);" + "snippet_1": "None to be shown here", + "snippet_2": "None to be shown here", + "snippet_3": "None to be shown here" } } }, @@ -128,9 +128,9 @@ "name": "Java Implementation", "template_code": "// The badge access log is full of denied entries \u2014 someone was probing every door.\n// The scanner that should have flagged them is offline.\n// Find every DENIED entry before [NULL] makes another move.\n\nimport java.util.ArrayList;\n\npublic class ThreatAnalyser {\n\n public static String findDenied(ArrayList entries) {\n\n // TASK 1: Declare a counter and an ArrayList for denied entries.\n {{{snippet_1}}}\n\n for (String entry : entries) {\n // TASK 2: If entry contains \"DENIED\" anywhere, increment and collect the full entry.\n {{{snippet_2}}}\n }\n\n // TASK 3: Return \"DENIED:0|none\" if none, else \"DENIED:\" + count + \"|\" + entries joined by \",\".\n {{{snippet_3}}}\n }\n\n public static void main(String[] args) {\n ArrayList e1 = new ArrayList<>();\n e1.add(\"Student 001: GRANTED\");\n e1.add(\"Student 002: DENIED low clearance\");\n e1.add(\"Student 003: GRANTED\");\n e1.add(\"Visitor 01: DENIED no badge\");\n System.out.println(findDenied(e1));\n\n ArrayList e2 = new ArrayList<>();\n e2.add(\"Staff 001: GRANTED\");\n System.out.println(findDenied(e2));\n }\n}", "snippets": { - "snippet_1": "int count = 0;\nArrayList denied = new ArrayList<>();", - "snippet_2": "if (entry.contains(\"DENIED\")) {\n count++;\n denied.add(entry);\n}", - "snippet_3": "if (count == 0) return \"DENIED:0|none\";\nreturn \"DENIED:\" + count + \"|\" + String.join(\",\", denied);" + "snippet_1": "None to be shown here", + "snippet_2": "None to be shown here", + "snippet_3": "None to be shown here" } } }, @@ -148,9 +148,9 @@ "name": "Java Implementation", "template_code": "// Elevator requests are piling up but the floor filter is down.\n// Security needs to know exactly how many calls are going to each floor.\n// Restore the filter \u2014 match by floor number, report the count.\n\nimport java.util.ArrayList;\n\npublic class ThreatAnalyser {\n\n public static String findFloorRequests(ArrayList logs, int floor) {\n\n // TASK 1: Declare a counter and an ArrayList for matching requests.\n {{{snippet_1}}}\n\n for (String entry : logs) {\n // TASK 2: If entry ends with \":\" + floor, increment and collect the full entry.\n {{{snippet_2}}}\n }\n\n // TASK 3: Return \"FLOOR\" + floor + \":0|none\" if none,\n // else \"FLOOR\" + floor + \":\" + count + \"|\" + entries joined by \",\".\n {{{snippet_3}}}\n }\n\n public static void main(String[] args) {\n ArrayList logs = new ArrayList<>();\n logs.add(\"User A requested floor:2\");\n logs.add(\"User B requested floor:3\");\n logs.add(\"User C requested floor:2\");\n logs.add(\"User D requested floor:1\");\n System.out.println(findFloorRequests(logs, 2));\n System.out.println(findFloorRequests(logs, 5));\n }\n}", "snippets": { - "snippet_1": "int count = 0;\nArrayList matches = new ArrayList<>();", - "snippet_2": "if (entry.endsWith(\":\" + floor)) {\n count++;\n matches.add(entry);\n}", - "snippet_3": "if (count == 0) return \"FLOOR\" + floor + \":0|none\";\nreturn \"FLOOR\" + floor + \":\" + count + \"|\" + String.join(\",\", matches);" + "snippet_1": "None to be shown here", + "snippet_2": "None to be shown here", + "snippet_3": "None to be shown here" } } }, diff --git a/src/scripts/data/java/temp/chunks.lvl4.json b/src/scripts/data/java/temp/chunks.lvl4.json new file mode 100644 index 0000000..f331381 --- /dev/null +++ b/src/scripts/data/java/temp/chunks.lvl4.json @@ -0,0 +1,162 @@ +[ + { + "title": "ELV-P4-CHUNK-001", + "difficulty": "Medium", + "category": "ELV-P4", + "templates": { + "java": { + "name": "Java Implementation", + "template_code": "// [NULL] stripped the exception handling from the ID scanner.\n// It now crashes on any non-integer input and floods the audit log with errors.\n// Restore the three blocks. Every scan must be logged, pass or fail.\n\npublic class CheckpointScanner {\n\n public static String parseStudentID(String input) {\n try {\n // TASK 1: Parse input. Return \"VALID:\" + id if 10000\u201399999, else \"INVALID:OUT_OF_RANGE\".\n {{{snippet_1}}}\n } catch (NumberFormatException e) {\n // TASK 2: Return \"INVALID:NOT_A_NUMBER\".\n {{{snippet_2}}}\n } finally {\n // TASK 3: Always print \"scan attempt logged\".\n {{{snippet_3}}}\n }\n }\n}", + "snippets": { + "snippet_1": "int id = Integer.parseInt(input);\nif (id >= 10000 && id <= 99999) {\n return \"VALID:\" + id;\n} else {\n return \"INVALID:OUT_OF_RANGE\";\n}", + "snippet_2": "return \"INVALID:NOT_A_NUMBER\";", + "snippet_3": "System.out.println(\"scan attempt logged\");" + } + } + }, + "expectation": { + "input": "12345", + "output": "VALID:12345" + } + }, + { + "title": "ELV-P4-CHUNK-002", + "difficulty": "Medium", + "category": "ELV-P4", + "templates": { + "java": { + "name": "Java Implementation", + "template_code": "// The room code scanner is throwing unhandled exceptions on every bad input.\n// [NULL] knew exactly which lines to delete to break the audit trail.\n// Restore all three exception blocks.\n\npublic class CheckpointScanner {\n\n public static String parseRoomCode(String input) {\n try {\n // TASK 1: Parse input. Return \"ROOM:\" + code if 100\u2013999, else \"INVALID:NOT_A_ROOM\".\n {{{snippet_1}}}\n } catch (NumberFormatException e) {\n // TASK 2: Return \"INVALID:FORMAT_ERROR\".\n {{{snippet_2}}}\n } finally {\n // TASK 3: Always print \"door scan logged\".\n {{{snippet_3}}}\n }\n }\n}", + "snippets": { + "snippet_1": "int code = Integer.parseInt(input);\nif (code >= 100 && code <= 999) {\n return \"ROOM:\" + code;\n} else {\n return \"INVALID:NOT_A_ROOM\";\n}", + "snippet_2": "return \"INVALID:FORMAT_ERROR\";", + "snippet_3": "System.out.println(\"door scan logged\");" + } + } + }, + "expectation": { + "input": "123", + "output": "ROOM:123" + } + }, + { + "title": "ELV-P4-CHUNK-003", + "difficulty": "Medium", + "category": "ELV-P4", + "templates": { + "java": { + "name": "Java Implementation", + "template_code": "// The port scanner crashes on anything that is not a clean integer.\n// Without proper exception handling the network audit trail is blind.\n// Restore it.\n\npublic class CheckpointScanner {\n\n public static String parsePort(String input) {\n try {\n // TASK 1: Parse input. Return \"PORT:\" + number if 1\u201365535, else \"INVALID:PORT_OUT_OF_RANGE\".\n {{{snippet_1}}}\n } catch (NumberFormatException e) {\n // TASK 2: Return \"INVALID:NOT_A_PORT\".\n {{{snippet_2}}}\n } finally {\n // TASK 3: Always print \"connection attempt logged\".\n {{{snippet_3}}}\n }\n }\n}", + "snippets": { + "snippet_1": "int port = Integer.parseInt(input);\nif (port >= 1 && port <= 65535) {\n return \"PORT:\" + port;\n} else {\n return \"INVALID:PORT_OUT_OF_RANGE\";\n}", + "snippet_2": "return \"INVALID:NOT_A_PORT\";", + "snippet_3": "System.out.println(\"connection attempt logged\");" + } + } + }, + "expectation": { + "input": "80", + "output": "PORT:80" + } + }, + { + "title": "ELV-P4-CHUNK-004", + "difficulty": "Medium", + "category": "ELV-P4", + "templates": { + "java": { + "name": "Java Implementation", + "template_code": "// The elevator rejects every floor request because the parser throws on bad input.\n// [NULL] removed the safety net. Restore the exception blocks.\n// The finally block is not optional \u2014 the lift log must always write.\n\npublic class CheckpointScanner {\n\n public static String parseFloor(String input) {\n try {\n // TASK 1: Parse input. Return \"FLOOR:\" + number if 1\u201310, else \"INVALID:NO_SUCH_FLOOR\".\n {{{snippet_1}}}\n } catch (NumberFormatException e) {\n // TASK 2: Return \"INVALID:NOT_A_NUMBER\".\n {{{snippet_2}}}\n } finally {\n // TASK 3: Always print \"elevator request logged\".\n {{{snippet_3}}}\n }\n }\n}", + "snippets": { + "snippet_1": "int floor = Integer.parseInt(input);\nif (floor >= 1 && floor <= 10) {\n return \"FLOOR:\" + floor;\n} else {\n return \"INVALID:NO_SUCH_FLOOR\";\n}", + "snippet_2": "return \"INVALID:NOT_A_NUMBER\";", + "snippet_3": "System.out.println(\"elevator request logged\");" + } + } + }, + "expectation": { + "input": "5", + "output": "FLOOR:5" + } + }, + { + "title": "ELV-P5-CHUNK-001", + "difficulty": "Medium", + "category": "ELV-P5", + "templates": { + "java": { + "name": "Java Implementation", + "template_code": "// 4,847 log entries. The threat filter is gone \u2014 [NULL] deleted it first.\n// Without it the emergency system cannot assess severity.\n// Find the threats. The building needs this report before it can act.\n\nimport java.util.ArrayList;\n\npublic class ThreatAnalyser {\n\n public static String analyzeLogs(ArrayList logs) {\n\n // TASK 1: Declare a counter and an ArrayList for threat descriptions.\n {{{snippet_1}}}\n\n for (String entry : logs) {\n // TASK 2: If entry starts with \"THREAT:\", increment and collect the description (after 8 chars).\n {{{snippet_2}}}\n }\n\n // TASK 3: Return \"THREATS:0|none\" if clean, else \"THREATS:\" + count + \"|\" + descriptions joined by \",\".\n {{{snippet_3}}}\n }\n\n public static void main(String[] args) {\n ArrayList logs1 = new ArrayList<>();\n logs1.add(\"INFO: door opened\");\n logs1.add(\"THREAT: brute force\");\n logs1.add(\"INFO: scan ok\");\n logs1.add(\"THREAT: port scan\");\n logs1.add(\"THREAT: login fail\");\n System.out.println(analyzeLogs(logs1));\n\n ArrayList logs2 = new ArrayList<>();\n logs2.add(\"INFO: all clear\");\n System.out.println(analyzeLogs(logs2));\n }\n}", + "snippets": { + "snippet_1": "int count = 0;\nArrayList threats = new ArrayList<>();", + "snippet_2": "if (entry.startsWith(\"THREAT:\")) {\n count++;\n threats.add(entry.substring(8));\n}", + "snippet_3": "if (count == 0) return \"THREATS:0|none\";\nreturn \"THREATS:\" + count + \"|\" + String.join(\",\", threats);" + } + } + }, + "expectation": { + "input": "", + "output": "" + } + }, + { + "title": "ELV-P5-CHUNK-002", + "difficulty": "Medium", + "category": "ELV-P5", + "templates": { + "java": { + "name": "Java Implementation", + "template_code": "// The server error filter was wiped along with the intrusion logs.\n// Critical errors are invisible to the monitoring system.\n// Restore the filter \u2014 find every ERROR entry and report the count.\n\nimport java.util.ArrayList;\n\npublic class ThreatAnalyser {\n\n public static String filterErrors(ArrayList logs) {\n\n // TASK 1: Declare a counter and an ArrayList for error messages.\n {{{snippet_1}}}\n\n for (String entry : logs) {\n // TASK 2: If entry starts with \"ERROR:\", increment and collect the message (after 7 chars).\n {{{snippet_2}}}\n }\n\n // TASK 3: Return \"ERRORS:0|none\" if clean, else \"ERRORS:\" + count + \"|\" + messages joined by \",\".\n {{{snippet_3}}}\n }\n\n public static void main(String[] args) {\n ArrayList logs1 = new ArrayList<>();\n logs1.add(\"INFO: server started\");\n logs1.add(\"ERROR: disk full\");\n logs1.add(\"ERROR: null pointer\");\n logs1.add(\"INFO: backup ok\");\n System.out.println(filterErrors(logs1));\n\n ArrayList logs2 = new ArrayList<>();\n logs2.add(\"INFO: running\");\n System.out.println(filterErrors(logs2));\n }\n}", + "snippets": { + "snippet_1": "int count = 0;\nArrayList errors = new ArrayList<>();", + "snippet_2": "if (entry.startsWith(\"ERROR:\")) {\n count++;\n errors.add(entry.substring(7));\n}", + "snippet_3": "if (count == 0) return \"ERRORS:0|none\";\nreturn \"ERRORS:\" + count + \"|\" + String.join(\",\", errors);" + } + } + }, + "expectation": { + "input": "", + "output": "" + } + }, + { + "title": "ELV-P5-CHUNK-003", + "difficulty": "Medium", + "category": "ELV-P5", + "templates": { + "java": { + "name": "Java Implementation", + "template_code": "// The badge access log is full of denied entries \u2014 someone was probing every door.\n// The scanner that should have flagged them is offline.\n// Find every DENIED entry before [NULL] makes another move.\n\nimport java.util.ArrayList;\n\npublic class ThreatAnalyser {\n\n public static String findDenied(ArrayList entries) {\n\n // TASK 1: Declare a counter and an ArrayList for denied entries.\n {{{snippet_1}}}\n\n for (String entry : entries) {\n // TASK 2: If entry contains \"DENIED\" anywhere, increment and collect the full entry.\n {{{snippet_2}}}\n }\n\n // TASK 3: Return \"DENIED:0|none\" if none, else \"DENIED:\" + count + \"|\" + entries joined by \",\".\n {{{snippet_3}}}\n }\n\n public static void main(String[] args) {\n ArrayList e1 = new ArrayList<>();\n e1.add(\"Student 001: GRANTED\");\n e1.add(\"Student 002: DENIED low clearance\");\n e1.add(\"Student 003: GRANTED\");\n e1.add(\"Visitor 01: DENIED no badge\");\n System.out.println(findDenied(e1));\n\n ArrayList e2 = new ArrayList<>();\n e2.add(\"Staff 001: GRANTED\");\n System.out.println(findDenied(e2));\n }\n}", + "snippets": { + "snippet_1": "int count = 0;\nArrayList denied = new ArrayList<>();", + "snippet_2": "if (entry.contains(\"DENIED\")) {\n count++;\n denied.add(entry);\n}", + "snippet_3": "if (count == 0) return \"DENIED:0|none\";\nreturn \"DENIED:\" + count + \"|\" + String.join(\",\", denied);" + } + } + }, + "expectation": { + "input": "", + "output": "" + } + }, + { + "title": "ELV-P5-CHUNK-004", + "difficulty": "Medium", + "category": "ELV-P5", + "templates": { + "java": { + "name": "Java Implementation", + "template_code": "// Elevator requests are piling up but the floor filter is down.\n// Security needs to know exactly how many calls are going to each floor.\n// Restore the filter \u2014 match by floor number, report the count.\n\nimport java.util.ArrayList;\n\npublic class ThreatAnalyser {\n\n public static String findFloorRequests(ArrayList logs, int floor) {\n\n // TASK 1: Declare a counter and an ArrayList for matching requests.\n {{{snippet_1}}}\n\n for (String entry : logs) {\n // TASK 2: If entry ends with \":\" + floor, increment and collect the full entry.\n {{{snippet_2}}}\n }\n\n // TASK 3: Return \"FLOOR\" + floor + \":0|none\" if none,\n // else \"FLOOR\" + floor + \":\" + count + \"|\" + entries joined by \",\".\n {{{snippet_3}}}\n }\n\n public static void main(String[] args) {\n ArrayList logs = new ArrayList<>();\n logs.add(\"User A requested floor:2\");\n logs.add(\"User B requested floor:3\");\n logs.add(\"User C requested floor:2\");\n logs.add(\"User D requested floor:1\");\n System.out.println(findFloorRequests(logs, 2));\n System.out.println(findFloorRequests(logs, 5));\n }\n}", + "snippets": { + "snippet_1": "int count = 0;\nArrayList matches = new ArrayList<>();", + "snippet_2": "if (entry.endsWith(\":\" + floor)) {\n count++;\n matches.add(entry);\n}", + "snippet_3": "if (count == 0) return \"FLOOR\" + floor + \":0|none\";\nreturn \"FLOOR\" + floor + \":\" + count + \"|\" + String.join(\",\", matches);" + } + } + }, + "expectation": { + "input": "", + "output": "" + } + } +] \ No newline at end of file