Spaces:
Sleeping
Sleeping
| import gradio as gr | |
| import random | |
| from typing import Dict, List | |
| PASS_POINTS = 13 | |
| NUM_EXAM_QUESTIONS = 8 | |
| MAX_QUESTION_SCORE = 3 | |
| class ExamPrepApp: | |
| def __init__(self): | |
| self.flashcards = self._parse_flashcards() | |
| self.all_topics = list(range(len(self.flashcards))) | |
| self.reset() | |
| def reset(self): | |
| random.shuffle(self.all_topics) | |
| self.exam_questions = self.all_topics[:NUM_EXAM_QUESTIONS] | |
| self.answered = {} # qidx: score (0-3) | |
| self.answered_yes = set() | |
| self.answered_no = set() | |
| self.current_index = 0 | |
| self.last_answer = "" | |
| def _parse_flashcards(self) -> List[Dict[str, str]]: | |
| return [ | |
| # 1 | |
| { | |
| "question": "Addresses in computer networks β structure, properties", | |
| "answer": """Addresses are used to identify communicating nodes or resources in a network. | |
| Typically this is some number (IP, MAC, port) or a string (URL, domain). | |
| Addresses should be unique within a network to be a proper ID, but there are exceptions (e.g private IP addresses are not unique, because they are used with port in a SNAT configuration)""" | |
| }, | |
| # 2 | |
| { | |
| "question": "Addressing features in different TCP/IP layers", | |
| "answer": """β’ Physical - MAC (βphysicalβ) addresses - visible only in the network (Directly connected devices), used by switches | |
| β’ Internet - IP addresses, visible globally (except private IP addresses) | |
| β’ sometimes ICMP payload is used (e.g for NAT), used by routers | |
| β’ Transport - ports, used by operating system, or routers in case of NAT | |
| β’ Application - paths, URLs, application-specific""" | |
| }, | |
| # 3 | |
| { | |
| "question": "ARP protocol", | |
| "answer": """β’ Used to discover MAC addresses of devices in the network (IP to MAC mapping) | |
| β’ Works on OSI data link layer | |
| β’ Typical procedure: | |
| β One device broadcasts request for MAC address | |
| β Other devices respond with their IP+MAC addresses | |
| β’ Info is stored in βARP tableβ and used when sending next packets""" | |
| }, | |
| # 4 | |
| { | |
| "question": "Basic transmission parameters", | |
| "answer": """β’ Bandwidth (mbps/gbps - mega/giga bits per second) - how much bits can be sent through a medium | |
| β’ Throughput - actual amount of data that can be sent, including control, errors, headers etc. | |
| β’ Propagation delay, RTT = latency | |
| β’ Jitter | |
| β’ Error coefficients (lost packet rate, bit error rate)""" | |
| }, | |
| # 5 | |
| { | |
| "question": "Client-server mode of transmission", | |
| "answer": """There is a single host (βserverβ) which processes βrequestsβ from other hosts (βclientsβ), the server is typically some authority. | |
| Example: HTTPβserver hosts a website, clients make requests. | |
| Advantages: | |
| β’ Important logic is in a single place (the server) | |
| β’ Server controls access, permissions, etc. | |
| Disadvantages: | |
| β’ If server goes down, nothing works | |
| β’ No privacy (server sees everything) | |
| Contrast with p2p (peer to peer) where every host can process requests from every other host.""" | |
| }, | |
| # 6 | |
| { | |
| "question": "Communication protocol", | |
| "answer": """Protocol specifies how two devices communicate. Defines messages, headers, algorithms, error handling, sessions, data formatting, etc. | |
| Each layer has its own protocols.""" | |
| }, | |
| # 7 | |
| { | |
| "question": "Connection oriented transmission", | |
| "answer": """The host needs to make a reliable βconnectionβ first before it starts to communicate. This is a kind of βsessionβ, lasting until a connection is closed (manually, one of hosts goes offline, etc.). | |
| This mode requires a βlistenerβ socket which accepts connectionsβused for client-server comms. | |
| Implemented by TCP transport protocol.""" | |
| }, | |
| # 8 | |
| { | |
| "question": "Connectionless transmission mode", | |
| "answer": """No need to make a connection, just send the data to the destination (if a socket is created!). | |
| Natural for p2p communication but works with client-server too (e.g DNS). | |
| Implemented by UDP transport protocol.""" | |
| }, | |
| # 9 | |
| { | |
| "question": "DNS", | |
| "answer": """Domain Name System. The main purpose is to translate human-readable addresses (βdomainsβ) into IP addresses (A/AAAA records) but also stores additional data (MX, TXT, SRV records). | |
| Typically works on UDP port 53. There is also DNS over TLS/HTTPS (for improved security). | |
| Records: | |
| β’ host IN A 1.1.1.1 β maps host to IPv4 address | |
| β’ host IN AAAA 2a00:: β maps host to IPv6 address | |
| β’ alias IN CNAME domain β alias to domain | |
| β’ IN MX β mail exchange (mail server) | |
| β’ NS β name server for this domain""" | |
| }, | |
| # 10 | |
| { | |
| "question": "Elements of communication system", | |
| "answer": """β’ Nodes - send and receive data | |
| β’ Medium - the βspaceβ through which data is sent, e.g. cables/wires, EM field (radio waves for wireless) | |
| β’ Protocol - a way to encode data so it is efficiently transmitted and understood by all nodes""" | |
| }, | |
| # 11 | |
| { | |
| "question": "Ethernet", | |
| "answer": """Specifies physical and data-link layer for wired communication (IEEE 802.3). Uses 48-bit βMAC addressesβ to identify interfaces. | |
| Variants wrt speed: 10BASE-T (first), 100BASE-T (βFast Ethernetβ), 1GBASE-T, 10GBASE-T, 25GBASE-T, 50GBASE-T, 100GBASE-X. | |
| Autoconfigures speed, duplex/half-duplex. | |
| Features collision detection (CSMA/CD) in half-duplex.""" | |
| }, | |
| # 12 | |
| { | |
| "question": "Functions of communication protocols", | |
| "answer": """β’ Data formatting | |
| β’ Error detection and correction | |
| β’ Flow control | |
| β’ Congestion control | |
| β’ Session/connection management | |
| β’ Addressing | |
| β’ Security | |
| β’ Interoperability""" | |
| }, | |
| # 13 | |
| { | |
| "question": "ICMP", | |
| "answer": """Internet Control Message Protocol, used to send status/control messages between hosts. | |
| Example messages: | |
| β’ Echo request/Echo reply - used for ping | |
| β’ Error codes: host unreachable, redirect, ttl exceeded, etc.""" | |
| }, | |
| # 14 | |
| { | |
| "question": "IEEE 802.11 standards", | |
| "answer": """WiFi | |
| β’ 802.11a/h/n: 5GHz | |
| β’ 802.11b/g/h/n: 2.4GHz | |
| β’ ac, ax are newer/faster standards""" | |
| }, | |
| # 15 | |
| { | |
| "question": "IPv4 address", | |
| "answer": """32-bit address used in network/Internet layer. Written in 4 decimal βoctetsβ, e.g. 123.123.123.123. | |
| Netmasks, e.g. 1.1.1.0/24, are used for network ranges. First address (network) and last (broadcast) are special; usable IP range is in between (e.g. 254 hosts for /24). | |
| Classes: A (0.0.0.0-127.255.255.255), B (128.0.0.0-191.255.255.255), C (192.0.0.0-223.255.255.255) | |
| Special addresses: multicast, broadcast, 127.0.0.0/8 (loopback), 169.254.0.0/16 (link-local), 10.0.0.0/8 etc. (private)""" | |
| }, | |
| # 16 | |
| { | |
| "question": "IPv4 and IPv6 comparison", | |
| "answer": """IPv4: 32-bit address space, exhausted, more complex header, supports fragmentation, unicast/broadcast/multicast, assigned externally, notation: xxx.xxx.xxx.xxx | |
| IPv6: 128-bit address space, simpler header, never fragmented by routers, supports unicast/multicast/anycast, can be assigned automatically, notation: xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx""" | |
| }, | |
| # 17 | |
| { | |
| "question": "IPv4 protocol", | |
| "answer": """Used to address hosts in the entire network. IPv4 packet contains (not in order): | |
| β’ source IP address | |
| β’ destination IP address | |
| β’ transport protocol ID | |
| β’ stuff for fragmentation | |
| β’ TTL | |
| β’ flags | |
| β’ checksum | |
| β’ data | |
| Supports fragmentation if packet doesnβt fit MTU. Sequence index is used.""" | |
| }, | |
| # 18 | |
| { | |
| "question": "IPv6 address", | |
| "answer": """128 bit address, successor to IPv4. | |
| Notation: xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx (hexadecimal) | |
| β’ Zeros can be skipped using :: (only once) | |
| β’ Leading zeros can be skipped | |
| Assignment: split into network (64 bits) and host (64 bits); host part can be auto-assigned (SLAAC). | |
| Special addresses: | |
| β’ :: - indefinite | |
| β’ ::1 - loopback | |
| β’ ff00::/8 - multicast | |
| β’ fe80::/10 - link-local | |
| β’ fec0::/10 - site-local""" | |
| }, | |
| # 19 | |
| { | |
| "question": "IPv6 protocol", | |
| "answer": """Header is simpler than IPv4: | |
| β’ source address | |
| β’ destination address | |
| β’ priority | |
| β’ TTL | |
| β’ flags | |
| β’ next header | |
| β’ data | |
| No fragmentation, no checksum. Extensions use βnext headerβ field.""" | |
| }, | |
| # 20 | |
| { | |
| "question": "LAN", | |
| "answer": """Local Area Network. Used within a single organization or household. Typically uses private IP addresses. Typical layer 2 protocols: Ethernet, Wi-Fi.""" | |
| }, | |
| # 21 | |
| { | |
| "question": "MAC address", | |
| "answer": """48 bit physical address. Used in data link layer (e.g. Ethernet). First 3 bytes identify manufacturer. Written as aa:bb:cc:dd:ee:ff | |
| Special: 00:00:00:00:00:00 (null), ff:ff:ff:ff:ff:ff (broadcast)""" | |
| }, | |
| # 22 | |
| { | |
| "question": "MAN", | |
| "answer": """Metropolitan Area Network. Typical range: a city. E.g. a research network connecting multiple LANs in a city.""" | |
| }, | |
| # 23 | |
| { | |
| "question": "Multilayer transmission in computer networks", | |
| "answer": """Layers separate responsibilities (abstraction), make protocol changes easier. Each layer serves a function and communicates only with adjacent layers. | |
| Changing a protocol in a layer (e.g. IPv6 vs IPv4) can cause compatibility issues. | |
| Protocols are stacked: Ethernet-IPv4-TCP-HTTP, WiFi-IPv6-UDP-DNS, etc.""" | |
| }, | |
| # 24 | |
| { | |
| "question": "NAT", | |
| "answer": """Network Address Translation. Used to translate addresses between networks. | |
| Allows Internet access for computers with private addresses. Improves security and conserves public IPs. | |
| β’ Source NAT - router translates private IPs into external address for outbound packets, uses TCP/UDP ports and a translation table | |
| β’ Destination NAT - router translates incoming messages to internal IP+port (port forwarding)""" | |
| }, | |
| # 25 | |
| { | |
| "question": "Network topology", | |
| "answer": """Defines how nodes are connected (logically) in a network. | |
| β’ Star - central node (switch), most common for LANs | |
| β’ Tree - nested star, for big LANs | |
| β’ Partial mesh - topology of public Internet (WAN), provides redundancy | |
| β’ Mesh - everyone connected to everyone (unusual for wired) | |
| β’ Bus - all devices connected to a single cable | |
| β’ Ring - computers connected in a ring""" | |
| }, | |
| # 26 | |
| { | |
| "question": "Networks classification (range of transmission)", | |
| "answer": """β’ BAN (bodynet), PAN (personal), NAN (near-me), LAN (local), CAN (campus), MAN (metropolitan), WAN (wide) | |
| Lower range networks use lower range mediums. | |
| LAN for resource sharing, MANs mostly research, WAN is large area (mostly routers).""" | |
| }, | |
| # 27 | |
| { | |
| "question": "Ports in transport layer", | |
| "answer": """Ports specify to which application the data should be sent on a host. | |
| Allows hosting multiple services on one server, or multiple clients. | |
| Ports are 16-bit numbers (1-65535) for both TCP and UDP. 1-1024 are βwell known portsβ. | |
| When sending, destination port is provided, source port is randomized by OS.""" | |
| }, | |
| # 28 | |
| { | |
| "question": "Router β functions, structure", | |
| "answer": """Routers select routes between networks (layer 3). Use routing tables (static/manual or dynamic). | |
| Main tasks: | |
| β’ Forwarding packets | |
| β’ Maintaining/generating routing tables (BGP, OSPF, RIP) | |
| Additional tasks: filtering (firewall), NAT, switching, DHCP, DNS, etc.""" | |
| }, | |
| # 29 | |
| { | |
| "question": "Routing protocols β examples", | |
| "answer": """Interior (internal to AS): RIP, OSPF, IS-IS | |
| Exterior (between AS): EGP (old), BGP (current)""" | |
| }, | |
| # 30 | |
| { | |
| "question": "Routing protocols β classification", | |
| "answer": """β’ Interior/Exterior | |
| β’ Algorithm: | |
| - Distance vector: each router shares routing table with neighbors (RIP) | |
| - Link-state: each router builds a connectivity map for the entire network (OSPF, IS-IS)""" | |
| }, | |
| # 31 | |
| { | |
| "question": "Socket β definition, applications", | |
| "answer": """Endpoint in operating systems for communication (send/receive data). Identified by IP + port. | |
| Stores protocol state (connected? listening? etc.). | |
| Examples: HTTP server socket 1.1.1.1:80; client creates a TCP socket at random port, connects to server. UDP: server binds 1.1.1.1:53, client sends from random port.""" | |
| }, | |
| # 32 | |
| { | |
| "question": "Switch β functions, applications, structure", | |
| "answer": """Physical device for extending IP networks without collisions (unlike hubs). Operates at data link layer. | |
| Remembers MAC addresses on its ports (MAC table), passes frames only to relevant ports. | |
| Professional switches: VLAN, STP, stacking, routing, etc.""" | |
| }, | |
| # 33 | |
| { | |
| "question": "TCP and UDP comparison", | |
| "answer": """TCP: | |
| β’ Requires connection | |
| β’ Ensures all data arrives in order | |
| β’ Streaming (app layer sees stream of data) | |
| β’ Complex header (retransmission) | |
| β’ Complex implementation (for reliability) | |
| UDP: | |
| β’ Connectionless | |
| β’ No guarantee of order or arrival | |
| β’ App layer sees discrete datagrams | |
| β’ Simple header | |
| Both: | |
| β’ Include a checksum (data arrives, it is correct)""" | |
| }, | |
| # 34 | |
| { | |
| "question": "TCP/IP layers and their functions", | |
| "answer": """β’ Physical: data encoding, communication within a network (Ethernet, WiFi, Bluetooth, USB) | |
| β’ Internet: routing, comm between networks, logical addressing (IPv4, IPv6) | |
| β’ Transport: data integrity/reliability, connection management (TCP, UDP) | |
| β’ Application: app-specific protocols (HTTP, FTP, SSH, etc)""" | |
| }, | |
| # 35 | |
| { | |
| "question": "TCP/IP stack of protocols β layers, exemplary protocols", | |
| "answer": """Physical: Ethernet, WiFi, Bluetooth, USB | |
| Internet: IPv4, IPv6 | |
| Transport: TCP, UDP | |
| Application: HTTP, FTP, SSH, many others""" | |
| }, | |
| # 36 | |
| { | |
| "question": "Wired media β types, features", | |
| "answer": """Cable structure: | |
| β’ Coaxial cables - single copper wire with insulation/shielding (old, still used) | |
| β’ Twisted pair cables - copper strands in pairs, 8P8C connectors, various shielding, used in LANs | |
| β’ Categories: 5e-1G, 6-10G, 7, 8-40Gbps | |
| β’ Optical fiber - uses light (infrared), low latency, no EM interference, long range (single/multi mode, various connectors)""" | |
| }, | |
| # 37 | |
| { | |
| "question": "Wireless and wired media comparison", | |
| "answer": """Wireless: | |
| β’ Easier and faster to deploy (no cables) | |
| β’ Good for ad-hoc networks | |
| β’ Low speed and reliability (interference) | |
| β’ High latency | |
| β’ Lower security | |
| Wired: | |
| β’ Requires cables | |
| β’ Good for permanent networks | |
| β’ Higher speed/reliability, low latency, higher security""" | |
| }, | |
| # 38 | |
| { | |
| "question": "Wireless media β applications, bands, features", | |
| "answer": """Applications: | |
| β’ Temporary networks (portable devices, personal area, public hotspots, satellite, IoT) | |
| Bands: | |
| β’ Wi-Fi has 11-14 channels around 2.4 GHz, more at 5 GHz | |
| β’ Also longer wavelength for satellite comms | |
| Features: | |
| β’ Short range (Wi-Fi), longer for satellite, prone to interference""" | |
| }, | |
| # 39 | |
| { | |
| "question": "Wireless transmission β exemplary protocols", | |
| "answer": """β’ WiFi (802.11) | |
| β’ Bluetooth | |
| β’ ZigBee | |
| β’ Mobile: GSM, LTE, 5G | |
| β’ Satellite: DVB-S""" | |
| }, | |
| # 40 | |
| { | |
| "question": "Wireless transmission characterization", | |
| "answer": """Range, bandwidth, interference, security.""" | |
| } | |
| ] | |
| def get_current_card(self) -> Dict[str, str]: | |
| qidx = self.exam_questions[self.current_index] | |
| return self.flashcards[qidx] | |
| def show_question(self): | |
| card = self.get_current_card() | |
| answer_to_show = self.last_answer if self.last_answer else "" | |
| return ( | |
| card["question"], | |
| answer_to_show, | |
| gr.update(visible=True), | |
| gr.update(visible=False), | |
| gr.update(visible=False), | |
| self.get_stats(), | |
| gr.update(visible=False), | |
| self.get_pass_probability() | |
| ) | |
| def show_answer(self): | |
| card = self.get_current_card() | |
| return ( | |
| card["question"], | |
| card["answer"], | |
| gr.update(visible=False), | |
| gr.update(visible=True), | |
| gr.update(visible=True), | |
| self.get_stats(), | |
| gr.update(visible=True), | |
| self.get_pass_probability() | |
| ) | |
| def handle_yes(self, score): | |
| qidx = self.exam_questions[self.current_index] | |
| self.answered_yes.add(qidx) | |
| self.answered[qidx] = int(score) | |
| self.last_answer = self.flashcards[qidx]["answer"] | |
| if qidx in self.answered_no: | |
| self.answered_no.remove(qidx) | |
| return self.goto_next() | |
| def handle_no(self, score): | |
| qidx = self.exam_questions[self.current_index] | |
| self.answered_no.add(qidx) | |
| self.answered[qidx] = int(score) | |
| self.last_answer = self.flashcards[qidx]["answer"] | |
| if qidx in self.answered_yes: | |
| self.answered_yes.remove(qidx) | |
| return self.goto_next() | |
| def goto_next(self): | |
| n = len(self.exam_questions) | |
| for _ in range(n): | |
| self.current_index = (self.current_index + 1) % n | |
| qidx = self.exam_questions[self.current_index] | |
| if qidx not in self.answered: | |
| return self.show_question() | |
| return self.show_summary() | |
| def show_summary(self): | |
| total = sum(self.answered.get(qidx, 0) for qidx in self.exam_questions) | |
| correct = len(self.answered_yes) | |
| wrong = len(self.answered_no) | |
| details = "\n\n".join([ | |
| f"**Q{i+1}: {self.flashcards[q]['question']}**\n" | |
| f"**A:** {self.flashcards[q]['answer']}\n" | |
| f"**Score:** {self.answered.get(q,0)}/3" | |
| for i, q in enumerate(self.exam_questions) | |
| ]) | |
| status = "β You PASSED!" if total >= PASS_POINTS else "β You did NOT pass." | |
| summary = ( | |
| f"**Your Score:** {total}/24\n" | |
| f"**Result:** {status}\n" | |
| f"β Remembered: {correct} | β Not remembered: {wrong}\n\n" | |
| f"**Full breakdown:**\n\n{details}" | |
| ) | |
| return ("Exam Finished!", summary, gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), summary, gr.update(visible=False), self.get_pass_probability()) | |
| def get_stats(self): | |
| total = sum(self.answered.get(qidx, 0) for qidx in self.exam_questions) | |
| correct = len(self.answered_yes) | |
| wrong = len(self.answered_no) | |
| return ( | |
| f"β Remembered: {correct} | β Not remembered: {wrong} | " | |
| f"π― Your Score: {total}/24 | " | |
| f"Question {len(self.answered)+1} of {NUM_EXAM_QUESTIONS}" | |
| ) | |
| def get_pass_probability(self): | |
| if len(self.answered) == NUM_EXAM_QUESTIONS: | |
| total = sum(self.answered.get(qidx, 0) for qidx in self.exam_questions) | |
| return f"π’ Probability to pass: {'100%' if total >= PASS_POINTS else '0%'}" | |
| current_score = sum(self.answered.get(qidx, 0) for qidx in self.exam_questions) | |
| remaining = NUM_EXAM_QUESTIONS - len(self.answered) | |
| ways = 0 | |
| passing_ways = 0 | |
| def dfs(depth, acc): | |
| nonlocal ways, passing_ways | |
| if depth == 0: | |
| ways += 1 | |
| if acc + current_score >= PASS_POINTS: | |
| passing_ways += 1 | |
| return | |
| for s in range(0, MAX_QUESTION_SCORE + 1): | |
| dfs(depth-1, acc+s) | |
| dfs(remaining, 0) | |
| prob = (passing_ways / ways) * 100 if ways > 0 else 0 | |
| return f"π’ Probability to pass (based on possible scores): {prob:.1f}%" | |
| def reset_exam(self): | |
| self.reset() | |
| return self.show_question() | |
| # Instantiate app | |
| app = ExamPrepApp() | |
| with gr.Blocks(title="Network Exam Simulator", theme=gr.themes.Soft()) as demo: | |
| gr.Markdown("# π Computer Networks Final Exam Simulator") | |
| gr.Markdown(""" | |
| - **Pattern:** 8 open questions randomly drawn from the official list. | |
| - **Scoring:** 0-3 points per question. Passing = 13 points or more.<br> | |
| - Mark yourself for each answer and track your passing probability live! | |
| """) | |
| with gr.Row(): | |
| with gr.Column(scale=3): | |
| question = gr.Textbox(label="β Question", interactive=False, lines=3) | |
| answer = gr.Textbox(label="π‘ Answer (for previous question)", interactive=False, visible=True, lines=8) | |
| with gr.Row(): | |
| show_answer_btn = gr.Button("π Show Answer", variant="primary") | |
| yes_btn = gr.Button("β I remember this", visible=False) | |
| no_btn = gr.Button("β I don't remember", visible=False) | |
| with gr.Row(): | |
| score_input = gr.Radio(choices=[0,1,2,3], value=0, label="How many points would you get for this question?", interactive=True, visible=False) | |
| with gr.Column(scale=1): | |
| stats = gr.Markdown(app.get_stats()) | |
| prob = gr.Markdown(app.get_pass_probability()) | |
| reset_btn = gr.Button("β»οΈ Start New Exam", variant="stop") | |
| show_answer_btn.click( | |
| fn=app.show_answer, | |
| outputs=[question, answer, show_answer_btn, yes_btn, no_btn, stats, score_input, prob] | |
| ) | |
| yes_btn.click( | |
| fn=app.handle_yes, | |
| inputs=[score_input], | |
| outputs=[question, answer, show_answer_btn, yes_btn, no_btn, stats, score_input, prob] | |
| ) | |
| no_btn.click( | |
| fn=app.handle_no, | |
| inputs=[score_input], | |
| outputs=[question, answer, show_answer_btn, yes_btn, no_btn, stats, score_input, prob] | |
| ) | |
| reset_btn.click( | |
| fn=app.reset_exam, | |
| outputs=[question, answer, show_answer_btn, yes_btn, no_btn, stats, score_input, prob] | |
| ) | |
| demo.load( | |
| fn=app.show_question, | |
| outputs=[question, answer, show_answer_btn, yes_btn, no_btn, stats, score_input, prob] | |
| ) | |
| if __name__ == "__main__": | |
| demo.launch() | |