Benchmark Information
A comprehensive multiple choice benchmark testing programming knowledge across various languages and difficulty levels. Questions range from basic syntax to advanced algorithmic concepts, covering Python, JavaScript, Java, C++, Go, SQL, and more. Each question has 6 options (A-F) with one correct answer.
Category:
Coding
Visibility:
PUBLIC
Max Completion Tokens:
20000
Max Retries:
1
Created:
Updated:
Input Tokens:
33255
Est. Output Tokens:
9500
System Prompt
You are taking a programming knowledge test. For each question, you will be given 6 options labeled A through F. Analyze the code or question carefully and respond with ONLY the single letter (A, B, C, D, E, or F) corresponding to the correct answer. Do not include any explanation in the answer, just the letter.
Validation Rules
Correct Option Letter
Exact Match Flex
JSON Path
$.answer
Benchmark Steps
# | User Prompt | Correct Option Letter |
---|---|---|
1 | What will this Python code print? ```python x = [1, 2, 3] y = x y.append(4) print(len(x)) ``` A) 3 B) 4 C) Error D) 0 E) 1 F) None |
B |
2 | In Git, which command undoes the last commit but keeps changes in working directory? A) git reset --hard HEAD~1 B) git reset --soft HEAD~1 C) git revert HEAD D) git checkout HEAD~1 E) git stash F) git clean -f |
B |
3 | What is the space complexity of merge sort? A) O(1) B) O(log n) C) O(n) D) O(n log n) E) O(n²) F) O(2^n) |
C |
4 | In JavaScript, what will [1, 2, 3].map(x => x * 2).filter(x => x > 3) return? A) [4, 6] B) [2, 4, 6] C) [2, 3] D) [1, 2, 3] E) [6] F) [] |
A |
5 | Which design pattern ensures a class has only one instance? A) Factory B) Observer C) Strategy D) Singleton E) Adapter F) Decorator |
D |
6 | In C, what is the size of a pointer on a 64-bit system? A) 4 bytes B) 8 bytes C) 16 bytes D) 32 bytes E) 64 bytes F) Depends on data type |
B |
7 | Which sorting algorithm has the best average case time complexity? A) Bubble Sort B) Selection Sort C) Insertion Sort D) Merge Sort E) Bogo Sort F) All have same complexity |
D |
8 | In React, which hook is used for side effects? A) useState B) useContext C) useEffect D) useReducer E) useMemo F) useCallback |
C |
9 | In Go, what is the zero value of a string? A) nil B) "0" C) "" D) null E) undefined F) false |
C |
10 | What is the output of this Java code? ```java String s1 = "Hello"; String s2 = new String("Hello"); System.out.println(s1 == s2); ``` A) true B) false C) null D) Error E) Hello F) undefined |
B |
11 | Consider the following pseudo-code with two threads running in parallel on a system without any explicit synchronization (no locks or memory barriers). Both x and y are shared integers initially 0. Both a and b are booleans initially false: // Initial state: x = 0, y = 0, a = false, b = false. Thread 1: x = 1; a = (y == 0); Thread 2: y = 1; b = (x == 0); // After both threads complete, we consider the output pair (a, b). Assume a sequentially consistent memory model (operations from each thread occur in program order globally). Which of the following outcomes for the printed pair (a, b) is impossible under sequential consistency? A. (false, false) B. (false, true) C. (true, false) D. (true, true) E. All four combinations of (a, b) are possible under sequential consistency. F. The program’s outcome will be the same on every run (deterministic under sequential consistency). |
D |
12 | What is the purpose of the 'volatile' keyword in Java? A) Makes variable immutable B) Ensures visibility across threads C) Allocates on stack D) Prevents garbage collection E) Makes method synchronized F) Enables lazy initialization |
B |
13 | In binary search tree, what is the time complexity of search in worst case? A) O(1) B) O(log n) C) O(n) D) O(n log n) E) O(n²) F) O(2^n) |
C |
14 | Large table Logs(ts timestamptz, user_id int, level int, message text) (≈ 4 billion rows, uniformly distributed over four years.) Two production queries run thousands of times per hour: -- Q1: recent events for one user, latency critical SELECT * FROM Logs WHERE user_id = 947 AND ts >= now() - INTERVAL '30 minutes' ORDER BY ts DESC LIMIT 200; -- Q2: monthly report, throughput oriented SELECT user_id, COUNT(*) AS hits FROM Logs WHERE ts BETWEEN '2025-01-01' AND '2025-01-31' GROUP BY user_id ORDER BY hits DESC LIMIT 50; Assume: user_id has high selectivity (≈ 1 million distinct IDs). In any 30-min slice, a single user has at most 5 000 rows. January 2025 contains ≈ 90 million rows total. Which single new B-tree index (other than the existing PK) yields the lowest combined cost for both queries on PostgreSQL 16? A. CREATE INDEX ON Logs (user_id, ts DESC) INCLUDE (level, message); B. CREATE INDEX ON Logs (ts DESC, user_id) INCLUDE (level, message); C. CREATE INDEX ON Logs (user_id) INCLUDE (ts, level, message); D. CREATE INDEX ON Logs (ts) INCLUDE (user_id, level, message); E. CREATE INDEX ON Logs (user_id, ts DESC, level) WHERE level = 3; F. CREATE INDEX ON Logs (ts DESC) WHERE ts >= now() - INTERVAL '1 day'; |
B |
15 | In Python, what does 'yield' keyword create? A) List B) Tuple C) Dictionary D) Generator E) Set F) Class |
D |
16 | In JavaScript, what is the result of: [] + []? A) [] B) 0 C) "" D) null E) undefined F) Error |
C |
17 | Which is NOT a principle of SOLID? A) Single Responsibility B) Open/Closed C) Liskov Substitution D) Interface Segregation E) Dependency Inversion F) Don't Repeat Yourself |
F |
18 | A cluster of 5 nodes is running the Raft consensus algorithm for a replicated log. Initially, all nodes have log entries committed up to index k. Node A is the leader in term T and appends a new log entry X at index k+1. Before A can replicate entry X to a majority, a network partition occurs. A and one other follower (2 nodes) are isolated in one partition, while the other 3 nodes form a second partition. In the partition with 3 nodes, a new leader B is elected in term T+1. Leader B does not have entry X (which was never fully replicated) and instead appends a different new entry Y at index k+1. Entry Y is replicated to the majority in B’s partition and becomes committed at index k+1 (in term T+1). Eventually, the network partition heals and all 5 nodes synchronize their logs. According to Raft’s log consistency and conflict resolution rules, what will be the state of the log at index k+1 across the entire cluster once the system stabilizes? A. All nodes preserve entry X at index k+1 because it was the first value proposed for that index. B. All nodes end up with entry Y at index k+1, as the new leader’s committed entry overwrites the old leader’s uncommitted entry X. C. Nodes in A’s partition keep X at index k+1 while nodes in B’s partition have Y at k+1, resulting in a permanent inconsistency. D. Both entries X and Y remain at index k+1 on different nodes (violating Raft’s consistency guarantees). E. Node A (the old leader) will assign Y a new index (e.g. k+2) upon reconnection, so X stays at k+1 on A and Y is at k+2 on others. F. Index k+1 will be blank on the former leader A’s log after conflict resolution, since two different entries were proposed for that slot. |
B |
19 | PostgreSQL 16 Schema: CREATE TABLE Products( product_id int PRIMARY KEY, name text ); CREATE TABLE Sales( sale_id bigint PRIMARY KEY, product_id int REFERENCES Products, sale_date timestamptz NOT NULL, amount numeric NOT NULL ); -- Composite covering index, descending order, plus included column CREATE INDEX idx_sales_pid_date_sid ON Sales (product_id, sale_date DESC, sale_id DESC) INCLUDE (amount); Task: For every product, return exactly one row representing its latest sale. If several sales share the same sale_date, pick the row with the greatest sale_id. The query must execute as an Index-Only Scan on idx_sales_pid_date_sid (no heap lookup) and must include products with no sales (yielding NULLs). Which query satisfies all requirements? A) SELECT p.product_id, p.name, s.sale_date, s.sale_id, s.amount FROM Products p LEFT JOIN LATERAL ( SELECT sale_date, sale_id, amount FROM Sales WHERE product_id = p.product_id ORDER BY sale_date DESC LIMIT 1 ) s ON true; B) SELECT p.product_id, p.name, s.sale_date, s.sale_id, s.amount FROM Products p LEFT JOIN LATERAL ( SELECT DISTINCT ON (sale_date) * FROM Sales WHERE product_id = p.product_id ORDER BY sale_date DESC, sale_id DESC LIMIT 1 ) s ON true; C) SELECT p., s. FROM Products p LEFT JOIN ( SELECT DISTINCT ON (product_id) * FROM Sales ORDER BY product_id, sale_date DESC, sale_id DESC ) s USING (product_id); D) SELECT p.product_id, p.name, (SELECT sale_date FROM Sales WHERE product_id = p.product_id ORDER BY sale_date DESC, sale_id DESC LIMIT 1) AS sale_date, (SELECT sale_id FROM Sales WHERE product_id = p.product_id ORDER BY sale_date DESC, sale_id DESC LIMIT 1) AS sale_id, (SELECT amount FROM Sales WHERE product_id = p.product_id ORDER BY sale_date DESC, sale_id DESC LIMIT 1) AS amount FROM Products p; E) SELECT p.product_id, p.name, s.sale_date, s.sale_id, s.amount FROM Products p LEFT JOIN LATERAL ( SELECT sale_date, sale_id, amount FROM Sales WHERE product_id = p.product_id ORDER BY sale_date, sale_id -- ascending! LIMIT 1 ) s ON true; F) SELECT p.product_id, p.name, s.sale_date, s.sale_id, s.amount FROM Products p LEFT JOIN LATERAL ( SELECT sale_date, sale_id, amount FROM Sales ORDER BY sale_date DESC, sale_id DESC LIMIT 1 ) s ON p.product_id = s.product_id; |
C |
20 | In C++, what is the output of: sizeof(char)? A) 0 B) 1 C) 2 D) 4 E) 8 F) Compiler dependent |
B |
21 | You start a session on MySQL 8.0.36 and run: SET SESSION cte_max_recursion_depth = 250; WITH RECURSIVE seq AS ( SELECT 1 AS n UNION ALL SELECT n + 1 FROM seq ) SELECT /*+ SET_VAR(cte_max_recursion_depth = 400) */ COUNT(*) AS c FROM seq WHERE n <= 350; No other settings are changed. What is returned to the client? A. Error 3573 – “Recursive query aborted after reaching limit of 250 recursion levels.” B. A single row with c = 350. C. Error 3573 after 251 iterations, because the hint is ignored inside a CTE. D. Error 3573 – the query reaches level 401 and exceeds the 400-level hint. E. The query runs forever because WHERE n <= 350 is pushed after recursion. F. A single row with c = 400 (the engine materialises 400 rows, then applies the WHERE). |
B |
22 | Which HTTP method is idempotent but NOT safe? A) GET B) POST C) PUT D) HEAD E) OPTIONS F) CONNECT |
C |
23 | In Python, what is the output of: type(lambda x: x)? A) <class 'function'> B) <class 'lambda'> C) <class 'object'> D) <class 'type'> E) <class 'NoneType'> F) Error |
A |
24 | What is the worst-case time complexity of quicksort? A) O(n) B) O(n log n) C) O(n²) D) O(log n) E) O(1) F) O(2^n) |
C |
25 | In JavaScript, what is the value of: typeof null? A) null B) undefined C) object D) string E) number F) boolean |
C |
26 | For the given schema which SQL statement satisfies this requirement: Find the top 3 most cost-effective transport routes for shipments originating from 'Warehouse A'. A route is defined by the sequence of carriers used (e.g., 'AirExpress->SeaLink'). Cost-effectiveness is measured by the lowest average 'cost per kilometer', which is calculated as total_shipment_cost / total_distance_km. This 'cost per kilometer' for a shipment must only be calculated and included in the average if the shipment did not have any 'compliance_failed' audits AND if all vehicles used for its legs had a maintenance_status of 'OK' at the time of each leg's departure. The final average should only consider routes used by at least 5 unique shipments. Return the route and its average cost per kilometer. Schema: Table Name Column Name Data Type Constraints Notes employees employee_id INTEGER PRIMARY KEY Unique identifier for each employee. name VARCHAR(100) Employee's full name. division VARCHAR(50) The division the employee belongs to (e.g., 'Logistics', 'Finance'). salary DECIMAL(10, 2) Annual salary. manager_id INTEGER FOREIGN KEY (manager_id) REFERENCES employees(employee_id) Self-referencing key for the organizational hierarchy. NULL for top-level heads. shipments shipment_id INTEGER PRIMARY KEY Unique identifier for a shipment. origin VARCHAR(100) Starting location of the entire shipment. destination VARCHAR(100) Final destination of the shipment. status VARCHAR(20) e.g., 'in_transit', 'delivered', 'delayed'. shipment_type VARCHAR(20) e.g., 'standard', 'express', 'high_value'. handler_employee_id INTEGER FOREIGN KEY (handler_employee_id) REFERENCES employees(employee_id) The primary employee responsible for the shipment. shipment_legs leg_id INTEGER PRIMARY KEY Unique identifier for a segment of a shipment. shipment_id INTEGER FOREIGN KEY (shipment_id) REFERENCES shipments(shipment_id) Links the leg to a specific shipment. leg_sequence INTEGER The order of this leg in the shipment's journey (1, 2, 3...). carrier_id INTEGER FOREIGN KEY (carrier_id) REFERENCES carriers(carrier_id) The carrier responsible for this leg. vehicle_id INTEGER FOREIGN KEY (vehicle_id) REFERENCES vehicles(vehicle_id) The specific vehicle used for this leg. actual_departure TIMESTAMP The actual departure time for this leg. Forms the start of a valid-time period. actual_arrival TIMESTAMP The actual arrival time for this leg. Forms the end of a valid-time period. carriers carrier_id INTEGER PRIMARY KEY Unique identifier for a transport carrier. carrier_name VARCHAR(100) Name of the carrier (e.g., 'SeaLink', 'AirExpress'). vehicles vehicle_id INTEGER PRIMARY KEY Unique identifier for a vehicle. vehicle_type VARCHAR(50) e.g., 'Truck', 'Cargo Ship', 'Airplane'. maintenance_status VARCHAR(20) e.g., 'OK', 'needs_service', 'out_of_service'. contracts contract_id INTEGER PRIMARY KEY Unique identifier for a contract. region VARCHAR(50) Geographic region for the contract. priority_level INTEGER Priority level (1-5). total_value DECIMAL(12, 2) The total monetary value of the contract. status VARCHAR(20) e.g., 'active', 'expired', 'pending'. valid_from DATETIME2 GENERATED ALWAYS AS ROW START Start of the row's validity period (transaction-time). valid_to DATETIME2 GENERATED ALWAYS AS ROW END End of the row's validity period (transaction-time). PERIOD FOR SYSTEM_TIME (valid_from, valid_to) Defines this as a system-versioned temporal table. audits audit_id INTEGER PRIMARY KEY Unique identifier for an audit event. entity_id INTEGER ID of the entity being audited. entity_type VARCHAR(20) Type of entity: 'shipment', 'contract', 'vehicle'. audit_type VARCHAR(50) e.g., 'compliance_failed', 'security_check', 'routine_inspection'. audit_timestamp TIMESTAMP When the audit was conducted. notes TEXT Free-text notes from the audit. A: SELECT c.carrier_name AS route, AVG(s.total_shipment_cost / s.total_distance_km) AS avg_cost_per_km FROM shipments s JOIN shipment_legs sl ON s.shipment_id = sl.shipment_id JOIN carriers c ON sl.carrier_id = c.carrier_id WHERE s.origin = 'Warehouse A' AND NOT EXISTS (SELECT 1 FROM audits a WHERE a.entity_id = s.shipment_id AND a.audit_type = 'compliance_failed') AND NOT EXISTS (SELECT 1 FROM vehicles v JOIN shipment_legs sl2 ON v.vehicle_id = sl2.vehicle_id WHERE sl2.shipment_id = s.shipment_id AND v.maintenance_status!= 'OK') GROUP BY c.carrier_name HAVING COUNT(DISTINCT s.shipment_id) >= 5 ORDER BY avg_cost_per_km ASC LIMIT 3; B: SELECT STRING_AGG(c.carrier_name, '->' ORDER BY sl.leg_sequence) AS route, AVG(s.total_shipment_cost / s.total_distance_km) AS avg_cost_per_km FROM shipments s JOIN shipment_legs sl ON s.shipment_id = sl.shipment_id JOIN carriers c ON sl.carrier_id = c.carrier_id JOIN vehicles v ON sl.vehicle_id = v.vehicle_id LEFT JOIN audits a ON s.shipment_id = a.entity_id AND a.entity_type = 'shipment' WHERE s.origin = 'Warehouse A' AND v.maintenance_status = 'OK' AND (a.audit_type!= 'compliance_failed' OR a.audit_id IS NULL) GROUP BY s.shipment_id HAVING COUNT(DISTINCT s.shipment_id) >= 5 ORDER BY avg_cost_per_km ASC LIMIT 3; C: WITH qualified_shipments AS ( SELECT s.shipment_id, s.total_shipment_cost, s.total_distance_km FROM shipments s WHERE s.origin = 'Warehouse A' ) SELECT STRING_AGG(c.carrier_name, '->' ORDER BY sl.leg_sequence) AS route, AVG(CASE WHEN a.audit_type!= 'compliance_failed' AND v.maintenance_status = 'OK' THEN qs.total_shipment_cost / qs.total_distance_km ELSE NULL END) AS avg_cost_per_km FROM qualified_shipments qs JOIN shipment_legs sl ON qs.shipment_id = sl.shipment_id JOIN carriers c ON sl.carrier_id = c.carrier_id JOIN vehicles v ON sl.vehicle_id = v.vehicle_id LEFT JOIN audits a ON qs.shipment_id = a.entity_id GROUP BY route HAVING COUNT(DISTINCT qs.shipment_id) >= 5 ORDER BY avg_cost_per_km ASC LIMIT 3; D: SELECT STRING_AGG(c.carrier_name, '->' ORDER BY sl.leg_sequence) AS route, AVG(s.total_shipment_cost / s.total_distance_km) AS avg_cost_per_km FROM shipments s JOIN shipment_legs sl ON s.shipment_id = sl.shipment_id JOIN carriers c ON sl.carrier_id = c.carrier_id JOIN vehicles v ON sl.vehicle_id = v.vehicle_id WHERE s.origin = 'Warehouse A' AND v.maintenance_status = 'OK' AND s.shipment_id NOT IN (SELECT entity_id FROM audits WHERE audit_type = 'compliance_failed') GROUP BY route HAVING COUNT(DISTINCT s.shipment_id) >= 5 ORDER BY avg_cost_per_km ASC LIMIT 3; E: WITH route_details AS ( SELECT s.shipment_id, s.total_shipment_cost, s.total_distance_km, STRING_AGG(c.carrier_name, '->' ORDER BY sl.leg_sequence) AS route FROM shipments s JOIN shipment_legs sl ON s.shipment_id = sl.shipment_id JOIN carriers c ON sl.carrier_id = c.carrier_id WHERE s.origin = 'Warehouse A' GROUP BY s.shipment_id, s.total_shipment_cost, s.total_distance_km ) SELECT route, SUM(total_shipment_cost) / SUM(total_distance_km) AS avg_cost_per_km FROM route_details GROUP BY route HAVING COUNT(DISTINCT shipment_id) >= 5 ORDER BY avg_cost_per_km ASC LIMIT 3; F: WITH valid_shipments AS ( SELECT s.shipment_id FROM shipments s WHERE s.origin = 'Warehouse A' AND NOT EXISTS ( SELECT 1 FROM audits a WHERE a.entity_id = s.shipment_id AND a.entity_type = 'shipment' AND a.audit_type = 'compliance_failed' ) AND NOT EXISTS ( SELECT 1 FROM shipment_legs sl JOIN vehicles v ON sl.vehicle_id = v.vehicle_id WHERE sl.shipment_id = s.shipment_id AND v.maintenance_status!= 'OK' ) ), route_details AS ( SELECT s.shipment_id, s.total_shipment_cost, s.total_distance_km, STRING_AGG(c.carrier_name, '->' ORDER BY sl.leg_sequence) AS route FROM shipments s JOIN shipment_legs sl ON s.shipment_id = sl.shipment_id JOIN carriers c ON sl.carrier_id = c.carrier_id WHERE s.shipment_id IN (SELECT shipment_id FROM valid_shipments) GROUP BY s.shipment_id, s.total_shipment_cost, s.total_distance_km ) SELECT route, AVG(total_shipment_cost / total_distance_km) AS avg_cost_per_km FROM route_details GROUP BY route HAVING COUNT(DISTINCT shipment_id) >= 5 ORDER BY avg_cost_per_km ASC LIMIT 3; |
F |
27 | What is the output of this Python code? ```python x = [1, 2, 3] print(x[-1]) ``` A) 1 B) 2 C) 3 D) -1 E) Error F) None |
C |
28 | In OOP, what is encapsulation? A) Inheritance of properties B) Multiple inheritance C) Data hiding D) Method overloading E) Polymorphism F) Abstraction |
C |
29 | In JavaScript, which statement creates a block scope variable? A) var B) let C) const D) Both B and C E) All of above F) None of above |
D |
30 | What is the purpose of a semaphore in concurrent programming? A) Memory allocation B) Synchronization C) Compilation D) Garbage collection E) Exception handling F) Type checking |
B |
31 | Which algorithm is used for finding shortest path in a graph? A) DFS B) BFS C) Dijkstra's D) Bubble Sort E) Binary Search F) Linear Search |
C |
32 | What does API stand for? A) Advanced Programming Interface B) Application Programming Interface C) Automated Programming Interface D) Abstract Programming Interface E) Asynchronous Programming Interface F) Active Programming Interface |
B |
33 | In C++, what is the difference between struct and class by default? A) Inheritance type B) Memory allocation C) Access level D) No difference E) Performance F) Compilation time |
C |
34 | In Python, what does the 'pass' statement do? A) Skips iteration B) Exits function C) Does nothing D) Raises error E) Returns None F) Continues loop |
C |
35 | What is the time complexity of binary search? A) O(1) B) O(log n) C) O(n) D) O(n log n) E) O(n²) F) O(2^n) |
B |
36 | In Linux, what does chmod 777 do? A) Deletes file B) Creates file C) Full permissions to all D) No permissions E) Read only F) Write only |
C |
37 | What is the output of: 10 % 3 in most programming languages? A) 3 B) 1 C) 3.33 D) 0 E) 10 F) Error |
B |
38 | In JavaScript, what is a closure? A) End of function B) Function with access to outer scope C) Private variable D) Loop construct E) Error type F) Array method |
B |
39 | Which data structure is used in breadth-first search? A) Stack B) Queue C) Tree D) Graph E) Array F) Linked List |
B |
40 | What is the purpose of virtual memory? A) Faster processing B) Extend available memory C) Store passwords D) Cache data E) Compress files F) Encrypt data |
B |
41 | In Python, what is the output of: len(set([1,2,2,3,3,3]))? A) 6 B) 3 C) 1 D) 0 E) Error F) None |
B |
42 | Which is NOT a valid CSS selector? A) .class B) #id C) @element D) element E) element > child F) element + sibling |
C |
43 | In Java, what is autoboxing? A) Automatic compilation B) Primitive to wrapper conversion C) Memory allocation D) Exception handling E) Type casting F) Object creation |
B |
44 | What is the maximum value of a signed 8-bit integer? A) 255 B) 127 C) 128 D) 256 E) 64 F) 512 |
B |
45 | In databases, what does ACID stand for? A) Atomicity, Consistency, Isolation, Durability B) Asynchronous, Concurrent, Independent, Distributed C) Automatic, Conditional, Integrated, Dynamic D) Abstract, Compiled, Interpreted, Deployed E) Active, Cached, Indexed, Documented F) Allocated, Compressed, Incremental, Dedicated |
A |
46 | In networking, what layer is HTTP in the OSI model? A) Physical B) Data Link C) Network D) Transport E) Session F) Application |
F |
47 | What is the output of this Python code? ```python print("Hello" * 2) ``` A) Hello2 B) HelloHello C) 2Hello D) Error E) Hello Hello F) None |
B |
48 | Which is a creational design pattern? A) Adapter B) Observer C) Factory D) Strategy E) Decorator F) Proxy |
C |
49 | In C, what does malloc() return on failure? A) 0 B) -1 C) NULL D) void E) Error F) false |
C |
50 | What is the output of the following C++ program? #include <initializer_list> #include <iostream> using namespace std; void f(int) { cout << "Int"; } template<typename T> void f(initializer_list<T> il) { cout << "Template"; } int main() { f({1}); } A. Int B. Template C. IntTemplate D. TemplateInt E. It fails to compile due to ambiguity F. It runs but results in a runtime error |
B |
51 | What is the time complexity of inserting at the beginning of a linked list? A) O(1) B) O(log n) C) O(n) D) O(n log n) E) O(n²) F) O(2^n) |
A |
52 | In Python, which is immutable? A) List B) Dictionary C) Set D) Tuple E) Array F) Deque |
D |
53 | Consider the equality comparison of two large numbers in Python vs JavaScript: # Python code print(9999999999999999 == 10000000000000000) // JavaScript code console.log(9999999999999999 == 10000000000000000); What will each snippet print? A. Python: False, JavaScript: True B. Python: True, JavaScript: True C. Python: False, JavaScript: False D. Python: True, JavaScript: False E. Python raises OverflowError, JavaScript prints false F. Python prints False, JavaScript throws RangeError for exceeding Number.MAX_SAFE_INTEGER |
A |
54 | In JavaScript, what is the result of: NaN === NaN? A) true B) false C) null D) undefined E) NaN F) Error |
B |
55 | Which is NOT a common sorting algorithm? A) Quick Sort B) Merge Sort C) Heap Sort D) Tree Sort E) Jump Sort F) Radix Sort |
E |
56 | You are given a function f defined as follows: int f(int x) { if (x < 10) return 5 * x; else return 4 * x; } We want to check if f(x) is non-decreasing (monotonic increasing). Which of the following provides a counterexample showing that f is not monotonic? A. x₁ = 10, x₂ = 11 B. x₁ = 9, x₂ = 10 C. x₁ = 8, x₂ = 9 D. x₁ = 0, x₂ = 100 E. x₁ = 10, x₂ = 9 F. x₁ = 1, x₂ = 2 |
B |
57 | In Unix, what does the pipe operator (|) do? A) Logical OR B) Concatenate files C) Connect command output to input D) Create file E) Delete file F) Compare files |
C |
58 | Which protocol is connectionless? A) TCP B) UDP C) HTTP D) FTP E) SSH F) SMTP |
B |
59 | Consider this naive implementation of the softmax function: import math def softmax(values): exp_vals = [math.exp(x) for x in values] total = sum(exp_vals) return [v / total for v in exp_vals] What problem can arise when values contains very large (e.g., 100 or 1000+) numbers, and how can it be fixed? A. It can overflow for large inputs; the solution is to subtract the maximum input value from each value before exponentiating (normalize inputs). B. It can produce negative probabilities due to underflow; adding a small epsilon before exponentiating fixes this. C. It might never sum to 1.0 exactly due to precision, but multiplying all outputs by 100 fixes the percentages. D. It will return NaNs for large inputs; using Python’s decimal module for high precision arithmetic fixes it completely. E. It mis-orders the probabilities if the inputs are sorted descending; sorting the inputs first resolves it. F. No issues — the implementation is numerically stable for all real-valued inputs. |
A |
60 | Below is a function intended to verify if two arrays a and b of length len are identical. It returns false upon the first mismatch: bool verify(const uint8_t *a, const uint8_t *b, size_t len) { for (size_t i = 0; i < len; ++i) { if (a[i] != b[i]) return false; } return true; } What is the main security flaw in this code? A. There is no flaw; the function is constant-time and secure. B. It may read out of bounds if a and b have different lengths, leading to undefined behavior. C. It leaks memory addresses of a and b due to pointer comparisons. D. It will overflow an integer if len is extremely large. E. It is too slow for long inputs because it doesn’t use hardware acceleration. F. It is vulnerable to a timing attack since it returns as soon as a mismatch is found (revealing how many initial bytes match). |
F |
61 | In React, what triggers a re-render? A) Console.log B) State change C) Variable declaration D) Function call E) Import statement F) Comment addition |
B |
62 | Which command creates a new branch in Git? A) git branch new-branch B) git create new-branch C) git new branch D) git make branch E) git add branch F) git init branch |
A |
63 | In adversarial machine learning, attackers find small perturbations to input data that cause a model to misclassify. One way to make a model more robust against such adversarial examples is to explicitly incorporate adversarially perturbed inputs during the training process. Which of the following techniques directly involves training the model on adversarially modified examples in order to improve robustness to future adversarial attacks? A. Early stopping to prevent overfitting on the training data B. Applying dropout regularization during training C. Using L2 weight decay (weight regularization) in the optimizer D. Standard data augmentation with random noise or flips to training inputs E. Adversarial training (augmenting the training data with crafted adversarial examples and training the model on them) F. Gradient clipping to restrict the size of weight updates during training |
E |
64 | What is the order of output produced by the following JavaScript code? console.log('A'); setTimeout(() => { console.log('B'); Promise.resolve().then(() => console.log('C')); }, 0); Promise.resolve().then(() => { console.log('D'); setTimeout(() => console.log('E'), 0); }); console.log('F'); A) A, F, D, B, C, E B) A, F, B, D, C, E C) A, D, F, B, C, E D) A, D, B, F, E, C E) A, F, D, B, E, C F) A, B, D, F, C, E |
A |
65 | Consider this Haskell program defining an infinite list of ones: ones :: [Int] ones = 1 : ones main = print (take 5 ones) What will be the output of running this program? A. [1,1,1,1,1] B. An infinite sequence of 1 until terminated manually. C. [1,1,1,1] D. It will not produce any output (hangs forever). E. It will print 1 five times on separate lines. F. The program will not compile due to the infinite list definition. |
A |
66 | The Rust code below attempts to return a closure that prints a message. However, it fails to compile: fn make_printer() -> impl Fn() { let message = String::from("Hello!"); || println!("{}", message) } How can we modify this code to compile correctly? A. Add the move keyword before the closure to capture message by value. B. Annotate message with a 'static lifetime. C. Mark the function as unsafe to bypass the borrow checker. D. Return a reference &String from make_printer instead of a closure. E. Declare message as mutable and reuse it outside the function. F. No change needed – it should compile as-is. |
A |
67 | In C++, consider the program below with two threads: #include <thread> #include <iostream> using namespace std; int x = 0, flag = 0; void thread1() { x = 1; flag = 1; } void thread2() { while (flag == 0); // spin-wait until flag is set cout << x; } int main() { thread t1(thread1); thread t2(thread2); t1.join(); t2.join(); } Which statement about this program’s output is correct? A. It will always print 1 because setting flag to 1 guarantees x is 1 by then. B. It may print 0 because the code has a data race (no synchronization), so thread2 could see stale data (undefined behavior). C. It will print 0 on weak memory-order CPUs but 1 on strong x86 CPUs, due to hardware reordering differences. D. It cannot print 0 because the while(flag==0) loop ensures x is updated before proceeding. E. The program will consistently crash or throw an exception due to the race on x. F. Marking flag as volatile would entirely prevent seeing 0 in the output. |
B |
68 | What is the output of this code? ```python print(list(range(3))) ``` A) [1, 2, 3] B) [0, 1, 2] C) [0, 1, 2, 3] D) [3] E) range(3) F) Error |
B |
69 | In distributed systems, what does CAP theorem stand for? A) Consistency, Availability, Partition tolerance B) Concurrency, Atomicity, Performance C) Cache, Application, Protocol D) Client, API, Platform E) Create, Alter, Partition F) Cluster, Agent, Process |
A |
70 | Which JavaScript operator checks both value and type? A) == B) === C) != D) <= E) >= F) <> |
B |
71 | What is the space complexity of an algorithm that uses no extra space? A) O(0) B) O(1) C) O(log n) D) O(n) E) O(n²) F) O(∞) |
B |
72 | What is the output of this Python code? ```python class MetaConfusion(type): def __new__(mcs, name, bases, namespace): namespace['x'] = 42 return super().__new__(mcs, name, bases, namespace) class Base(metaclass=MetaConfusion): y = 10 def transform(self, val): return val * 2 class Derived(Base): def __init__(self): self.z = 5 super().__init__() def transform(self, val): return super().transform(val) + self.z class Wrapper: def __init__(self, obj): self._obj = obj def __getattr__(self, name): if name == 'special': return lambda: self._obj.x + self._obj.y return getattr(self._obj, name) d = Derived() w = Wrapper(d) result = w.transform(w.special()) - d.x print(result) ``` A) 67 B) 72 C) 77 D) 82 E) 87 F) 92 |
A |
73 | What is the output of this Java code? ```java import java.util.concurrent.*; import java.util.concurrent.atomic.*; public class ComplexThreading { static class Counter { private AtomicInteger value = new AtomicInteger(0); private final Object lock = new Object(); void increment() { synchronized(lock) { value.incrementAndGet(); } } int getValue() { return value.get(); } } static class Worker extends Thread { private Counter counter; private CyclicBarrier barrier; Worker(Counter c, CyclicBarrier b) { counter = c; barrier = b; } public void run() { try { for(int i = 0; i < 5; i++) { counter.increment(); } barrier.await(); for(int i = 0; i < 3; i++) { counter.increment(); } } catch(Exception e) {} } } public static void main(String[] args) throws Exception { Counter counter = new Counter(); CyclicBarrier barrier = new CyclicBarrier(3); Worker[] workers = new Worker[3]; for(int i = 0; i < 3; i++) { workers[i] = new Worker(counter, barrier); workers[i].start(); } for(Worker w : workers) { w.join(); } System.out.println(counter.getValue()); } } ``` A) 15 B) 18 C) 21 D) 24 E) 27 F) 30 |
D |
74 | What is the output of this JavaScript code? ```javascript function createFactory() { let shared = 0; return class Factory { constructor(init) { this.value = init; shared++; } async process() { await new Promise(r => setTimeout(r, 0)); return this.value + shared; } static create(n) { return new this(n * 2); } }; } const F1 = createFactory(); const F2 = createFactory(); class Extended extends F1 { async process() { const base = await super.process(); return base * 2; } } async function main() { const obj1 = F1.create(5); const obj2 = new F2(3); const obj3 = new Extended(4); const results = await Promise.all([ obj1.process(), obj2.process(), obj3.process() ]); console.log(results.reduce((a, b) => a + b, 0)); } main(); ``` A) 28 B) 31 C) 34 D) 37 E) 40 F) 43 |
A |
75 | What is the output of this C++ code? ```cpp #include <iostream> #include <type_traits> template<int N> struct Factorial { static constexpr int value = N * Factorial<N-1>::value; }; template<> struct Factorial<0> { static constexpr int value = 1; }; template<typename T, typename U> struct TypeCalculator { static constexpr int process(int x) { return sizeof(T) * x + sizeof(U); } }; template<typename T> struct TypeCalculator<T, T> { static constexpr int process(int x) { return sizeof(T) * (x + 1); } }; class Base { protected: int value = 10; public: virtual int compute() { return value; } }; class Derived : public Base { int extra = 5; public: int compute() override { return value * 2 + extra; } }; int main() { constexpr int fact = Factorial<5>::value; int calc1 = TypeCalculator<int, double>::process(3); int calc2 = TypeCalculator<char, char>::process(4); Derived d; Base* ptr = &d; std::cout << (fact / 10 + calc1 + calc2 - ptr->compute()); return 0; } ``` A) 5 B) 7 C) 9 D) 11 E) 12 F) 15 |
E |
76 | What is the output of this Ruby code? ```ruby module Mixable def self.included(base) base.extend(ClassMethods) end module ClassMethods def create_method(name, &block) define_method(name, &block) end end def mix_value @mix_value ||= 0 @mix_value += 10 end end class Base include Mixable attr_accessor :base_val def initialize @base_val = 5 end create_method :dynamic do |x| base_val * x + mix_value end end class Derived < Base def initialize super @base_val = 7 end def dynamic(x) super(x) + mix_value end end obj = Derived.new result = obj.dynamic(3) + obj.base_val puts result ``` A) 45 B) 48 C) 51 D) 54 E) 58 F) 60 |
E |
77 | What is the output of this Go code? ```go package main import ( "fmt" "sync" ) type Counter struct { mu sync.Mutex value int } func (c *Counter) Increment(n int) { c.mu.Lock() c.value += n c.mu.Unlock() } func (c *Counter) Get() int { c.mu.Lock() defer c.mu.Unlock() return c.value } func worker(c *Counter, ch chan int, wg *sync.WaitGroup) { defer wg.Done() for val := range ch { c.Increment(val) if val%2 == 0 { c.Increment(1) } } } func main() { counter := &Counter{} ch := make(chan int, 3) var wg sync.WaitGroup for i := 0; i < 2; i++ { wg.Add(1) go worker(counter, ch, &wg) } nums := []int{3, 4, 5, 6, 7, 8} for _, n := range nums { ch <- n } close(ch) wg.Wait() fmt.Println(counter.Get()) } ``` A) 33 B) 36 C) 39 D) 42 E) 45 F) 48 |
B |
78 | What is the output of this Rust code? ```rust struct Container<T> { data: Vec<T>, } impl<T: Clone> Container<T> { fn new() -> Self { Container { data: Vec::new() } } fn add(&mut self, item: T) { self.data.push(item); } fn process<F>(&self, f: F) -> Vec<T> where F: Fn(&T) -> T { self.data.iter().map(|x| f(x)).collect() } } struct Transformer { factor: i32, } impl Transformer { fn transform(&self, val: &i32) -> i32 { val * self.factor + 1 } } fn complex_operation(mut c: Container<i32>) -> i32 { c.add(3); c.add(5); let t1 = Transformer { factor: 2 }; let t2 = Transformer { factor: 3 }; let res1 = c.process(|x| t1.transform(x)); let res2 = Container { data: res1 }.process(|x| t2.transform(x)); res2.iter().sum() } fn main() { let mut container = Container::new(); container.add(2); container.add(4); println!("{}", complex_operation(container)); } ``` A) 86 B) 92 C) 98 D) 100 E) 110 F) 116 |
D |
79 | What is the output of this TypeScript code? ```typescript interface Processor<T> { process(input: T): T; } class Chain<T> { private processors: Processor<T>[] = []; add<U extends Processor<T>>(p: U): Chain<T> { this.processors.push(p); return this; } execute(initial: T): T { return this.processors.reduce((val, proc) => proc.process(val), initial); } } class NumberProcessor implements Processor<number> { constructor(private op: (n: number) => number) {} process(input: number): number { return this.op(input); } } class ComplexProcessor<T extends number> implements Processor<T> { private cache = new Map<T, T>(); process(input: T): T { if (!this.cache.has(input)) { const result = (input * 2 + 3) as T; this.cache.set(input, result); } return this.cache.get(input)!; } } const chain = new Chain<number>() .add(new NumberProcessor(n => n + 5)) .add(new ComplexProcessor()) .add(new NumberProcessor(n => n - 4)); const result = chain.execute(7); console.log(result); ``` A) 23 B) 27 C) 29 D) 31 E) 33 F) 35 |
A |
80 | What is the output of this C# code? ```csharp using System; using System.Linq; using System.Collections.Generic; public class Program { delegate int Transform(int x); class DataProcessor { private List<int> data = new List<int>(); public void Add(params int[] values) { data.AddRange(values); } public int Process(Transform t) { return data.Select(t).Sum(); } public DataProcessor Filter(Func<int, bool> predicate) { var result = new DataProcessor(); result.data.AddRange(data.Where(predicate)); return result; } } static Transform CreateTransform(int factor) { int offset = 2; return x => { offset++; return x * factor + offset; }; } public static void Main() { var processor = new DataProcessor(); processor.Add(1, 2, 3, 4, 5); var filtered = processor.Filter(x => x % 2 == 1); Transform t1 = CreateTransform(2); Transform t2 = x => x + 10; Transform combined = x => t2(t1(x)); int result = filtered.Process(combined); Console.WriteLine(result); } } ``` A) 60 B) 66 C) 69 D) 72 E) 75 F) 78 |
A |
81 | What is the output of this Scala code? ```scala object ComplexCode { implicit class RichInt(val x: Int) extends AnyVal { def ***(y: Int): Int = x * y + x + y } trait Processor[T] { def process(input: T)(implicit conv: T => Int): Int } class ChainProcessor[T] extends Processor[T] { private var operations: List[Int => Int] = List() def addOp(f: Int => Int): this.type = { operations = operations :+ f this } def process(input: T)(implicit conv: T => Int): Int = { operations.foldLeft(conv(input))((acc, f) => f(acc)) } } sealed trait Result case class Success(value: Int) extends Result case class Failure(msg: String) extends Result def compute(x: Int, y: Int): Result = { implicit val doubleToInt: Double => Int = _.toInt val processor = new ChainProcessor[Double] processor.addOp(_ + 3).addOp(_ * 2).addOp(_ - 5) val base = x *** y val processed = processor.process(base.toDouble) if (processed > 50) Success(processed) else Failure("Too small") } def main(args: Array[String]): Unit = { compute(4, 5) match { case Success(v) => println(v) case Failure(m) => println(0) } } } ``` A) 51 B) 53 C) 55 D) 57 E) 59 F) 61 |
E |
82 | The C++ template below tries to make a deep copy of a raw array *and* simulate an allocation-failure path. Two subtle problems remain that can crash the program, but one of them is the most fundamental. Identify it. ```cpp template<typename T> T* copy_array(const T* src, std::size_t n) noexcept(false) { if (!src || n == 0) return nullptr; T* dst = nullptr; try { dst = new T[n]; // (1) } catch (const std::bad_alloc&) { // simulated fallback path … dst = reinterpret_cast<T*>(std::malloc(n * sizeof(T))); } // BUG hiding here ↓ for (std::size_t i = 0; i <= n; ++i) // (2) dst[i] = src[i]; return dst; // caller owns memory } ``` A) Using `malloc` in the fallback path breaks RAII and risks a leak. B) The function never frees `dst` if the copy later throws. C) The loop condition `i <= n` writes one element past the end of `dst`. D) `reinterpret_cast` is undefined behaviour for non-trivially-copyable `T`. E) Returning raw pointers instead of `std::unique_ptr<T[]>` violates the Rule of 0. F) Initial `src` null-check is unreliable because `nullptr` can compare equal to integers. |
C |
83 | The next function tries to fetch a user, then that user’s last five posts, *and* finally combine the results. Why will it still log `undefined`? ```javascript async function latestFivePostTitles(userId) { let user; fetch(`/api/users/${userId}`) // (1) .then(r => r.ok && r.json()) .then(u => { user = u; }) .then(() => fetch(`/api/posts?userId=${user.id}`)) // (2) .then(r => r.json()) .then(posts => posts.slice(0, 5)) .then(titles => console.log(titles)); } ``` A) Line (2) is missing an explicit `await` keyword. B) `user.id` is `undefined` because the promise chain in (1) is non-blocking and `user` is read before it is set. C) `r.json()` is synchronous, so the chain resolves too early. D) Arrow-function implicit returns are required after braces. E) The slice call mutates the original posts array. F) Promises inside `async` functions cannot be chained with `.then`. |
B |
84 | We want a **thread-safe, O(1) lookup** that can be updated at runtime without introducing race conditions. Which concise refactor best fulfils *all* requirements while staying Pythonic? ```python def get_permission_level(role): # original 8-branch if/elif ladder here … ``` A) `return {'admin': 4, 'editor': 3, 'contributor': 2, 'viewer': 1}.get(role, 0)` B) `lock = threading.Lock(); with lock: return ROLE_MAP.get(role, 0)` C) `return len([r for r in ROLES_ORDERED if r == role])` D) `return max(4 if role=='admin' else 3 if role=='editor' else 2 if role=='contributor' else 1 if role=='viewer' else 0)` E) `try: return ROLE_MAP[role] except KeyError: return 0` F) `return globals().get(role, 0)` |
E |
85 | Refactor this Java method so it is **deterministic**, uses *no boxing*, and is still the most readable solution. Which option achieves that? ```java public long sumOfSquares(List<Integer> numbers) { long sum = 0; // … imperative loop … } ``` A) `return numbers.stream().map(n -> n * n).filter(n -> n % 2 == 0).sum();` B) `return numbers.stream().filter(n -> (n & 1) == 0).mapToLong(n -> (long)n * n).sum();` C) `return numbers.parallelStream().filter(n -> n % 2 == 0).reduce(0L, (a, b) -> a + (long)b*b);` D) `numbers.forEach(n -> { if(n % 2 == 0) sum += (long)n*n; }); return sum;` E) `return numbers.stream().filter(n -> n % 2 == 0).collect(Collectors.summingLong(n -> (long)n*n));` F) `return numbers.stream().map(n -> n % 2 == 0 ? (long)n*n : 0).mapToLong(Long::longValue).sum();` |
B |
86 | The PHP snippet *appears* to use prepared statements but was subtly broken by a later edit. Which line now poses the gravest security risk? ```php $userId = $_GET['id']; $stmt = $conn->prepare('SELECT username, email FROM users WHERE id = ?'); // accidental mistake ↓ $sql = "SELECT username, email FROM users WHERE id = $userId"; $result = $conn->query($sql); ``` A) Hard-coded DB credentials. B) Potential stored-XSS when echoing `$row['username']`. C) The interpolated `$userId` inside `$sql` enables SQL-Injection even though a prepared statement was written above. D) The connection is never closed. E) `$userId` could contain path-traversal characters. F) No user authentication guard. |
C |
87 | An engineer has built a "secure" JavaScript sandbox using Node.js to evaluate untrusted mathematical expressions from a third-party partner. To prevent abuse, they use the vm module and a Proxy to intercept property access. The sandbox is exposed via a web server that processes a JSON payload. Analyze the following Node.js code. Which statement unambiguously describes the most severe, exploitable security vulnerability? JavaScript // server.js const express = require('express'); const { VM } = require('vm2'); const fetch = require('node-fetch'); const app = express(); app.use(express.json()); // The 'secure' sandbox utility function createSandbox(apiResponse) { const sandbox = { result: null, apiData: apiResponse, log: (message) => { // Intentionally delayed log to simulate a slow I/O operation setTimeout(() => console.log(SANDBOX: ${message}), 50); } }; const securityHandler = { get(target, prop) { if (prop === 'constructor' || prop === 'prototype') { throw new Error('Security Violation: Property access denied.'); } return target[prop]; } }; return new Proxy(sandbox, securityHandler); } // The main route for processing expressions app.post('/calculate', async (req, res) => { const { expression } = req.body; // e.g., "result = apiData.value * 2" if (!expression || typeof expression !== 'string' || expression.length > 128) { return res.status(400).send({ error: 'Invalid expression' }); } try { const apiResponse = await fetch('https://api.internal.corp/data'); const data = await apiResponse.json(); const sandbox = createSandbox(data); const vm = new VM({ timeout: 100, sandbox: sandbox, eval: false, wasm: false }); vm.run(expression); res.status(200).send({ result: sandbox.result }); } catch (err) { res.status(500).send({ error: err.message }); } }); app.listen(3000); Answer Options A) The Proxy is ineffective because a sophisticated payload in expression can access the Proxy's internal [[Handler]] and [[Target]] slots to bypass the get trap and achieve prototype pollution. B) The application is vulnerable to a Time-of-Check to Time-of-Use (TOCTOU) race condition. An attacker can modify the sandbox.result after vm.run() completes but before res.status(200).send() is called by exploiting the Node.js event loop. C) The code is vulnerable to Server-Side Request Forgery (SSRF) because the fetch call to api.internal.corp can be manipulated by an attacker-controlled expression that reassigns fetch within the sandbox. D) The code has a critical sandbox escape vulnerability. The log function's asynchronous nature can be exploited by the expression to execute code on the host machine outside the vm2 timeout and sandbox constraints. E) The primary vulnerability is Denial-of-Service (DoS). The setTimeout within the log function can be called in a tight loop from the expression, creating millions of pending timers that exhaust server memory. F) The code is vulnerable to HTTP Response Splitting. An attacker can craft a malicious expression that sets sandbox.result to a value containing \r\n characters, which are then reflected unsanitized in the final JSON response, allowing for header injection. |
D |
88 | Finish this query so it works *unchanged* on both PostgreSQL and MySQL and uses the **shortest possible syntax**. ```sql SELECT e.name FROM employees e -- JOIN here WHERE d.name = 'Sales'; ``` A) `JOIN departments d ON e.id = d.employee_id` B) `LEFT JOIN departments d ON e.id = d.department_id` C) `FROM departments d WHERE e.department_id = d.id` D) `JOIN departments d USING (department_id)` E) `CROSS JOIN departments d` F) `WITH departments d ON e.department_id = d.id` |
D |
89 | We need to listen to `ch1` or `ch2` but *also* ensure the goroutine doesn’t leak if neither channel ever closes. Fill in the blank. ```go func waitForMessage(ctx context.Context, ch1, ch2 <-chan string) { select { // <-- BLANK WAS HERE case <-ctx.Done(): return case msg1 := <-ch1: fmt.Println("ch1:", msg1) case msg2 := <-ch2: fmt.Println("ch2:", msg2) case <-time.After(2 * time.Second): fmt.Println("timeout") } } ``` A) `for select` B) `select case` C) `switch` D) `select` E) `go select` F) `if select` |
D |
90 | A more realistic GitHub Actions job now checks out code, caches npm, and runs on Node 18. Which definition is valid? ```yaml jobs: test: # choose one snippet ↓ ``` A) `runner: ubuntu-latest\n steps:\n - uses: actions/setup-node@v3\n with: {node-version: 18}\n - run: npm install && npm test` B) `runs-on: ubuntu-latest\n uses: actions/setup-node@v3\n with: {node-version: 18}\n steps:\n - run: npm ci\n - run: npm test` C) `runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v3\n - uses: actions/setup-node@v3\n with: {node-version: '18', cache: 'npm'}\n - run: npm ci\n - run: npm test` D) `runs-on: ubuntu-latest\n steps:\n - with: {node-version: 18}\n uses: actions/setup-node@v3\n - run: npm install\n - run: npm test` E) `os: ubuntu-latest\n steps:\n - run: npm install\n - run: npm test` F) `runs-on: ubuntu-latest\n services: {node: 18}\n steps:\n - run: npm install\n - run: npm test` |
C |
91 | Which liveness probe definition avoids start-up restart loops *and* follows Kubernetes syntax? A) `livenessProbe:\n httpGet:\n path: /healthz\n port: 8080\n initialDelaySeconds: 5\n periodSeconds: 10` B) `probe:\n liveness:\n http: {path:/healthz,port:8080}\n interval: 10` C) `healthCheck:\n type: liveness\n httpGet:\n path:/healthz\n port:8080\n periodSeconds:10` D) `livenessProbe:\n exec:\n command: [\"curl\",\"-f\",\"http://localhost:8080/healthz\"]\n periodSeconds: 10` E) `livenessProbe:\n path:/healthz\n port:8080\n period:10s` F) `livenessProbe:\n http:\n path:/healthz\n port:8080\n periodSeconds:10` |
A |
92 | Traffic model: 10 000 reads/s, 40 writes/minute, DB must stay below 1 000 QPS and serve reads < 20 ms p95. Which single caching pattern satisfies *all* requirements **and** keeps code simplest? A) Write-through B) Write-around C) Write-behind (async) D) Cache-aside (lazy-loading) E) Blow away entire cache on every write F) Skip caching; add a read-replica DB |
D |
93 | Clients are behind restrictive corporate proxies that only allow outbound HTTPS. You still need full-duplex, low-latency game traffic. Which protocol is the best fit? A) HTTP/1.1 long-polling B) gRPC unary RPCs over HTTP/2 C) WebSockets over wss:// D) Server-Sent Events E) REST over HTTP/2 F) SMTP |
C |
94 | You are debugging a complex integration test that relies on requests.Session internals, custom adapters, and header precedence. Consider the following self-contained snippet (assume requests 2.31+ and standard CPython 3.12): import requests from io import BytesIO URL = "https://httpbin.org/post" class PassthroughAdapter(requests.adapters.HTTPAdapter): """Adds a Query-ID fragment swap *after* the session has merged settings.""" def add_headers(self, request, **kwargs): super().add_headers(request, **kwargs) # swap the query string and fragment *in place* p = requests.utils.urlparse(request.url) request.url = requests.utils.urlunparse(( p.scheme, p.netloc, p.path, p.params, p.fragment, # new query (old fragment) p.query, # new fragment (old query) )) s = requests.Session() # ❶ Session-level defaults s.params = {"token": "ABC123"} s.headers = {"Content-Type": "application/octet-stream"} s.mount("https://httpbin.org", PassthroughAdapter()) # installs custom adapter # ❷ Build the one-off request req = requests.Request( "POST", # method URL + "?init=1#debug", # base URL has both query & fragment params={"token": None, "v": "42"},# overrides session.params headers={"Content-Type": "application/json"}, files={"report": ("rep.csv", BytesIO(b"x,y\n1,2"))}, ) # ❸ Prepare + send (network call succeeds) prepped = s.prepare_request(req) print(prepped.url) # ← What EXACT string is printed? A) https://httpbin.org/post?init=1&v=42&token=ABC123#debug B) https://httpbin.org/post?init=1&v=42#token=ABC123 C) https://httpbin.org/post#init=1&v=42 D) https://httpbin.org/post?debug&v=42#init=1 E) https://httpbin.org/post?init=1&v=42#debug F) https://httpbin.org/post#init=1&v=42&token=ABC123 |
E |
95 | A memoised child component should *not* re-render when its parent does unless `onPress` really changes. How should `handlePress` be wrapped? ```jsx const Parent = () => { const [count, setCount] = useState(0); const handlePress = () => console.log('pressed'); return (<> <button onClick={() => setCount(c=>c+1)}>++</button> <MemoizedChild onPress={handlePress}/> </>); }; ``` A) `useEffect` B) `useRef` C) `useContext` D) `useCallback` E) `useMemo` F) `useState` |
D |
96 | Which single naming rule violation would Roslyn flag as *Severity = Error* with default Microsoft conventions? ```csharp public class customerRecord : IDisposable { public string customerName; public async Task printDetailsAsync() {...} public void Dispose() {...} } ``` A) The class `customerRecord` should be `CustomerRecord` (PascalCase). B) Public field `customerName` should be a property named `CustomerName`. C) Method `printDetailsAsync` should be `PrintDetailsAsync`. D) Fields in `IDisposable` types must be private. E) Both A and B. F) There are no violations. |
A |
97 | What will the output be from the following code? ``` from dataclasses import dataclass, field from typing import ClassVar # ---------- custom metaclass ---------- class Reveal(type): def __new__(mcls, name, bases, ns): # store the length of the class name ns["count"] = sum(map(len, name)) return super().__new__(mcls, name, bases, ns) def __call__(cls, *a, **kw): obj = super().__call__(*a, **kw) # mutate instance AFTER normal __init__ obj.data.append(cls.count) return obj # ---------- data‑descriptor ---------- class Memo: def __set_name__(self, owner, name): self.name = name # remember attribute's name def __get__(self, inst, owner): if inst is None: return self # first access: compute & replace descriptor with value if self.name not in inst.__dict__: value = len(owner.__name__) + len(inst.data) # shadow the descriptor for future fast access inst.__dict__[self.name] = value return inst.__dict__[self.name] # ---------- primary dataclass ---------- @dataclass class Alpha(metaclass=Reveal): data: list = field(default_factory=lambda: [1]) # fresh list every time note: ClassVar[Memo] = Memo() # descriptor, not a field def tweak(self): self.data[0] += 1 return sum(self.data) + self.note # ---------- alias (same class object) ---------- Beta = Alpha # ---------- late‑bound lambda capture ---------- def maker(funcs=[]): x = len(funcs) funcs.append(lambda y=x: y) # default arg captures current x return funcs[-1] result = Alpha().tweak() + Beta().tweak() + maker()() + maker()() print(result) ``` Answer options: A) 26 B) 27 C) 28 D) 30 E) 29 F) 31 |
E |
98 | What exact value does the following program print to stdout? (Choose one option A–F.) import java.lang.invoke.*; import java.util.*; import java.util.concurrent.*; /* A tiny expression DSL */ sealed interface Expr permits Val, Add, Mul, Neg { int eval(); } record Val(int v) implements Expr { public int eval() { return v; } } record Add(Expr l, Expr r) implements Expr { public int eval() { return l.eval() + r.eval(); } } record Mul(Expr l, Expr r) implements Expr { public int eval() { return l.eval() * r.eval(); } } record Neg(Expr in) implements Expr { public int eval() { return -in.eval(); } } public class Puzzle { private static final VarHandle ACC; static { try { ACC = MethodHandles.lookup() .findStaticVarHandle(Puzzle.class, "acc", int.class); // ✅ static lookup } catch (Exception e) { throw new ExceptionInInitializerError(e); } } private static int acc = 0; private static void accumulate(Expr e) { int delta = e.eval(); if (delta % 2 == 0) delta = -delta; ACC.getAndAdd(delta); // atomic, order-independent :contentReference[oaicite:2]{index=2} } public static void main(String[] args) throws Exception { List<Expr> exprs = List.of( new Add(new Val(3), new Neg(new Val(1))), // 2 → -2 new Mul(new Val(2), new Val(3)), // 6 → -6 new Neg(new Add(new Val(1), new Val(4))) // -5 → -5 ); try (var exec = Executors.newVirtualThreadPerTaskExecutor()) { // virtual threads :contentReference[oaicite:3]{index=3} for (Expr e : exprs) exec.submit(() -> accumulate(e)); } acc ^= acc >>> 1; // Gray-code tweak :contentReference[oaicite:4]{index=4} System.out.println(acc); } } A) -2147483638 B) -13 C) 2147483658 D) -2147483648 E) Non-deterministic (depends on thread scheduling) F) Fails to compile due to preview features |
A |
99 | What exact value does the following program print to stdout? (Choose one option A–F.) import java.lang.invoke.*; import java.util.*; import java.util.concurrent.*; /* A tiny expression DSL */ sealed interface Expr permits Val, Add, Mul, Neg { int eval(); } record Val(int v) implements Expr { public int eval() { return v; } } record Add(Expr l, Expr r) implements Expr { public int eval() { return l.eval() + r.eval(); } } record Mul(Expr l, Expr r) implements Expr { public int eval() { return l.eval() * r.eval(); } } record Neg(Expr in) implements Expr { public int eval() { return -in.eval(); } } public class Puzzle { private static final VarHandle ACC; static { try { ACC = MethodHandles.lookup() .findStaticVarHandle(Puzzle.class, "acc", int.class); // ✅ static lookup } catch (Exception e) { throw new ExceptionInInitializerError(e); } } private static int acc = 0; private static void accumulate(Expr e) { int delta = e.eval(); if (delta % 2 == 0) delta = -delta; ACC.getAndAdd(delta); // atomic, order-independent :contentReference[oaicite:2]{index=2} } public static void main(String[] args) throws Exception { List<Expr> exprs = List.of( new Add(new Val(3), new Neg(new Val(1))), // 2 → -2 new Mul(new Val(2), new Val(3)), // 6 → -6 new Neg(new Add(new Val(1), new Val(4)) // -5 → -5 ); try (var exec = Executors.newVirtualThreadPerTaskExecutor()) { // virtual threads :contentReference[oaicite:3]{index=3} for (Expr e : exprs) exec.submit(() -> accumulate(e)); } acc ^= acc >>> 1; // Gray-code tweak :contentReference[oaicite:4]{index=4} System.out.println(acc); } } A) -2147483638 B) -13 C) 2147483658 D) -2147483648 E) Non-deterministic (depends on thread scheduling) F) Fails to compile |
F |
100 | Assume the code is compiled and run on OpenJDK 17 with no --add-opens flags. (No command-line modules are opened, and the program is executed exactly once.) import java.lang.reflect.*; public class Puzzle { // Compile-time constant, inlined wherever ANSWER is used (§8.3.2) private static final String ANSWER = "ORIGINAL"; static { // class-initialiser (§12.4.2) try { Field f = Puzzle.class.getDeclaredField("ANSWER"); f.setAccessible(true); // bypass 'private' Field mods = Field.class.getDeclaredField("modifiers"); mods.setAccessible(true); // <— filtered since JDK 12 mods.setInt(f, f.getModifiers() & ~Modifier.FINAL); f.set(null, "MUTATED"); // attempt to overwrite } catch (Exception e) { System.out.println("INIT-ERROR:" + e.getClass().getSimpleName()); } } public static void main(String[] args) { System.out.println(ANSWER); } } What exactly is printed (or thrown) when the program runs? Option Outcome A) Prints only ORIGINAL (single line). B) Prints two lines: INIT-ERROR: InaccessibleObjectException ORIGINAL C) Prints MUTATED (single line). D) Fails during class-initialisation and terminates with InaccessibleObjectException (nothing printed by main). E) Compilation fails; program cannot be run. F) Prints two lines: INIT-ERROR: NoSuchFieldException ORIGINAL |
F |
No triggers defined for this benchmark. Create a trigger to automatically run this benchmark when a new model is added that matches your criteria.
No alerts defined for this benchmark. Create an alert to get notified when an execution result matching your criteria performs well on this benchmark.
Model | Reasoning Effort | Strategy | Executions | Accuracy | Cost | Duration |
---|