-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode-snippets.ts
More file actions
258 lines (255 loc) · 38.2 KB
/
code-snippets.ts
File metadata and controls
258 lines (255 loc) · 38.2 KB
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
export type Chapter = {
title: string;
code: string | null;
};
export type Language = {
name: string;
chapters: Chapter[];
};
export const codeSnippets: Record<string, Language> = {
typing: {
name: "Typing Skills",
chapters: [
{ title: "Easy 1", code: `The sun is shining and the birds are singing. It's a beautiful day to go for a walk in the park. Many people enjoy the simple pleasures of life.` },
{ title: "Easy 2", code: `My friend and I are going to the movies tonight. We are excited to see the new film. Popcorn is a must-have snack for any movie.` },
{ title: "Easy 3", code: `Cooking can be a fun and relaxing hobby. I like to try new recipes on the weekend. My favorite dish to make is pasta with fresh tomatoes.` },
{ title: "Easy 4", code: `Reading a good book is a great way to unwind. I have a collection of classic novels. The library is a wonderful place to discover new authors.` },
{ title: "Easy 5", code: `Music can lift your spirits and change your mood. I enjoy listening to a wide variety of genres. A catchy song can stay in your head for days.` },
{ title: "Easy 6", code: `Learning a new skill takes time and patience. Practice is the key to improvement. It is rewarding to see your progress over time.` },
{ title: "Easy 7", code: `Traveling allows you to experience different cultures. I dream of visiting far-off lands. Every journey begins with a single step.` },
{ title: "Easy 8", code: `Keeping a journal can help you organize your thoughts. Writing down your ideas is a good habit. It's interesting to look back at old entries.` },
{ title: "Easy 9", code: `Spending time with family and friends is important. Strong relationships are built on trust and love. Laughter is the best medicine for the soul.` },
{ title: "Easy 10", code: `A healthy diet and regular exercise are vital for well-being. Eating fresh fruits and vegetables is good for you. A morning run can energize your day.` },
{ title: "Moderate 1", code: `The quick brown fox jumps over the lazy dog. This sentence contains every letter of the alphabet. It's a classic pangram used for typing practice.` },
{ title: "Moderate 2", code: `Technology has revolutionized the way we live and work, offering both convenience and new challenges. We must adapt to keep up with the pace of innovation.` },
{ title: "Moderate 3", code: `Juggling multiple tasks requires strong organizational skills. Prioritizing your work and managing your time effectively are crucial for success.` },
{ title: "Moderate 4", code: `The sphinx of black quartz, judge my vow. This pangram is more complex and poetic. It tests your ability to type less common letter combinations.` },
{ title: "Moderate 5", code: `Climate change is a significant global issue that requires immediate attention. International cooperation is essential to find sustainable solutions.` },
{ title: "Moderate 6", code: `The history of the ancient world is filled with fascinating stories of empires, myths, and legends. Exploring these tales can be quite enlightening.` },
{ title: "Moderate 7", code: `Creativity is the ability to generate or recognize ideas, alternatives, or possibilities that may be useful in solving problems, communicating with others.` },
{ title: "Moderate 8", code: `Pack my box with five dozen liquor jugs. This is another popular pangram. It is short but effective for practicing all the letters.` },
{ title: "Moderate 9", code: `The pursuit of knowledge is a lifelong journey. Every day presents an opportunity to learn something new and expand your understanding of the world.` },
{ title: "Moderate 10", code: `Problem-solving involves defining a problem, determining the cause, identifying, prioritizing, and selecting alternatives for a solution.` },
{ title: "Hard 1", code: `~ \` ! @ # $ % ^ & * ( ) _ - + = { } [ ] | \\ : ; " ' < > , . ? /` },
{ title: "Hard 2", code: `The function's signature is func(arg1, arg2) -> { return arg1 + arg2; }. Pay attention to the syntax: parentheses(), curly braces{}, and arrows->.` },
{ title: "Hard 3", code: `My password is "p@$$w0rd_!@#". It's a mix of special characters, numbers, and letters for security. Remember to use strong, unique passwords.` },
{ title: "Hard 4", code: `The file path is C:\\Users\\Default\\Documents. Notice the backslashes (\\) and colons (:). This is a common format in Windows.` },
{ title: "Hard 5", code: `The JSON object is {"key": "value", "number": 123}. It uses quotes, colons, and commas to structure data. This is a popular data interchange format.` },
{ title: "Hard 6", code: `SQL queries like SELECT * FROM users WHERE id = 1; often contain special characters. Semicolons (;), asterisks (*), and equal signs (=) are common.` },
{ title: "Hard 7", code: `Regular expressions such as /^[a-z0-9_-]{3,16}$/ are powerful but complex. They use characters like ^, $, -, and {}.` },
{ title: "Hard 8", code: `HTML tags like <div class="container"> require angle brackets and quotes. Attributes are assigned with an equals sign.` },
{ title: "Hard 9", code: `You can reach me at 'user.name+alias@example.com'. Email addresses can contain periods, plus signs, and the at symbol (@).` },
{ title: "Hard 10", code: `The calculation is ( ( 5 + 3 ) * 2 ) / 4 = 4. Parentheses are used to control the order of operations in mathematics.` }
]
},
javascript: {
name: "JavaScript",
chapters: [
{ title: "Chapter 1: Variables", code: `const name = "CodeType";\nlet version = 1.0;\nvar isAwesome = true;\n\nfunction greet(user) {\n console.log("Hello, " + user);\n}\n\ngreet(name);` },
{ title: "Chapter 2: Functions", code: `function add(a, b) {\n return a + b;\n}\n\nconst multiply = (x, y) => {\n return x * y;\n};\n\nconst result = add(5, 10);\nconsole.log(multiply(result, 2));` },
{ title: "Chapter 3: Arrays", code: `const numbers = [1, 2, 3, 4, 5];\nconst squares = numbers.map(n => n * n);\n\nconst evenSquares = squares.filter(sq => {\n return sq % 2 === 0;\n});\n\nconsole.log(evenSquares);` },
{ title: "Chapter 4: Objects", code: `const person = {\n firstName: "John",\n lastName: "Doe",\n age: 30,\n fullName: function() {\n return this.firstName + " " + this.lastName;\n }\n};\n\nconsole.log(person.fullName());` },
{ title: "Chapter 5: Conditionals", code: `let temperature = 25;\n\nif (temperature > 30) {\n console.log("It's a hot day!");\n} else if (temperature > 20) {\n console.log("It's a pleasant day.");\n} else {\n console.log("It's a bit chilly.");\n}` },
{ title: "Chapter 6: Loops", code: `for (let i = 0; i < 5; i++) {\n console.log("Iteration: " + i);\n}\n\nconst colors = ['red', 'green', 'blue'];\nfor (const color of colors) {\n console.log(color);\n}` },
{ title: "Chapter 7: DOM Manipulation", code: `document.addEventListener('DOMContentLoaded', () => {\n const container = document.getElementById('container');\n const p = document.createElement('p');\n p.textContent = 'This was added by JavaScript!';\n container.appendChild(p);\n});` },
{ title: "Chapter 8: Events", code: `const button = document.querySelector('#myButton');\n\nbutton.addEventListener('click', () => {\n alert('Button was clicked!');\n});` },
{ title: "Chapter 9: Async/Await", code: `async function fetchData() {\n try {\n const response = await fetch('https://api.example.com/data');\n const data = await response.json();\n console.log(data);\n } catch (error) {\n console.error('Fetching data failed:', error);\n }\n}` },
{ title: "Chapter 10: Promises", code: `const myPromise = new Promise((resolve, reject) => {\n setTimeout(() => {\n resolve("Success!");\n }, 2000);\n});\n\nmyPromise.then(message => {\n console.log(message);\n});` },
{ title: "Chapter 11: Classes", code: `class Animal {\n constructor(name) {\n this.name = name;\n }\n\n speak() {\n console.log(this.name + ' makes a sound.');\n }\n}\n\nconst dog = new Animal('Dog');\ndog.speak();` },
{ title: "Chapter 12: Modules", code: `// utils.js\nexport const PI = 3.14159;\nexport function double(n) { return n * 2; }\n\n// main.js\nimport { PI, double } from './utils.js';\nconsole.log(double(PI));` },
{ title: "Chapter 13: Destructuring", code: `const user = { id: 1, name: 'Satoshi' };\nconst { id, name } = user;\n\nconst numbers = [10, 20, 30, 40];\nconst [first, second] = numbers;` },
{ title: "Chapter 14: Spread & Rest", code: `const arr1 = [1, 2, 3];\nconst arr2 = [...arr1, 4, 5];\n\nfunction sum(...args) {\n return args.reduce((acc, val) => acc + val, 0);\n}\nconsole.log(sum(1, 2, 3, 4));` },
{ title: "Chapter 15: Template Literals", code: `const framework = 'React';\nconst library = 'Next.js';\n\nconst sentence = \`We are using \${framework} with \${library}.\`;\nconsole.log(sentence);` },
{ title: "Chapter 16: Array Reduce", code: `const items = [ { price: 10 }, { price: 20 }, { price: 5 } ];\nconst total = items.reduce((sum, item) => sum + item.price, 0);\nconsole.log('Total price:', total);` },
{ title: "Chapter 17: Closures", code: `function createCounter() {\n let count = 0;\n return function() {\n count++;\n return count;\n };\n}\n\nconst counter = createCounter();\nconsole.log(counter());` },
{ title: "Chapter 18: Prototypal Inheritance", code: `function Person(name) {\n this.name = name;\n}\n\nPerson.prototype.greet = function() {\n console.log('Hello, ' + this.name);\n};\n\nconst alice = new Person('Alice');\nalice.greet();` },
{ title: "Chapter 19: Fetch API", code: `fetch('https://jsonplaceholder.typicode.com/todos/1')\n .then(response => response.json())\n .then(json => console.log(json))\n .catch(error => console.error('Error:', error));` },
{ title: "Chapter 20: Local Storage", code: `localStorage.setItem('username', 'test-user');\nconst username = localStorage.getItem('username');\n\nif (username) {\n console.log('Welcome back, ' + username);\n}` },
{ title: "Chapter 21: Error Handling", code: `try {\n let result = riskyOperation();\n console.log(result);\n} catch (error) {\n console.error('An error occurred:', error.message);\n} finally {\n console.log('Cleanup code runs here.');\n}` },
{ title: "Chapter 22: Regular Expressions", code: `const text = 'The rain in Spain stays mainly in the plain.';\nconst regex = /ain/g;\nconst matches = text.match(regex);\nconsole.log(matches);` },
{ title: "Chapter 23: Set", code: `const letters = new Set(['a', 'b', 'c', 'a']);\nletters.add('d');\n\nfor (const letter of letters) {\n console.log(letter);\n}` },
{ title: "Chapter 24: Map", code: `const userRoles = new Map();\nuserRoles.set('admin', 'Full access');\nuserRoles.set('editor', 'Can edit content');\n\nconsole.log(userRoles.get('admin'));` },
{ title: "Chapter 25: JSON", code: `const book = { title: '1984', author: 'George Orwell' };\nconst jsonString = JSON.stringify(book);\nconst bookObject = JSON.parse(jsonString);\nconsole.log(bookObject.title);` },
{ title: "Chapter 26: Web Workers", code: `// worker.js\nself.onmessage = function(e) {\n const result = e.data * 2;\n self.postMessage(result);\n}\n\n// main.js\nconst myWorker = new Worker('worker.js');` },
{ title: "Chapter 27: Generators", code: `function* numberGenerator() {\n yield 1;\n yield 2;\n yield 3;\n}\n\nconst gen = numberGenerator();\nconsole.log(gen.next().value);` },
{ title: "Chapter 28: Symbols", code: `const idSymbol = Symbol('id');\nconst userObject = {\n name: 'developer',\n [idSymbol]: 123\n};\n\nconsole.log(userObject[idSymbol]);` },
{ title: "Chapter 29: Proxy", code: `const target = { message: 'hello' };\nconst handler = {\n get: function(target, prop) {\n return prop in target ? target[prop] : 'default';\n }\n};\n\nconst proxy = new Proxy(target, handler);` },
{ title: "Chapter 30: Internationalization API", code: `const number = 123456.789;\n\nconsole.log(new Intl.NumberFormat('de-DE').format(number));\n\nconst date = new Date();\nconsole.log(new Intl.DateTimeFormat('en-GB').format(date));` }
],
},
python: {
name: "Python",
chapters: [
{ title: "Chapter 1: Hello World", code: `def main():\n name = "Python"\n print(f"Hello, {name}!")\n\nif __name__ == "__main__":\n main()` },
{ title: "Chapter 2: Lists", code: `numbers = [1, 2, 3, 4, 5]\nsquared = [num**2 for num in numbers]\n\nfor s in squared:\n if s > 10:\n print(s)` },
{ title: "Chapter 3: Dictionaries", code: `user = {\n "name": "Alice",\n "age": 25,\n "is_active": True\n}\n\nprint(f"{user['name']} is {user['age']} years old.")` },
{ title: "Chapter 4: Classes and Objects", code: `class Dog:\n def __init__(self, name):\n self.name = name\n\n def bark(self):\n return f"{self.name} says woof!"\n\nmydog = Dog("Rex")\nprint(mydog.bark())` },
{ title: "Chapter 5: File I/O", code: `with open("example.txt", "w") as f:\n f.write("Hello, file world!\\n")\n\nwith open("example.txt", "r") as f:\n content = f.read()\n print(content)` },
{ title: "Chapter 6: Modules", code: `import math\n\nprint(f"The value of pi is {math.pi}")\n\nradius = 5\narea = math.pi * (radius ** 2)\nprint(f"Area of circle: {area}")` },
{ title: "Chapter 7: Inheritance", code: `class Animal:\n def speak(self):\n raise NotImplementedError\n\nclass Cat(Animal):\n def speak(self):\n return "Meow"\n\nmy_cat = Cat()\nprint(my_cat.speak())` },
{ title: "Chapter 8: Exception Handling", code: `try:\n result = 10 / 0\nexcept ZeroDivisionError as e:\n print(f"Error: {e}")\nfinally:\n print("Execution complete.")` },
{ title: "Chapter 9: Tuples and Sets", code: `my_tuple = (1, 'apple', 3.14)\nmy_set = {1, 2, 3, 2, 1}\n\nprint(my_tuple[1])\nprint(my_set)` },
{ title: "Chapter 10: Lambdas", code: `multiply = lambda x, y: x * y\nprint(multiply(5, 4))\n\npoints = [(1, 2), (4, 1), (3, 5)]\npoints.sort(key=lambda p: p[1])\nprint(points)` },
{ title: "Chapter 11: Decorators", code: `def my_decorator(func):\n def wrapper():\n print("Something is happening before.")\n func()\n print("Something is happening after.")\n return wrapper\n\n@my_decorator\ndef say_whee():\n print("Whee!")` },
{ title: "Chapter 12: Generators", code: `def countdown(n):\n while n > 0:\n yield n\n n -= 1\n\nfor i in countdown(5):\n print(i)` },
{ title: "Chapter 13: Regular Expressions", code: `import re\n\ntext = "The quick brown fox jumps over the lazy dog."\nmatch = re.search(r"brown (\\w+)", text)\nif match:\n print("Found:", match.group(1))` },
{ title: "Chapter 14: Working with JSON", code: `import json\n\ndata = {"name": "test", "value": 42}\njson_string = json.dumps(data)\nparsed_data = json.loads(json_string)` },
{ title: "Chapter 15: Datetime Module", code: `from datetime import datetime, timedelta\n\nnow = datetime.now()\nprint("Current time:", now)\nyesterday = now - timedelta(days=1)\nprint("Yesterday:", yesterday)` },
{ title: "Chapter 16: Virtual Environments", code: `python3 -m venv myenv\nsource myenv/bin/activate\n\npip install requests\ndeactivate` },
{ title: "Chapter 17: Concurrency with Threads", code: `import threading\n\ndef worker(num):\n print(f"Worker: {num}")\n\nthreads = []\nfor i in range(5):\n t = threading.Thread(target=worker, args=(i,))\n threads.append(t)\n t.start()` },
{ title: "Chapter 18: Asyncio", code: `import asyncio\n\nasync def main():\n print("Hello")\n await asyncio.sleep(1)\n print("...world!")\n\nasyncio.run(main())` },
{ title: "Chapter 19: Context Managers", code: `class ManagedFile:\n def __init__(self, filename):\n self.filename = filename\n\n def __enter__(self):\n self.file = open(self.filename, 'w')\n return self.file\n\n def __exit__(self, *args):\n if self.file:\n self.file.close()` },
{ title: "Chapter 20: Argparse for CLI", code: `import argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument("echo", help="echo the string")\nargs = parser.parse_args()\nprint(args.echo)` },
{ title: "Chapter 21: Unit Testing", code: `import unittest\n\ndef add(a, b):\n return a + b\n\nclass TestAdd(unittest.TestCase):\n def test_add(self):\n self.assertEqual(add(2, 3), 5)` },
{ title: "Chapter 22: Data Classes", code: `from dataclasses import dataclass\n\n@dataclass\nclass Point:\n x: float\n y: float\n\np = Point(1.0, 2.5)` },
{ title: "Chapter 23: Type Hinting", code: `def greeting(name: str) -> str:\n return "Hello " + name\n\npi: float = 3.14159` },
{ title: "Chapter 24: Itertools", code: `import itertools\n\nfor i in itertools.count(10, 2):\n if i > 20:\n break\n print(i)` },
{ title: "Chapter 25: Collections Module", code: `from collections import Counter\n\ncolors = ['red', 'blue', 'red', 'green', 'blue', 'blue']\ncolor_counts = Counter(colors)\nprint(color_counts)` },
{ title: "Chapter 26: Walrus Operator", code: `while (line := input("Enter text: ")) != "quit":\n print(f"You entered: {line}")` },
{ title: "Chapter 27: F-strings Advanced", code: `import datetime\n\nnow = datetime.datetime.now()\nprint(f"{now=:%Y-%m-%d %H:%M}")` },
{ title: "Chapter 28: Networking with Sockets", code: `import socket\n\nwith socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\n s.connect(("www.python.org", 80))` },
{ title: "Chapter 29: Interacting with APIs", code: `import requests\n\nresponse = requests.get('https://api.github.com')\nif response.status_code == 200:\n print('Success!')` },
{ title: "Chapter 30: Web Scraping with BeautifulSoup", code: `from bs4 import BeautifulSoup\nimport requests\n\nurl = 'https://news.ycombinator.com'\nresponse = requests.get(url)\n\nsoup = BeautifulSoup(response.text, 'html.parser')` }
],
},
html: {
name: "HTML",
chapters: [
{ title: "Chapter 1: Basic Structure", code: `<!DOCTYPE html>\n<html>\n<head>\n <title>My First Page</title>\n</head>\n<body>\n <h1>Welcome</h1>\n <p>This is a paragraph.</p>\n</body>\n</html>` },
{ title: "Chapter 2: Forms", code: `<form action="/submit" method="post">\n <label for="username">Username:</label>\n <input type="text" id="username" name="username">\n \n <button type="submit">Submit</button>\n</form>` },
{ title: "Chapter 3: Tables", code: `<table>\n <tr>\n <th>Firstname</th>\n <th>Lastname</th>\n </tr>\n <tr>\n <td>Peter</td>\n <td>Griffin</td>\n </tr>\n</table>` },
{ title: "Chapter 4: Lists", code: `<h2>Unordered List</h2>\n<ul>\n <li>Coffee</li>\n <li>Tea</li>\n</ul>\n\n<h2>Ordered List</h2>\n<ol>\n <li>First item</li>\n <li>Second item</li>\n</ol>` },
{ title: "Chapter 5: Images", code: `<img src="image.jpg" alt="An example image" width="500" height="300">` },
{ title: "Chapter 6: Links", code: `<a href="https://www.example.com">Visit Example.com</a>` },
{ title: "Chapter 7: Div and Span", code: `<div class="container">\n <p>This is a <span class="highlight">highlighted</span> word.</p>\n</div>` },
{ title: "Chapter 8: Semantic HTML", code: `<header>\n <h1>My Website</h1>\n</header>\n<nav>\n <a href="/">Home</a>\n</nav>\n<main>\n <article>\n <h2>Article Title</h2>\n </article>\n</main>\n<footer>\n <p>Copyright 2024</p>\n</footer>` },
{ title: "Chapter 9: Audio and Video", code: `<video controls width="250">\n <source src="/media/cc0-videos/flower.webm" type="video/webm">\n</video>\n\n<audio controls>\n <source src="horse.ogg" type="audio/ogg">\n</audio>` },
{ title: "Chapter 10: Iframe", code: `<iframe src="https://www.openstreetmap.org/export/embed.html" width="425" height="350"></iframe>` },
{ title: "Chapter 11: Canvas", code: `<canvas id="myCanvas" width="200" height="100" style="border:1px solid #000;"></canvas>` },
{ title: "Chapter 12: SVG", code: `<svg width="100" height="100">\n <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />\n</svg>` },
{ title: "Chapter 13: Details and Summary", code: `<details>\n <summary>Click to see details</summary>\n <p>Here are some details you can now see.</p>\n</details>` },
{ title: "Chapter 14: Figure and Figcaption", code: `<figure>\n <img src="pic_trulli.jpg" alt="Trulli" style="width:100%">\n <figcaption>Fig.1 - Trulli, Puglia, Italy.</figcaption>\n</figure>` },
{ title: "Chapter 15: Input Types", code: `<input type="date">\n<input type="color">\n<input type="range" min="0" max="100">\n<input type="file">` },
{ title: "Chapter 16: Data Attributes", code: `<div id="user" data-id="12345" data-user="johndoe">John Doe</div>` },
{ title: "Chapter 17: Meta Tags", code: `<head>\n <meta charset="UTF-8">\n <meta name="description" content="Free Web tutorials">\n <meta name="keywords" content="HTML, CSS, JavaScript">\n <meta name="author" content="John Doe">\n <meta name="viewport" content="width=device-width, initial-scale=1.0">\n</head>` },
{ title: "Chapter 18: Select Element", code: `<label for="cars">Choose a car:</label>\n<select id="cars" name="cars">\n <option value="volvo">Volvo</option>\n <option value="saab">Saab</option>\n</select>` },
{ title: "Chapter 19: Textarea", code: `<textarea name="message" rows="10" cols="30">\n The cat was playing in the garden.\n</textarea>` },
{ title: "Chapter 20: Button Element", code: `<button type="button" onclick="alert('Hello world!')">Click Me</button>` },
{ title: "Chapter 21: Label Element", code: `<label for="fname">First name:</label><br>\n<input type="text" id="fname" name="fname"><br>` },
{ title: "Chapter 22: Fieldset and Legend", code: `<fieldset>\n <legend>Personalia:</legend>\n <label for="fname">First name:</label>\n <input type="text" id="fname" name="fname">\n</fieldset>` },
{ title: "Chapter 23: Datalist", code: `<input list="browsers">\n<datalist id="browsers">\n <option value="Edge">\n <option value="Firefox">\n <option value="Chrome">\n</datalist>` },
{ title: "Chapter 24: Progress and Meter", code: `<label for="file">Downloading progress:</label>\n<progress id="file" value="32" max="100"> 32% </progress>\n\n<meter id="disk_c" value="2" min="0" max="10">2 out of 10</meter>` },
{ title: "Chapter 25: Blockquote", code: `<blockquote cite="http://www.worldwildlife.org/who/index.html">\n For 50 years, WWF has been protecting the future of nature.\n</blockquote>` },
{ title: "Chapter 26: Abbreviation", code: `<p>The <abbr title="World Health Organization">WHO</abbr> was founded in 1948.</p>` },
{ title: "Chapter 27: Address", code: `<address>\n Written by John Doe.<br>\n Visit us at:<br>\n Example.com\n</address>` },
{ title: "Chapter 28: Time Element", code: `<p>Open from <time>10:00</time> to <time>21:00</time> every weekday.</p>` },
{ title: "Chapter 29: Code and Pre", code: `<pre>\n<code>\nfunction hello() {\n console.log("Hello");\n}\n</code>\n</pre>` },
{ title: "Chapter 30: Template Tag", code: `<template>\n <h2>Flower</h2>\n <img src="img_white_flower.jpg" width="214" height="204">\n</template>` }
],
},
cpp: {
name: "C++",
chapters: [
{ title: "Chapter 1: Basic I/O", code: `#include <iostream>\n#include <string>\n\nint main() {\n std::string name;\n std::cout << "Enter your name: ";\n std::cin >> name;\n std::cout << "Hello, " << name << "!" << std::endl;\n return 0;\n}` },
{ title: "Chapter 2: Vectors", code: `#include <iostream>\n#include <vector>\n\nint main() {\n std::vector<int> numbers = {1, 2, 3, 4, 5};\n for (int num : numbers) {\n std::cout << num << " ";\n }\n std::cout << std::endl;\n return 0;\n}` },
{ title: "Chapter 3: Functions", code: `#include <iostream>\n\nint add(int a, int b) {\n return a + b;\n}\n\nint main() {\n int result = add(10, 20);\n std::cout << "The sum is: " << result << std::endl;\n return 0;\n}` },
{ title: "Chapter 4: Classes", code: `class Rectangle {\n int width, height;\n public:\n void set_values(int,int);\n int area() {return width*height;}\n};\n\nvoid Rectangle::set_values(int x, int y) {\n width = x;\n height = y;\n}` },
{ title: "Chapter 5: Pointers", code: `#include <iostream>\n\nint main() {\n int var = 20;\n int *ip;\n ip = &var;\n\n std::cout << "Address: " << ip << std::endl;\n std::cout << "Value: " << *ip << std::endl;\n return 0;\n}` },
{ title: "Chapter 6: References", code: `#include <iostream>\n\nint main () {\n int i = 5;\n int& r = i;\n r = 10;\n std::cout << "Value of i: " << i << std::endl;\n return 0;\n}` },
{ title: "Chapter 7: File I/O", code: `#include <fstream>\n#include <iostream>\n\nint main () {\n std::ofstream outfile("test.txt");\n outfile << "Writing to a file." << std::endl;\n outfile.close();\n return 0;\n}` },
{ title: "Chapter 8: Inheritance", code: `class Shape {\n public:\n void setWidth(int w) { width = w; }\n protected:\n int width;\n};\n\nclass Square: public Shape {\n public:\n int getArea() { return width * width; }\n};` },
{ title: "Chapter 9: Polymorphism", code: `class Animal {\n public:\n void animalSound() {\n std::cout << "The animal makes a sound \\n";\n }\n};\n\nclass Pig : public Animal {\n public:\n void animalSound() {\n std::cout << "The pig says: wee wee \\n";\n }\n};` },
{ title: "Chapter 10: Structs", code: `struct Person {\n std::string name;\n int age;\n};\n\nint main() {\n Person p1;\n p1.name = "Bjarne";\n p1.age = 73;\n}` },
{ title: "Chapter 11: Enums", code: `enum Color { RED, GREEN, BLUE };\n\nint main() {\n Color myColor = BLUE;\n if (myColor == BLUE) {\n std::cout << "It's blue!" << std::endl;\n }\n return 0;\n}` },
{ title: "Chapter 12: Templates", code: `template <typename T>\nT const& max(T const& a, T const& b) {\n return a < b ? b : a;\n}\n\nint main() {\n std::cout << max(5, 10) << std::endl;\n}` },
{ title: "Chapter 13: Namespaces", code: `namespace first_space {\n void func() {\n std::cout << "Inside first_space" << std::endl;\n }\n}\n\nusing namespace first_space;\nint main() { func(); }` },
{ title: "Chapter 14: Standard Template Library (STL)", code: `#include <map>\n\nint main() {\n std::map<char, int> mymap;\n mymap['a'] = 10;\n mymap['b'] = 20;\n std::cout << "Value of 'a' is " << mymap['a'] << std::endl;\n}` },
{ title: "Chapter 15: Exception Handling", code: `#include <iostream>\n\nint main() {\n try {\n throw 20;\n } catch (int e) {\n std::cout << "An exception occurred. " << e << std::endl;\n }\n return 0;\n}` },
{ title: "Chapter 16: Operator Overloading", code: `class Box {\n public:\n Box operator+(const Box& b) {\n Box box;\n box.length = this->length + b.length;\n return box;\n }\n private:\n double length;\n};` },
{ title: "Chapter 17: Smart Pointers", code: `#include <memory>\n\nint main() {\n std::unique_ptr<int> p1(new int(5));\n std::shared_ptr<int> p2 = std::make_shared<int>(10);\n return 0;\n}` },
{ title: "Chapter 18: Multithreading", code: `#include <thread>\n\nvoid foo() {\n // do something\n}\n\nint main() {\n std::thread t1(foo);\n t1.join();\n return 0;\n}` },
{ title: "Chapter 19: Lambda Functions", code: `#include <vector>\n#include <algorithm>\n\nint main() {\n std::vector<int> v {4, 1, 3, 5, 2};\n std::sort(v.begin(), v.end(), [](int a, int b) {\n return a < b;\n });\n}` },
{ title: "Chapter 20: Ranged-based for loop", code: `int my_numbers[] = {1, 2, 3, 4, 5};\nfor (int i : my_numbers)\n{\n std::cout << i << " ";\n}` },
{ title: "Chapter 21: Auto keyword", code: `auto x = 5; // x is an int\nauto y = 3.14; // y is a double\nauto z = "hello"; // z is a const char*` },
{ title: "Chapter 22: Constexpr", code: `constexpr int square(int x) {\n return x * x;\n}\n\nint main() {\n const int val = square(5);\n return 0;\n}` },
{ title: "Chapter 23: Type Casting", code: `double d = 3.14;\nint i = static_cast<int>(d);\n\nclass Base {};\nclass Derived : public Base {};\nDerived* d_ptr = new Derived();\nBase* b_ptr = dynamic_cast<Base*>(d_ptr);` },
{ title: "Chapter 24: Preprocessor Directives", code: `#define PI 3.14159\n\n#ifdef DEBUG\n std::cout << "Debugging is enabled." << std::endl;\n#endif` },
{ title: "Chapter 25: Virtual Functions", code: `class Base {\npublic:\n virtual void print() { std::cout << "Base" << std::endl; }\n};\n\nclass Derived : public Base {\npublic:\n void print() override { std::cout << "Derived" << std::endl; }\n};` },
{ title: "Chapter 26: Friend Functions", code: `class MyClass {\n int secret;\n friend void reveal(MyClass&);\n};\n\nvoid reveal(MyClass& obj) {\n std::cout << obj.secret;\n}` },
{ title: "Chapter 27: Filesystem Library", code: `#include <filesystem>\nnamespace fs = std::filesystem;\n\nint main() {\n fs::path p = "/";\n std::cout << p << " exists: " << fs::exists(p) << std::endl;\n}` },
{ title: "Chapter 28: Chrono Library", code: `#include <chrono>\n#include <thread>\n\nint main() {\n auto start = std::chrono::high_resolution_clock::now();\n std::this_thread::sleep_for(std::chrono::seconds(1));\n auto end = std::chrono::high_resolution_clock::now();\n}` },
{ title: "Chapter 29: Move Semantics", code: `std::string str = "Hello";\nstd::vector<std::string> v;\nv.push_back(std::move(str)); // efficiently move str into v` },
{ title: "Chapter 30: Concurrency with Futures", code: `#include <future>\n\nint find_the_answer() { return 42; }\n\nint main() {\n std::future<int> the_answer = std::async(find_the_answer);\n std::cout << "The answer is " << the_answer.get() << std::endl;\n}` }
],
},
typescript: {
name: "TypeScript",
chapters: [
{ title: "Chapter 1: Basic Types", code: `let isDone: boolean = false;\nlet decimal: number = 6;\nlet color: string = "blue";\nlet list: number[] = [1, 2, 3];` },
{ title: "Chapter 2: Interfaces", code: `interface Person {\n name: string;\n age: number;\n}\n\nfunction greet(person: Person) {\n return "Hello, " + person.name;\n}` },
{ title: "Chapter 3: Classes", code: `class Greeter {\n greeting: string;\n constructor(message: string) {\n this.greeting = message;\n }\n greet() {\n return "Hello, " + this.greeting;\n }\n}` },
{ title: "Chapter 4: Enums", code: `enum Color {Red, Green, Blue}\nlet c: Color = Color.Green;` },
{ title: "Chapter 5: Generics", code: `function identity<T>(arg: T): T {\n return arg;\n}\n\nlet output = identity<string>("myString");` },
{ title: "Chapter 6: Type Aliases", code: `type Point = {\n x: number;\n y: number;\n};\n\nfunction logPoint(p: Point) {\n console.log(p.x, p.y);\n}` },
{ title: "Chapter 7: Union Types", code: `function padLeft(value: string, padding: string | number) {\n // ...\n}` },
{ title: "Chapter 8: Intersection Types", code: `interface Draggable { drag: () => void; }\ninterface Resizable { resize: () => void; }\n\ntype UIElement = Draggable & Resizable;` },
{ title: "Chapter 9: Literal Types", code: `let x: "hello";\nx = "hello";\n// x = "howdy"; // Error` },
{ title: "Chapter 10: Modules", code: `export const pi = 3.14;\n\nimport { pi } from "./math";\nconsole.log(pi);` },
{ title: "Chapter 11: Decorators", code: `@sealed\nclass BugReport {\n type = "report";\n title: string;\n\n constructor(t: string) {\n this.title = t;\n }\n}` },
{ title: "Chapter 12: Mixins", code: `class Disposable { isDisposed: boolean; }\nclass Activatable { isActive: boolean; }\n\nclass SmartObject implements Disposable, Activatable { }` },
{ title: "Chapter 13: Namespaces", code: `namespace Validation {\n export interface StringValidator { isAcceptable(s: string): boolean; }\n}` },
{ title: "Chapter 14: Utility Types", code: `interface Todo { title: string; }\n\nconst todo: Readonly<Todo> = {\n title: "Delete inactive users",\n};` },
{ title: "Chapter 15: Advanced Types", code: `type Easing = "ease-in" | "ease-out" | "ease-in-out";\nclass UIElement {\n animate(options: { easing: Easing }) {}\n}` },
{ title: "Chapter 16: Async/Await", code: `async function getTodo() {\n const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');\n const todo: Todo = await response.json();\n return todo;\n}` },
{ title: "Chapter 17: Conditional Types", code: `type Check<T> = T extends string ? boolean : number;\ntype A = Check<string>; // boolean\ntype B = Check<number>; // number` },
{ title: "Chapter 18: Mapped Types", code: `type Readonly<T> = { readonly [P in keyof T]: T[P]; };` },
{ title: "Chapter 19: Type Guards", code: `function isFish(pet: Fish | Bird): pet is Fish {\n return (pet as Fish).swim !== undefined;\n}` },
{ title: "Chapter 20: Discriminated Unions", code: `interface Square { kind: "square"; size: number; }\ninterface Circle { kind: "circle"; radius: number; }\ntype Shape = Square | Circle;` },
{ title: "Chapter 21: Never Type", code: `function error(message: string): never {\n throw new Error(message);\n}` },
{ title: "Chapter 22: Index Signatures", code: `interface StringArray {\n [index: number]: string;\n}\nconst myArray: StringArray = ["Bob", "Fred"];` },
{ title: "Chapter 23: Keyof Operator", code: `type PointKeys = keyof Point; // "x" | "y"` },
{ title: "Chapter 24: Typeof Operator", code: `let s = "hello";\nlet n: typeof s; // n is a string` },
{ title: "Chapter 25: Tuple Types", code: `let x: [string, number];\nx = ["hello", 10];` },
{ title: "Chapter 26: Ambient Declarations", code: `declare var jQuery: (selector: string) => any;` },
{ title: "Chapter 27: Project References", code: `// tsconfig.json\n{\n "references": [\n { "path": "../common" }\n ]\n}` },
{ title: "Chapter 28: Declaration Merging", code: `interface Box {\n height: number;\n width: number;\n}\ninterface Box {\n scale: number;\n}` },
{ title: "Chapter 29: ts-ignore", code: `// @ts-ignore\nconst value: string = 123; // This will not cause a compile error` },
{ title: "Chapter 30: JSDoc Support", code: `/**\n * @param {string} name The name of the person to greet.\n */\nfunction greet(name) {\n console.log(\`Hello, \${name}!\`);\n}` }
],
},
c: {
name: "C",
chapters: [
{ title: "Chapter 1: Hello World", code: `#include <stdio.h>\n\nint main() {\n printf("Hello, World!\\n");\n return 0;\n}` },
{ title: "Chapter 2: Variables and Types", code: `int myNum = 5; // Integer\nfloat myFloatNum = 5.99; // Floating point number\nchar myLetter = 'D'; // Character` },
{ title: "Chapter 3: Arrays", code: `int myNumbers[] = {25, 50, 75, 100};\nprintf("%d", myNumbers[0]);` },
{ title: "Chapter 4: Pointers", code: `int myAge = 43;\nint* ptr = &myAge;\nprintf("%p\\n", (void*)ptr);\nprintf("%d\\n", *ptr);` },
{ title: "Chapter 5: Strings", code: `char greetings[] = "Hello World!";\nprintf("%s", greetings);` },
{ title: "Chapter 6: User Input", code: `int myNum;\nprintf("Type a number: ");\nscanf("%d", &myNum);` },
{ title: "Chapter 7: Conditionals", code: `if (20 > 18) {\n printf("20 is greater than 18");\n}` },
{ title: "Chapter 8: Loops", code: `int i;\nfor (i = 0; i < 5; i++) {\n printf("%d\\n", i);\n}` },
{ title: "Chapter 9: Functions", code: `void myFunction() {\n printf("I just got executed!");\n}\n\nint main() {\n myFunction();\n return 0;\n}` },
{ title: "Chapter 10: Structs", code: `struct myStructure {\n int myNum;\n char myLetter;\n};\n\nint main() {\n struct myStructure s1;\n return 0;\n}` },
{ title: "Chapter 11: File Handling", code: `FILE *fptr;\nfptr = fopen("filename.txt", "w");\nfprintf(fptr, "Some text");\nfclose(fptr);` },
{ title: "Chapter 12: Dynamic Memory Allocation", code: `#include <stdlib.h>\n\nint* ptr;\nptr = (int*) malloc(5 * sizeof(int));\nfree(ptr);` },
{ title: "Chapter 13: Enums", code: `enum Level {\n LOW,\n MEDIUM,\n HIGH\n};\n\nenum Level myVar = MEDIUM;` },
{ title: "Chapter 14: Preprocessor Directives", code: `#define PI 3.14159\n\n#include <stdio.h>` },
{ title: "Chapter 15: Header Files", code: `// myheader.h\nvoid my_function(void);\n\n// main.c\n#include "myheader.h"` },
{ title: "Chapter 16: Recursion", code: `int sum(int k) {\n if (k > 0) {\n return k + sum(k - 1);\n } else {\n return 0;\n }\n}` },
{ title: "Chapter 17: Bitwise Operators", code: `unsigned int a = 60; // 0011 1100\nunsigned int b = 13; // 0000 1101\nint c = a & b; // 0000 1100` },
{ title: "Chapter 18: Unions", code: `union Data {\n int i;\n float f;\n char str[20];\n};\n\nunion Data data;` },
{ title: "Chapter 19: Function Pointers", code: `void my_int_func(int x) {}\nvoid (*foo)(int);\nfoo = &my_int_func;` },
{ title: "Chapter 20: Static Variables", code: `void func(void) {\n static int i = 5; \n i++;\n}` },
{ title: "Chapter 21: Typedef", code: `typedef unsigned char BYTE;\nBYTE b1, b2;` },
{ title: "Chapter 22: Error Handling", code: `#include <errno.h>\n#include <string.h>\n\nFILE *fp = fopen("none.txt", "r");\nif (fp == NULL) {\n fprintf(stderr, "Error: %s\\n", strerror(errno));\n}` },
{ title: "Chapter 23: Command Line Arguments", code: `int main(int argc, char *argv[]) {\n printf("Argument count: %d\\n", argc);\n return 0;\n}` },
{ title: "Chapter 24: Macros", code: `#define MAX(x, y) (((x) > (y)) ? (x) : (y))` },
{ title: "Chapter 25: Volatile Keyword", code: `volatile int counter = 0;` },
{ title: "Chapter 26: Extern Keyword", code: `// first file: main.c\nint count;\n\n// second file: support.c\nextern int count;` },
{ title: "Chapter 27: Const Keyword", code: `const int LENGTH = 10;` },
{ title: "Chapter 28: Multithreading (pthreads)", code: `#include <pthread.h>\n\nvoid *myThreadFun(void *vargp) {\n return NULL;\n}\n\nint main() {\n pthread_t thread_id;\n pthread_create(&thread_id, NULL, myThreadFun, NULL);\n pthread_join(thread_id, NULL);\n}` },
{ title: "Chapter 29: Sockets", code: `#include <sys/socket.h>\n\nint sockfd = socket(AF_INET, SOCK_STREAM, 0);` },
{ title: "Chapter 30: Signal Handling", code: `#include <signal.h>\n\nvoid sighandler(int signum) {}\n\nsignal(SIGINT, sighandler);` }
],
},
};