1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
|
[
{
"category": "programming",
"language": "javascript",
"attribution": "JavaScript",
"content": "const total = items.reduce((acc, item) => acc + item.price, 0);",
"explanation": "reduce walks the array carrying a running value. The 0 is the starting total; drop it and an empty array throws."
},
{
"category": "programming",
"language": "javascript",
"attribution": "JavaScript",
"content": "const unique = [...new Set(values)].sort((a, b) => a - b);",
"explanation": "A Set discards duplicates. Spreading it back to an array allows sorting; the comparator is required or numbers sort as text."
},
{
"category": "programming",
"language": "javascript",
"attribution": "JavaScript",
"content": "export async function load(url) { const res = await fetch(url); return res.json(); }",
"explanation": "fetch resolves as soon as headers arrive, so .json() is a second await for the body. It does not throw on a 404 - check res.ok."
},
{
"category": "programming",
"language": "javascript",
"attribution": "JavaScript",
"content": "document.querySelectorAll('.row').forEach(el => el.classList.toggle('active'));",
"explanation": "querySelectorAll returns a static NodeList, so it will not change as you mutate the elements in it."
},
{
"category": "programming",
"language": "javascript",
"attribution": "JavaScript",
"content": "if (typeof value !== 'string' || value.length === 0) { return null; }",
"explanation": "A guard clause: reject the bad input first and return, instead of nesting the real work inside an if."
},
{
"category": "programming",
"language": "javascript",
"attribution": "JavaScript",
"content": "const { id, name = 'anonymous', ...rest } = await request.json();",
"explanation": "Destructuring with a default and a rest property. The default applies only when the value is undefined, not when it is null."
},
{
"category": "programming",
"language": "python",
"attribution": "Python",
"content": "squares = [n * n for n in range(1, 21) if n % 3 != 0]",
"explanation": "A list comprehension: the expression, the loop, then the filter. Faster and clearer than appending in a for loop."
},
{
"category": "programming",
"language": "python",
"attribution": "Python",
"content": "def fib(n): return n if n < 2 else fib(n - 1) + fib(n - 2)",
"explanation": "Recursion with a base case. Correct but exponential - each call spawns two more, so it recomputes the same values repeatedly."
},
{
"category": "programming",
"language": "python",
"attribution": "Python",
"content": "with open('data.csv', encoding='utf-8') as f: rows = [line.split(',') for line in f]",
"explanation": "with closes the file even if the body raises. Iterating a file yields lines without loading it all into memory."
},
{
"category": "programming",
"language": "python",
"attribution": "Python",
"content": "counts = {word: text.count(word) for word in set(text.split())}",
"explanation": "A dict comprehension. Note it is quadratic: count rescans the whole string per word. collections.Counter is the right tool."
},
{
"category": "programming",
"language": "python",
"attribution": "Python",
"content": "try: value = int(raw) except ValueError: value = 0",
"explanation": "Catching the specific exception, not a bare except - a bare one would also swallow KeyboardInterrupt."
},
{
"category": "programming",
"language": "rust",
"attribution": "Rust",
"content": "let mut counts: HashMap<String, usize> = HashMap::new();",
"explanation": "mut because inserting mutates it. The type annotation is needed here since nothing yet tells the compiler what it holds."
},
{
"category": "programming",
"language": "rust",
"attribution": "Rust",
"content": "fn main() { println!(\"{}\", args().skip(1).collect::<Vec<_>>().join(\" \")); }",
"explanation": "skip(1) drops the program name, which is always the first argument. Vec<_> lets the compiler infer the element type."
},
{
"category": "programming",
"language": "rust",
"attribution": "Rust",
"content": "let total: i64 = values.iter().filter(|v| **v > 0).sum();",
"explanation": "iter() borrows rather than consuming. The double deref is because filter hands you a reference to the iterator's own reference."
},
{
"category": "programming",
"language": "rust",
"attribution": "Rust",
"content": "match result { Ok(v) => println!(\"{v}\"), Err(e) => eprintln!(\"error: {e}\") }",
"explanation": "match on a Result must cover both arms - the compiler rejects it otherwise, which is how Rust stops an error going unhandled."
},
{
"category": "programming",
"language": "rust",
"attribution": "Rust",
"content": "pub struct Point { pub x: f64, pub y: f64 }",
"explanation": "Fields are private by default in Rust, so each one needs its own pub - making the struct public does not publish its contents."
},
{
"category": "programming",
"language": "rust",
"attribution": "Rust",
"content": "impl Display for Token { fn fmt(&self, f: &mut Formatter) -> Result { write!(f, \"{}\", self.0) } }",
"explanation": "Implementing Display is what makes a type usable in {}. self.0 is the first field of a tuple struct."
},
{
"category": "programming",
"language": "clike",
"attribution": "C",
"content": "int *buf = malloc(len * sizeof(int)); if (!buf) return -1;",
"explanation": "malloc returns NULL when it fails, and checking is not optional. sizeof(int) rather than 4 keeps it correct across platforms."
},
{
"category": "programming",
"language": "clike",
"attribution": "C",
"content": "for (int i = 0; i < n; i++) { sum += a[i] * b[i]; }",
"explanation": "A dot product. The bound is < n, not <= n; off-by-one here reads past the end of the array."
},
{
"category": "programming",
"language": "clike",
"attribution": "C",
"content": "struct node { int value; struct node *next; };",
"explanation": "A linked-list node. It refers to its own type through a pointer, which is legal because a pointer has a known size."
},
{
"category": "programming",
"language": "clike",
"attribution": "Go",
"content": "for i, v := range items { fmt.Printf(\"%d: %v\\n\", i, v) }",
"explanation": "range yields index and value. In Go before 1.22 the loop variable was reused each iteration, which surprised anyone capturing it in a closure."
},
{
"category": "programming",
"language": "clike",
"attribution": "Go",
"content": "if err != nil { return fmt.Errorf(\"read config: %w\", err) }",
"explanation": "Go's error convention. %w wraps the original so errors.Is and errors.As can still see it further up."
},
{
"category": "programming",
"language": "clike",
"attribution": "Java",
"content": "public static void main(String[] args) { System.out.println(\"ready\"); }",
"explanation": "Java's entry point. The signature is fixed: static so it runs without an instance, and taking the command-line arguments."
},
{
"category": "programming",
"language": "shell",
"attribution": "Shell",
"content": "grep -rn \"TODO\" src/ | awk -F: '{print $1}' | sort -u",
"explanation": "grep -n prints file:line:text, awk splits on the colon to take the filename, sort -u removes the duplicates."
},
{
"category": "programming",
"language": "shell",
"attribution": "Shell",
"content": "for f in *.log; do gzip -9 \"$f\" && echo \"packed $f\"; done",
"explanation": "The quotes around $f matter: without them a filename containing a space becomes two arguments."
},
{
"category": "programming",
"language": "shell",
"attribution": "Shell",
"content": "export PATH=\"$HOME/.local/bin:$PATH\" && command -v rg >/dev/null || echo missing",
"explanation": "Prepending puts your own binaries ahead of the system ones. command -v is the portable test for whether something is installed."
},
{
"category": "programming",
"language": "shell",
"attribution": "Git",
"explanation": "Finds the commit that introduced a bug by bisecting history. Give it a known-good and known-bad commit and it halves the range each step.",
"content": "git bisect start HEAD v1.2.0 && git bisect run ./test.sh"
},
{
"category": "programming",
"language": "shell",
"attribution": "Git",
"explanation": "Who last touched each line of a range, which is how you find the person to ask rather than the person to blame.",
"content": "git log -L 40,60:src/parser.rs --oneline"
},
{
"category": "programming",
"language": "shell",
"attribution": "Git",
"explanation": "Recovers commits that are no longer reachable from any branch. A hard reset does not destroy them; it just stops pointing at them.",
"content": "git reflog --date=iso | head -20"
},
{
"category": "programming",
"language": "python",
"attribution": "Python",
"explanation": "zip pairs two sequences and stops at the shorter one. strict=True makes a length mismatch an error rather than silent truncation.",
"content": "for name, score in zip(names, scores, strict=True): print(f'{name}: {score:>5.1f}')"
},
{
"category": "programming",
"language": "python",
"attribution": "Python",
"explanation": "defaultdict removes the exists-check before every append, which is the most common shape of a grouping loop.",
"content": "groups = defaultdict(list); [groups[w[0]].append(w) for w in words]"
},
{
"category": "programming",
"language": "javascript",
"attribution": "JavaScript",
"explanation": "?? falls back only on null or undefined, unlike ||, which also fires on 0 and the empty string.",
"content": "const port = config.port ?? process.env.PORT ?? 8080;"
},
{
"category": "programming",
"language": "javascript",
"attribution": "JavaScript",
"explanation": "Promise.all runs them concurrently and rejects on the first failure; allSettled waits for every result instead.",
"content": "const [user, posts] = await Promise.all([getUser(id), getPosts(id)]);"
},
{
"category": "programming",
"language": "rust",
"attribution": "Rust",
"explanation": "The ? operator returns early on Err, converting the error type through From. It is what keeps error handling from nesting.",
"content": "let config: Config = toml::from_str(&fs::read_to_string(path)?)?;"
},
{
"category": "programming",
"language": "rust",
"attribution": "Rust",
"explanation": "entry().or_insert_with() looks the key up once. The obvious contains_key-then-insert hashes it twice.",
"content": "*counts.entry(word).or_insert(0) += 1;"
},
{
"category": "programming",
"language": "clike",
"attribution": "SQL",
"explanation": "A window function ranks rows within each partition without collapsing them, which a GROUP BY cannot do.",
"content": "SELECT user_id, wpm, RANK() OVER (PARTITION BY mode ORDER BY wpm DESC) AS rank FROM results;"
},
{
"category": "programming",
"language": "clike",
"attribution": "SQL",
"explanation": "EXPLAIN ANALYZE runs the query and reports what the planner actually did, not what it guessed it would do.",
"content": "EXPLAIN ANALYZE SELECT * FROM test_results WHERE mode_key = 'time-30' ORDER BY wpm DESC LIMIT 50;"
},
{
"category": "programming",
"content": "const grouped = items.reduce((acc, item) => ({ ...acc, [item.type]: [...(acc[item.type] ?? []), item] }), {});",
"attribution": "JavaScript",
"explanation": "Groups a list by one field. The nullish coalescing operator supplies an empty array the first time a type is seen, so no separate initialisation step is needed.",
"language": "javascript"
},
{
"category": "programming",
"content": "let counts: HashMap<&str, usize> = text.split_whitespace().fold(HashMap::new(), |mut m, w| { *m.entry(w).or_insert(0) += 1; m });",
"attribution": "Rust",
"explanation": "entry returns a view into the slot for a key whether or not it exists. or_insert fills it on first sight, and the star dereferences that slot so it can be incremented in place.",
"language": "rust"
},
{
"category": "programming",
"content": "with open(path, encoding='utf-8') as fh: rows = [line.rstrip('\\n').split('\\t') for line in fh if line.strip()]",
"attribution": "Python",
"explanation": "The with block closes the file even if the loop raises. Naming the encoding matters: without it Python uses the machine's locale, so the same file can parse differently elsewhere.",
"language": "python"
},
{
"category": "programming",
"content": "impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, \"{}: {}\", self.kind, self.detail) } }",
"attribution": "Rust",
"explanation": "Implementing Display is what lets a type be printed with the plain brace form. The formatter carries the width and precision the caller asked for.",
"language": "rust"
},
{
"category": "programming",
"content": "export const debounce = (fn, ms) => { let t; return (...args) => { clearTimeout(t); t = setTimeout(() => fn(...args), ms); }; };",
"attribution": "JavaScript",
"explanation": "The timer handle lives in the closure, so every returned function keeps its own. Each call cancels the pending one, and only a pause longer than ms lets the work through.",
"language": "javascript"
},
{
"category": "programming",
"content": "SELECT u.name, COUNT(o.id) AS orders FROM users u LEFT JOIN orders o ON o.user_id = u.id GROUP BY u.id, u.name HAVING COUNT(o.id) > 5;",
"attribution": "SQL",
"explanation": "A LEFT JOIN keeps users with no orders, and HAVING filters on the aggregate, which WHERE cannot do because WHERE runs before the grouping.",
"language": "clike"
},
{
"category": "programming",
"content": "def chunked(seq, n): return [seq[i:i + n] for i in range(0, len(seq), n)]",
"attribution": "Python",
"explanation": "Slicing past the end of a sequence is not an error in Python, it simply returns what is there, so the final chunk needs no special case.",
"language": "python"
},
{
"category": "programming",
"content": "match value { Some(n) if n > 0 => n, Some(_) => 0, None => return Err(Error::Missing) }",
"attribution": "Rust",
"explanation": "The if after a pattern is a match guard. It narrows an arm without a nested conditional, and the compiler still checks that every case is covered.",
"language": "rust"
},
{
"category": "programming",
"content": "const sorted = [...items].sort((a, b) => a.score - b.score || a.name.localeCompare(b.name));",
"attribution": "JavaScript",
"explanation": "sort mutates, so the spread makes a copy first. The logical or supplies a second comparison used only when the scores are equal.",
"language": "javascript"
},
{
"category": "programming",
"content": "async fn fetch_all(urls: Vec<String>) -> Vec<Result<String, Error>> { futures::future::join_all(urls.into_iter().map(fetch)).await }",
"attribution": "Rust",
"explanation": "join_all drives every future at once on one task and waits for all of them, rather than awaiting each in turn, which would make the requests sequential.",
"language": "rust"
}
]
|