Development questions, answered
318 short answers from 64 guides. Each set links to the full guide for the worked examples and the reasoning behind the answer.
.gitignore Patterns Explained: Rules, Negation and What to Ignore
How do I find which .gitignore rule is ignoring a file?
Run git check-ignore -v path/to/file. Git prints the ignore file, line number and pattern that matched, for example .gitignore:14:*.log, and prints nothing if the path is not ignored. Add --no-index to test a path that is already tracked, and use git status --ignored to list everything currently ignored in the working tree.
How do I keep an empty folder in a git repository?
Git does not track empty directories, so put a placeholder file such as .gitkeep in the folder. Then ignore the folder's contents with uploads/* and re-include the placeholder with !uploads/.gitkeep. Do not use uploads/, because excluding the directory itself stops git looking inside it, so the negation never applies.
What is the difference between .gitignore and .git/info/exclude?
A .gitignore file is committed and shared with everyone, and it takes precedence. The .git/info/exclude file is local to your clone and never committed, so it suits personal scratch files in one project. A third place, the file named by core.excludesFile, holds patterns such as editor and operating system junk that you never want in any repository.
Should .env files be in .gitignore?
Yes. The Node.js template ignores .env and .env.* but re-includes .env.example, so you can commit a template with dummy values for new developers. If a real secret was already committed, adding it to .gitignore is not enough because it stays in history: rotate the secret, then rewrite history with a tool such as git filter-repo if you must remove it.
Should Terraform state files be committed to git?
No. Terraform state files such as *.tfstate can contain secrets in plain text, so they belong in a remote backend and in .gitignore, along with .terraform/ and *.tfvars. The dependency lock file .terraform.lock.hcl and the *.tf configuration files should be committed, because they are needed to reproduce the setup.
301, 302, 307 or 308? Writing Redirects for Apache, Nginx, Netlify and Vercel
What is the difference between a 301 and a 308 redirect?
Both are permanent redirects, but after a 301 a client may change a POST into a GET, while a 308 requires it to repeat the request with the same method and body. For pages people click through to, 301 is fine and remains the most widely understood. For API endpoints, webhooks and form targets, use 308, or uploads will arrive as empty GETs.
When should I use a 303 See Other redirect?
Use 303 See Other after handling a form POST. It always means "now GET this other URL", so refreshing the result page does not resubmit the form. That differs from 307 and 308, which require the client to repeat the original method and body at the new URL.
How long should I keep redirects after a site migration?
Google recommends keeping redirects in place for as long as possible, generally at least a year, and pointing each old URL at its closest equivalent. Sending every old URL to the home page tends to be treated as a soft 404, which loses the value the redirects were meant to keep.
Why does an old 301 redirect still happen after I changed it?
Browsers cache permanent redirects. RFC 9110 lists 301 and 308 among the codes cacheable by default, and browsers often keep them until the cache is cleared, ignoring later changes on the server. To avoid a stuck mistake, test new rules with a 302, confirm them with curl -I, and switch to 301 or 308 once they are right.
Does permanent: true in vercel.json send a 301?
No. In vercel.json, permanent: true sends a 308 and permanent: false sends a 307. To send a 301 or 302, set statusCode instead, and never set both fields on the same rule. Vercel wildcards use path-to-regexp syntax such as :path*, and has conditions can match on host, header, cookie or query.
Base64, URL and HTML Encoding Explained (and When to Use Each)
How does Base64 encoding work?
Base64 takes input three bytes, or 24 bits, at a time and splits them into four 6-bit groups, each a number from 0 to 63 looked up in an alphabet of A-Z, a-z, 0-9, + and /. The text Hi!, bytes 72, 105 and 33, becomes the values 18, 6, 36 and 33, which encode as SGkh.
How much bigger is Base64 than the original data?
Base64 output is about 33% larger than the input, because every 3 bytes become 4 characters. When the input is not a multiple of three bytes, the output is padded with = so its length is a multiple of four, which also means you can tell roughly how long the original was from the encoded length.
Are Kubernetes Secrets encrypted?
No. Kubernetes Secrets are Base64-encoded, not encrypted, so a value such as password: cGFzc3dvcmQ= in a manifest can be decoded in one step by anyone with read access. Base64 is a reversible encoding with no key, and seeing it in a manifest can create a false sense of security.
What is the difference between encodeURIComponent and encodeURI?
encodeURIComponent escapes everything except letters, digits and - _ . ! ~ * ' ( ), so it suits a single value such as one query parameter. encodeURI leaves : / ? & = # alone so a complete URL keeps working. Using encodeURI on a parameter value leaves its & unescaped; in modern code, URLSearchParams handles query string encoding.
Why does btoa fail on emoji or Unicode text?
JavaScript's built-in btoa() works on binary strings where each character is one byte, so characters outside Latin-1, such as emoji or most non-European scripts, cannot be encoded directly. Convert the text to UTF-8 bytes first, typically with TextEncoder, then Base64-encode those bytes, and decode UTF-8 on the way back.
Beautifying and Minifying JavaScript Without Breaking It
What is the difference between js-beautify and Prettier?
js-beautify is a token-based formatter: it reads code as a stream of tokens without building a syntax tree, so it is fast, tolerates code that does not parse and offers many options. Prettier parses the file into a syntax tree and reprints it in one style, so the input must be valid, options are few and output is byte-identical across a team.
What is automatic semicolon insertion in JavaScript?
Automatic semicolon insertion (ASI) is the rule by which JavaScript treats some line breaks as statement terminators. When the parser meets a token that cannot continue the current statement after a line break, it inserts a semicolon. Restricted productions also forbid line breaks in certain spots, so return followed by a line break ends the statement there and returns undefined.
How do JavaScript minifiers rename variables?
JavaScript minifiers such as terser, esbuild and SWC rename variables through mangling: local variables and parameters are shortened to one or two letters, so function add(firstNumber, secondNumber) becomes function add(n,r). Only names whose scope the tool can see are renamed, while globals and object properties are left alone by default.
Is minifying JavaScript still worth it if the server uses gzip?
Yes, though the saving on the wire is smaller than the raw byte saving. Servers compress JavaScript with gzip or Brotli, which is very good at repetitive whitespace. Comments are text that compression cannot remove, so stripping them still helps: minifying lodash.js, which ships full JSDoc comments, cut it from 545,945 to 149,537 bytes.
Why can removing whitespace break JavaScript code?
Removing whitespace breaks JavaScript when gluing two tokens forms a new one. a + b can safely become a+b, but a + +b cannot become a++b, because ++ is a different operator. A careful minifier keeps one space between two words, between + and +, between a number and a dot, and between a division sign and a regular expression.
Blameless Incident Postmortems: A Template and How to Run One
What is the difference between a trigger and a root cause in a postmortem?
The trigger is the event that set off an incident, such as a config change that halved the database pool size. The root cause is whatever let that change ship unnoticed, such as no validation on pool settings or no alert on pool saturation. Fixing only the trigger leaves the next config change free to cause the same outage.
What is the difference between time to detect and time to mitigate?
Time to detect runs from the start of user impact to the first alert or report. Time to mitigate runs from the start of impact until users stop being hurt, often through a rollback, failover or feature flag rather than a fix. Slow detection points to monitoring gaps, while slow mitigation means the team lacks a fast, safe way to back out.
How do you write postmortem action items that actually get done?
Give each postmortem action item one owner who is a person, not a team, and a due date. Make it specific and checkable: "Alert when pool usage exceeds 80% for 5 minutes" can be finished, "improve monitoring" cannot. Balance items across detection, mitigation and prevention, copy them into the issue tracker, and review open items regularly until they close.
Which time zone should an incident timeline use?
An incident timeline should use one time zone, preferably UTC, stated at the top. Mixed time zones are the most common timeline error and make durations wrong by whole hours. Build the timeline from logs, alert history and the incident channel rather than memory, from the first symptom to the all-clear.
Who should facilitate a postmortem review meeting?
Someone other than the incident commander should facilitate the postmortem review. Hold it within a week, share the draft a day before so the meeting discusses it instead of reading it, and walk the timeline first, because most disagreements turn out to be about what happened when. Then cover root cause, then action items.
camelCase, snake_case, kebab-case: Naming Conventions Across Languages
What naming convention does Python use?
Python's PEP 8 recommends snake_case for functions and variables, such as user_name. Classes use PascalCase, as they do in Java, TypeScript and C#, and constants use SCREAMING_SNAKE_CASE, such as ORDER_TOTAL. Ruby and Rust follow the same pattern of snake_case for functions and variables and PascalCase for types.
Should JSON keys be camelCase or snake_case?
Either works for JSON keys, as long as an API chooses once and documents it. Google's JSON style guide recommends camelCase property names, while many Rails and Django APIs use snake_case. When a Python or Ruby backend meets a JavaScript frontend, convert at a single well-tested layer, such as a serializer, rather than ad hoc throughout the code.
Why use snake_case for database column names?
PostgreSQL folds unquoted identifiers to lower case, so a column created as createdAt without quotes becomes createdat. Using snake_case, such as created_at, for SQL tables and columns avoids having to quote every identifier forever, and it is the common convention in SQL schemas.
Why can't variable names use kebab-case?
Most C-family languages cannot use kebab-case for variable names because order-total parses as order minus total. Kebab-case comes from Lisp, where hyphens are legal in identifiers, and today it lives where names are strings: CSS properties and class names, HTML attributes, command-line flags like --dry-run, npm package names and URLs.
How should acronyms be written in camelCase and PascalCase?
Style guides disagree on acronyms in camelCase and PascalCase. Microsoft's .NET guidelines keep two-letter acronyms upper case, as in IOStream, and capitalize only the first letter of longer ones, as in XmlReader. Google's Java style guide treats acronyms as words, as in customerId. Go keeps initialisms consistently cased, as in userID and HTTPServer.
Coding Interview Prep: What Gets Scored and a 6-Week Plan
What do coding interviewers look for?
Most coding interview rubrics score four signals: problem solving, communication, code quality and verification. Interviewers want to see a candidate clarify inputs, explain a plan before coding, think aloud, write readable code with correct edge cases, and trace an example unprompted. A clean brute force with a clear explanation of the faster approach can pass, while a fast, silent, buggy solution often does not.
What are the most common coding interview patterns?
Coding interview problems come from a fairly small set of patterns: two pointers for pairs in sorted arrays, sliding window for contiguous substrings, binary search, heaps for top k, BFS for shortest paths with equal weights, DFS for connected regions, topological sort for dependencies, dynamic programming for counting or optimising over choices, and backtracking for combinations and permutations.
How do you solve two sum in O(n) time?
Solve two sum in O(n) time with a hash map. Loop through the array once, and for each value check whether target minus that value is already in the map; if it is, return both indices, otherwise store the value with its index. Checking before inserting is what makes duplicates like [3, 3] with target 6 work. It uses O(n) space.
What is the time complexity of building a heap?
Building a heap from n items at once is O(n), while inserting n items one at a time is O(n log n). Other complexities candidates often get wrong: quicksort is O(n log n) on average but O(n²) in the worst case, and hash map operations are O(1) on average but O(n) in the worst case when many keys collide.
How should I spend time in a 45 minute coding interview?
In a 45 minute coding interview, spend 2 to 3 minutes understanding the problem, 2 minutes on examples, 2 minutes naming a pattern, 3 to 5 minutes planning with complexity, 15 to 20 minutes coding, 5 minutes testing, and the rest discussing optimisations. The step people skip is planning, which is how candidates end up rewriting half their solution late.
Conventional Commits and the 50/72 Rule, Explained
Which conventional commit types change the version number?
Under Semantic Versioning, a feat commit triggers a minor release and a fix commit triggers a patch release, while perf usually means a patch. Types such as refactor, docs, style, test, build, ci and chore have no release effect. Any type marked with ! or a BREAKING CHANGE footer triggers a major release, which tools like semantic-release and release-please read automatically.
What is the 50/72 rule for git commit messages?
The 50/72 rule, from a 2008 note by Tim Pope, says to keep the commit summary to about 50 characters and wrap the body at 72. Git does not wrap messages itself, and git log indents the body by four spaces, so 72 plus 4 fits an 80-column terminal. Treat 50 as the target for the header and 72 as the hard limit.
How do I write a multi-line git commit message?
For a commit message with a header, body and footer, save it in a file and run git commit -F msg.txt, or run git commit and paste it into the editor git opens. You can also pass several -m flags, one per paragraph, and git joins them with blank lines. Avoid putting newlines inside a single quoted -m argument.
Should a commit message subject use past tense?
No, write commit subjects in the imperative, such as "fix the bug" rather than "Fixed the bug", as if completing the sentence "If applied, this commit will...". Past tense reads oddly in a changelog. Also leave off the trailing period, since the header is a title, and split the commit if the subject needs "and".
What is a scope in a conventional commit?
A scope is an optional name in parentheses after the type that says which part of the codebase a conventional commit touches, as in fix(auth), feat(billing) or docs(readme). Teams that use scopes usually keep a short agreed list so the generated changelog groups well. A change to a root file such as package.json can simply have no scope.
Converting CSV to JSON (and Back) Without Losing Data
What is RFC 4180?
RFC 4180, published in 2005, is the closest thing CSV has to a standard, though it is informational and documents common practice. Each record is on its own line ending in CRLF, an optional header line comes first, fields are separated by commas, fields containing commas, quotes or line breaks are enclosed in double quotes, and an embedded double quote is doubled.
How do you escape a double quote inside a CSV field?
In CSV, a double quote inside a field is escaped by doubling it, and the whole field must be enclosed in double quotes. So the value Said "hello" is written as "Said ""hello""". Fields containing commas or line breaks also need enclosing quotes, which is why splitting CSV on commas and newlines gets such rows wrong.
Why is my first CSV column name wrong after converting from Excel?
Excel's CSV UTF-8 export adds a byte order mark, three invisible bytes, at the start of the file, so the first header can come out as id instead of id. Code that looks up row.id then gets undefined. If only the first column misbehaves after a CSV to JSON conversion, the byte order mark is the likely cause.
What is CSV injection?
CSV injection happens when a cell in an exported CSV starts with =, +, - or @, and a spreadsheet application treats it as a formula when the file is opened. A malicious value such as =HYPERLINK(...) can then run in the context of whoever opens the export. OWASP recommends prefixing such cells with a single quote when generating CSV from untrusted input.
How can I check that a CSV to JSON conversion worked?
Check that row counts match, since extra objects mean line breaks inside fields split records, and that every object has the same keys. Confirm the first key has no byte order mark, that leading zeros survived in codes and IDs, and spot-check a row containing punctuation such as commas or quotes.
Cron Schedules Across Platforms: Crontab, GitHub, Kubernetes, AWS
How do I run a cron job on the first Monday of the month?
There is no five-field cron expression for the first Monday, because cron joins restricted day-of-month and day-of-week fields with OR. Instead, schedule 0 9 * * 1 and add a date test to the command so it only runs on days 1 to 7, escaping % as % inside the crontab. Quartz and EventBridge support 1#1, meaning first Monday, directly.
What does */10 mean in a cron expression?
A step such as */10 runs at every tenth value starting from the field's minimum. In the minute field it means 0, 10, 20, 30, 40 and 50, while in the day-of-month field it means 1, 11, 21 and 31. Classic Vixie cron does not accept a start without a range, such as 5/15, so write 5-59/15 to be safe.
How does daylight saving time affect cron jobs?
Classic cron runs in the daemon's local time zone, so in a zone with daylight saving, local times between roughly 01:00 and 03:00 can be skipped or repeated once a year, and implementations differ in how they compensate. The safe habits are to run servers in UTC or to keep daily cron jobs away from the change window.
Why does Sunday have a different number in Quartz and EventBridge cron?
Unix cron counts Sunday as 0, while Quartz and AWS EventBridge count Sunday as 1. So a Unix day-of-week range of 1-5, Monday to Friday, would mean Sunday to Thursday if pasted unchanged into Quartz or EventBridge. Using day names such as MON-FRI avoids the off-by-one error on every platform.
Why does my cron job skip some months?
A cron job set for day 31, such as 0 0 31 * *, silently skips April, June, September and November, five months a year, because those months have no 31st, and 0 0 30 2 * never runs at all. For the last day of the month in five fields, run on days 28 to 31 and test whether tomorrow is the 1st.
CSS Formatting, Minification and Property Order: What Is Safe
Does CSS calc() need spaces around plus and minus?
Yes. The + and - operators in calc(), min(), max() and clamp() must have whitespace on both sides. calc(100% - 2px) works, but calc(100%-2px) is invalid because -2px reads as a negative number. Multiplication and division do not need spaces, but keeping the author's spacing is the safe choice for any CSS minifier.
Can a CSS minifier remove the space in a descendant selector?
No. In a CSS selector a space is the descendant combinator, an operator. .card p means a p inside .card, while .cardp is a different class. The subtle case is a pseudo-class: .menu :hover matches any hovered element inside .menu, whereas .menu:hover matches .menu itself when hovered, so the space must stay.
Does a CSS shorthand override longhand properties?
Yes. A CSS shorthand sets every longhand it covers, resetting unmentioned ones to their initial values, and within one rule the later declaration wins. So border-top: 4px solid red followed by border: 0 leaves no border, while border: 0 followed by border-top: 4px solid red gives a red top border. Shorthand and longhand pairs must keep their order.
Which CSS shorthands reset properties with unrelated names?
Some CSS shorthands reset longhands whose names give no hint. font resets line-height, inset sets top, right, bottom and left, gap sets row-gap and column-gap, flex-flow sets flex-direction and flex-wrap, and place-items sets align-items and justify-items. The all shorthand resets nearly everything, so a safe property sorter treats these pairs as ordered.
Why does CSS have duplicate declarations like display: -webkit-box; display: flex?
A pair such as display: -webkit-box; display: flex; is a deliberate fallback, not a duplicate. Browsers ignore a value they do not understand, so older browsers use the prefixed value and newer ones apply the later standard value. A minifier that removes such "duplicate" declarations can break support in the browsers the fallback was written for.
Database Backups with pg_dump, mysqldump and Friends: What Actually Works
What is the difference between a logical and a physical database backup?
A logical backup, from tools such as pg_dump or mysqldump, contains SQL or an archive that recreates objects and rows, so restoring one table is easy and it usually works across versions. A physical backup copies the database's own data files, restores fast, and supports point-in-time recovery with archived logs, but only on the same major version.
Does pg_dump back up users and roles?
No. pg_dump dumps one database, and roles, passwords and tablespaces are cluster-wide, so they are not included. Run pg_dumpall --globals-only as well, or a restore on a fresh server will fail on GRANT statements for roles that do not exist yet. Adding --no-owner to pg_dump lets you restore where the original owner role is missing.
Does mysqldump include stored procedures?
Not by default. mysqldump includes tables, views and triggers, but stored procedures, functions and scheduled events are only included if you add --routines and --events. For a consistent InnoDB dump also add --single-transaction, and --quick so rows stream to the file instead of being buffered in memory.
How do I test a database backup restore?
Once a month, or after any change to the backup script, create an empty scratch database, restore last night's backup into it, compare row counts for the biggest tables with production, and run a query the application depends on. Time it, because a full restore's duration is your minimum recovery time. Never restore over the live database.
What is the 3-2-1 backup rule?
The 3-2-1 backup rule means keeping three copies of your data, on two kinds of storage, with one copy off-site. For a small service that can be a nightly dump on the server, a copy in object storage such as S3, GCS or Azure Blob with versioning or object lock, and a lifecycle rule keeping dailies for two weeks and monthlies for a year.
Database Schema Design and ER Diagrams: Keys, Relationships and Normal Forms
What is the difference between a surrogate key and a natural key?
A surrogate key is an auto-generated integer or UUID with no business meaning, so a value such as users.id = 1842 never needs to change. A natural key is a real-world value such as an ISO country code or an email address. Natural keys save a join but break when the real world changes, which is why most teams use surrogate keys for entity tables.
How far should I normalise a database?
In practice, the first three normal forms cover most of normalisation. First normal form means one value per column, second means every column in a composite-key table depends on the whole key, and third means no column depends on another non-key column. Denormalising on purpose, such as keeping an order total as a snapshot, is fine when the two copies can never legitimately disagree.
What does ON DELETE CASCADE do?
ON DELETE CASCADE removes child rows automatically when their parent row is deleted. The alternatives are ON DELETE SET NULL, which orphans the children deliberately, and the default NO ACTION or RESTRICT, which refuses to delete a parent that still has children. Choose per relationship: deleting a user should probably delete their sessions, but not their invoices.
Does PostgreSQL create an index on a foreign key column?
No, PostgreSQL does not create an index on a foreign key column for you, while MySQL's InnoDB does. Without that index, joins from the parent table and every cascading delete have to scan the child table, so in PostgreSQL you should add an index on each foreign key column yourself.
Why should money not be stored as a FLOAT in a database?
Money belongs in a DECIMAL column with explicit precision and scale, such as DECIMAL(12,2), never FLOAT. Binary floating-point numbers cannot represent a value like 0.10 exactly. Floats for money are one of the database design mistakes that are hard to undo once a schema is in use.
Date Math for Developers: Month Ends, DST Days and Unix Time
What is 31 January plus one month?
31 January plus one month is 29 February in a leap year such as 2024 and 28 February otherwise, when the date library clamps to the last day of the target month as date-fns addMonths, Java's plusMonths and PostgreSQL's + interval '1 month' do. JavaScript's setMonth instead rolls over to 2 March, or 3 March in a non-leap year.
How do I tell if a Unix timestamp is in seconds or milliseconds?
Count the digits. A current Unix timestamp has 10 digits in seconds, 13 in milliseconds and 19 in nanoseconds. Reading a seconds value as milliseconds lands in January 1970, while reading milliseconds as seconds lands tens of thousands of years in the future, so an absurd converted date usually means the unit is wrong.
What is the year 2038 problem?
The 2038 problem is the overflow of a signed 32-bit counter of Unix seconds, which runs out at 2147483647, or 2038-01-19 03:14:07 UTC. JavaScript, modern Linux and 64-bit databases are fine, but old C structs, embedded firmware and INT database columns that hold timestamps still turn up and can be affected.
Is adding one day the same as adding 24 hours?
No. Where daylight saving time applies, one calendar day a year has 23 hours and one has 25. Adding one day keeps the wall-clock time, which suits "same time tomorrow" reminders, while adding 24 hours adds elapsed time, which suits token lifetimes, cache TTLs and rate limits. In New York, noon on 9 March 2024 plus 24 hours is 1 PM on 10 March.
How do I know if a year is a leap year?
Under the Gregorian rule, a year is a leap year if it is divisible by 4, except century years, which must also be divisible by 400. That is why 2000 was a leap year and 2100 will not be. Adding one year to 29 February 2024 gives 28 February 2025, while adding four years gives 29 February 2028.
Decoding Ethereum Transactions: RLP, Selectors and ABI Calldata
How do I calculate a function selector?
A function selector is the first four bytes of keccak256 of the function's canonical signature. For example, keccak256("transfer(address,uint256)") begins 0xa9059cbb, so that is the selector for transfer. The signature must be the name and the parameter types separated by commas, with no spaces, no parameter names, uint written as uint256 and structs written as tuples of their member types.
What is RLP encoding?
RLP, Recursive Length Prefix encoding, is the format of a raw Ethereum transaction, and it only knows byte strings and lists. A single byte below 0x80 is itself, a string of 0 to 55 bytes is 0x80 plus the length followed by the bytes, and a list of 0 to 55 bytes is 0xc0 plus the length. Integers are big-endian with no leading zeros.
How do I decode Ethereum transaction input data?
Read the first four bytes of the input data as the function selector, then decode the rest as 32-byte words against the contract's verified ABI. Static types such as address and uint256 sit in place, while bytes, string and arrays hold an offset to a tail with a length and the data. A decoded uint256 token amount is in base units, so divide by 10^decimals.
What is an unlimited token approval?
An unlimited approval is an approve call with an amount of 2^256 - 1, a 78-digit number starting 115792. It lets the spender move every token you hold, now and later. The approve(address,uint256) selector is 0x095ea7b3, so calldata starting with those bytes means you are letting some address spend your tokens, and the next 64 bytes say which address and how much.
Why is my Ethereum transaction hash not found on Etherscan?
An Ethereum-style transaction hash that shows "not found" on Etherscan is most likely on another chain, because every EVM chain has its own explorer. Generate explorer links for the same hash on Base, Arbitrum and Polygon and open them until one resolves. Testnet hashes need the testnet explorer.
DNS Records Explained: A, AAAA, CNAME, MX, TXT, NS and CAA
What is a DNS TTL and how should I set it before a change?
A DNS TTL, or time to live, is the number of seconds a resolver may cache a record before asking again. Before a cutover, lower the record's TTL to 300 a day ahead, wait at least one old TTL so caches pick up the short value, make the change, then raise the TTL again once traffic has settled.
Why does a newly created DNS record not work yet?
A freshly created DNS record that does not resolve is often a cached NXDOMAIN rather than slow propagation. If someone looked up the name before it existed, resolvers cache the "does not exist" answer for the negative-caching TTL, which is the last number in the zone's SOA record, as defined in RFC 2308.
What does the number in an MX record mean?
The number in an MX record is its priority, and lower numbers are tried first, so 10 mx1.example.com is preferred over a record with a higher number. An MX lookup shows where mail for a domain is delivered, while the TXT records beside it carry the SPF policy. DKIM and DMARC live under their own names.
What is DNS over HTTPS?
DNS over HTTPS, defined in RFC 8484 in 2018, lets a client send DNS queries inside ordinary HTTPS requests. It is the only way a web page can ask DNS questions at all, because browsers do not expose raw UDP port 53. The record format and wire protocol still come from RFC 1034 and RFC 1035, published in 1987.
Can a domain have two SPF records?
No, only one SPF record is allowed per name. Publishing a second v=spf1 TXT record instead of merging it into the first makes SPF evaluation return a permanent error. SPF, defined in RFC 7208, also has a hard limit of 10 DNS lookups during evaluation, which a few include: entries can easily exceed.
Escape Sequences Explained: Backslashes in JSON, JavaScript, Python and SQL
What is an escape sequence?
An escape sequence is a backslash followed by a character that means something special inside a string literal, such as \n for a line feed, \" for a literal quote or \\ for a backslash. C introduced the idea in the early 1970s, and Java, JavaScript, C#, Python, PHP, Go and JSON inherited it. The sequence exists only in source text and disappears once the code is parsed.
What is a raw string?
A raw string is a string literal with backslash escaping switched off, so the backslashes are kept exactly as written. Python has r"C:\new", C# has verbatim strings such as @"C:\new", Go has backtick strings and JavaScript has String.raw. Raw strings are the right choice for regular expressions and Windows paths, which otherwise need every backslash doubled.
How do I escape a single quote in SQL?
In a SQL string literal, double the single quote: 'It''s'. Standard SQL, PostgreSQL and SQL Server do not treat the backslash as special in ordinary strings, but MySQL does by default unless the NO_BACKSLASH_ESCAPES mode is set. Hand-escaping SQL is fragile and does not stop injection, so use parameterised queries instead.
How do I escape a double quote in a CSV file?
Under RFC 4180, wrap the CSV field in double quotes and double any quote inside it, so a field containing She said "hi" is written as "She said ""hi""". CSV, SQL, HTML and URLs each have their own escaping scheme, and using the wrong one for the destination is a common source of bugs.
Why does a Windows path break in a JavaScript string?
In JavaScript, "C:\new\table" contains a line feed and a tab, because \n and \t are escape sequences, not two directory names. Unknown escapes are silently changed too: "\q" becomes "q". Write Windows paths with doubled backslashes or use String.raw, which turns escaping off.
Ethereum Units and Gas Fees: Wei, Gwei and EIP-1559 Worked Out
How many wei are in an ether?
One ether is 10^18 wei, so 1 ETH equals 1,000,000,000,000,000,000 wei. Ethereum has no decimals at the protocol level: every balance, msg.value and fee is an unsigned integer counted in wei. The named units are powers of ten, with gwei at 10^9 wei used for gas prices and ether at 10^18 wei for balances people read.
How many satoshis are in a bitcoin?
One bitcoin is 100,000,000 satoshi, because the satoshi is 10^-8 BTC. Wallets also show bits, which are 100 satoshi and the same as a microbitcoin, and mBTC, which are 100,000 satoshi. The 21 million BTC cap is 2,100,000,000,000,000 satoshi, which fits comfortably in a 64-bit integer.
Why does my Ethereum transaction fail with insufficient funds when I have enough ETH?
When an Ethereum transaction is validated, the sender must hold value + gasLimit x maxFeePerGas, a reservation for the worst case. Sending 0.1 ETH with a 200,000 gas limit and a 300 gwei max fee reserves 0.06 ETH for gas, so a wallet holding 0.15 ETH fails. After execution, only gasUsed x effectivePrice is charged and the rest is returned.
What max fee per gas should I set?
A common rule of thumb is to set maxFeePerGas to roughly twice the current base fee plus your priority fee. Because the base fee can rise by at most 12.5% per block, doubling covers about six consecutive full blocks before the transaction gets priced out. A max fee equal to the base fee leaves no headroom and can stall for many blocks.
Why does JavaScript give wrong wei amounts?
A JavaScript Number is a 64-bit float that is exact for integers only up to 2^53, about 9.007 x 10^15, while one ether is 10^18 wei. So 1.123456789123456789 x 1e18 becomes 1123456789123456800, with invented last digits. Parse amounts into BigInt, or use library helpers such as parseEther and formatEther from ethers or viem.
Favicon Sizes and Formats: What Browsers and Phones Actually Use
What size should an Apple touch icon be?
An Apple touch icon should be 180 x 180 pixels, saved as apple-touch-icon.png and linked with <link rel="apple-touch-icon">. iPhone and iPad use it for the home screen and Safari favourites. iOS does not keep transparency in touch icons and fills the corners in, so give the icon a solid background and leave the corner rounding to the platform.
What HTML tags do I need for a favicon?
Link favicon.ico with sizes="any", 32 x 32 and 48 x 48 PNG icons with rel="icon", apple-touch-icon.png with rel="apple-touch-icon", and site.webmanifest with rel="manifest", all from the site root. The 192 and 512 px images are not linked from HTML; they are listed in the manifest's icons array instead.
What is inside a favicon.ico file?
An ICO file is a Microsoft container, not an image format of its own. It starts with a 6-byte header, then a 16-byte directory entry per image recording width, height, colour depth, byte length and data offset, then the images. Since Windows Vista each entry can hold a complete PNG, and a real ICO begins with the bytes 00 00 01 00.
What icon sizes does a web app manifest need?
A web app manifest needs a 192 x 192 and a 512 x 512 PNG icon listed in its icons array. Chrome uses those two sizes when it decides whether a site can be installed and what to show in the install prompt, and Android uses them for home screen icons and splash screens.
Why does my favicon disappear in dark mode?
A black logo on a transparent background becomes invisible on a dark browser tab. Either give the favicon a solid background or make sure the artwork has enough contrast on both light and dark tabs. An SVG favicon can also switch colours for dark mode with a media query inside the SVG, in browsers that support SVG favicons.
Formatting HTML, XML and YAML Without Changing What They Mean
What are HTML void elements?
HTML void elements are elements that never have an end tag. The HTML Living Standard lists area, base, br, col, embed, hr, img, input, link, meta, source, track and wbr. A formatter that indents after every start tag without knowing this list drifts further right after each one and never comes back.
Does pretty-printing XML change the data?
Indenting element-only content in XML is safe, because consumers of data formats ignore the whitespace between child elements. Mixed content is different: in <p>Hello <b>world</b>!</p> any added whitespace becomes part of the paragraph. A careful XML formatter prints elements that contain text exactly as written, honours xml:space="preserve" and keeps & and < escaped.
What are the YAML indentation rules?
In YAML, indentation is the structure: a key belongs to whichever mapping its column lines up with, so moving a line two spaces can move a setting to a different object without any syntax error. Tabs are not allowed for indentation at all. That is why YAML should be formatted by a parser-based tool, not a line-based re-indenter.
Why does YAML turn NO into false?
Under YAML 1.1, used by PyYAML and older tools, the words no, off and yes are booleans, so country: NO is read as false. Under YAML 1.2 they are plain strings. Formatting a file does not change its values, but converting between JSON and YAML with a 1.1 parser can, so quote such values when in doubt.
Why does the XPath query //url match nothing in a sitemap?
A sitemap declares a default namespace, xmlns="http://www.sitemaps.org/schemas/sitemap/0.9", so its elements are not plain url elements to XPath and the query //url matches nothing. Matching on the local name instead, with //*[local-name()='url'], finds them. The same default-namespace gotcha applies to any XML document with an xmlns attribute.
From curl to Code: What Each curl Option Means in Your Language
What is the difference between curl -d and --data-binary?
Both send a request body, but when reading from a file, curl -d @file removes carriage returns, newlines and null bytes, while --data-binary @file sends the file byte for byte. Use --data-binary to send a JSON or XML file unchanged. --data-raw is like -d except that @ is not treated as a file reference.
Does curl -d URL-encode the data?
No. curl -d sends exactly what you type, so -d 'name=Ada Lovelace' sends the space unencoded, with a form-urlencoded Content-Type. To encode a value, use --data-urlencode, which sends name=Ada%20Lovelace, encoding everything except letters, digits and -._~. Repeated -d values are joined with &, so -d a=1 -d b=2 sends a=1&b=2.
Does curl follow redirects by default?
No. curl does not follow a 301 or 302 redirect unless you pass -L or --location; it returns the redirect response itself. Most libraries do follow redirects by default, including fetch, Axios in Node, Python requests and Go net/http, while PHP's ext-curl needs CURLOPT_FOLLOWLOCATION. A faithful translation turns redirects off in the target library.
What does curl -u do?
curl -u user:password sends HTTP Basic authentication as defined in RFC 7617: an Authorization: Basic header followed by the Base64 encoding of user:password. Libraries have their own equivalents, such as auth=(user, password) in Python requests and req.SetBasicAuth in Go. Base64 is an encoding, not encryption, so Basic auth must only be used over HTTPS.
Why does a request work in curl but fail in Python requests?
A common cause is the Content-Type header. curl -d 'a=1' silently adds Content-Type: application/x-www-form-urlencoded, but requests.post(url, data='a=1') sends no Content-Type, and many servers then ignore the body. The other usual cause is redirects, which curl does not follow without -L but requests does. Make curl's implicit header explicit.
From docker run to Docker Compose: Every Flag Mapped
Why does Docker Compose prefix volume and network names?
Compose prefixes everything it creates with the project name, which defaults to the name of the directory holding the compose file. In a folder called shop, the volume pgdata becomes shop_pgdata, the default network becomes shop_default and containers are named like shop-db-1. Override the project with -p or the top-level name: key.
How do I keep existing volume data when moving from docker run to Compose?
Declare the volume with name: pgdata, or with external: true, under the top-level volumes key. Otherwise converting docker run -v pgdata:... to Compose creates a new, empty volume prefixed with the project name, such as home_pgdata, and the database starts without the data stored in the original pgdata volume.
How do I add a healthcheck in docker compose?
The docker run flag --health-cmd becomes a healthcheck key in Compose, written as test: ["CMD-SHELL", "..."] plus optional interval, timeout, retries and start_period. Combined with depends_on: {db: {condition: service_healthy}}, a health check gives real start-up ordering, so a service waits until its database reports healthy.
What is the difference between a named volume and a bind mount?
A named volume has a source with no slash, such as pgdata:/var/lib/postgresql/data, and Docker manages it. A bind mount uses a host path, such as ./init:/docker-entrypoint-initdb.d:ro. In Compose, a named volume must also be declared under the top-level volumes section, while a bind mount needs nothing extra.
How do services find each other in Docker Compose?
Compose creates a network for each project, attaches every service to it, and gives each service its name as a DNS alias, so a web service can connect to db:5432 without links. Containers started with docker run on the default bridge network cannot resolve each other by name, which is why older instructions use --link or a user-defined network.
From JSON to TypeScript Types: Inference, Optional Fields and Nulls
What is the difference between optional and nullable in TypeScript?
An optional property, email?: string, may be missing but is never null. A nullable property, email: string | null, is always present but may be null. With strictNullChecks on, { email: null } does not satisfy the optional version and {} does not satisfy the nullable one. Many APIs send null for "no value", so string | null is usually the honest type.
What is the difference between (A | B)[] and A | B[] in TypeScript?
(A | B)[] is an array whose elements can each be A or B, such as (number | string)[] for [1, "a"]. A | B[] means either a single A or an array of B, so number | string[] is "a number, or an array of strings". The parentheses change the type, and a surprising number of hand-written types get this wrong.
How should JSON dates be typed in TypeScript?
JSON dates should be typed as string, because JSON has no date type: "2024-01-15T10:00:00Z" arrives as a string and stays a string in the generated TypeScript type. Typing timestamps as Date is a common mistake. If the code needs Date objects, convert the strings explicitly after parsing.
Why should I generate TypeScript types from more than one JSON record?
A single record makes fields that are sometimes missing or sometimes null look required. Pasting an array of several varied records lets the generator mark keys missing from some items as optional and merge different object shapes into one interface. Empty arrays have nothing to infer from and come out as any[], so add an element to the sample.
How does a JSON to TypeScript generator type a top-level array?
A top-level JSON array becomes a type alias for an array of item interfaces, such as export type Root = RootItem[] with a separate RootItem interface describing each record. A naive generator names both the array and the item Root, which does not compile. Nested arrays of objects are named after their key, singularised, so orders becomes Order[].
GraphQL Schemas and Queries: Validation, Types and Query Cost
How does GraphQL nullability map to TypeScript?
GraphQL types are nullable unless marked with !, while TypeScript types are non-null unless you add | null. So String! becomes string and String becomes string | null. Lists have two layers: [String]! becomes Array<string | null>, and [String!] becomes Array<string> | null. Nullable input fields and arguments also become optional, such as age?: number | null.
Why does my GraphQL server return HTTP 200 when the query failed?
A GraphQL server usually answers HTTP 200 even when a query fails validation or a resolver throws. The failure is reported in the errors array of the response, sometimes next to partial data. Always check that array rather than treating HTTP 200 as success, and read errors[].path to see which field failed.
How is GraphQL query complexity calculated?
A common GraphQL cost model charges each field 1, multiplied by the page size of every paginated ancestor. For posts(first: 10) with title and comments(first: 5) { body }, the cost is 1 for posts, 10 for title, 10 for comments and 50 for body, a total of 71. The outermost page size multiplies everything below it.
Why does a GraphQL request fail in the browser but work with curl?
A GraphQL request sent from a browser is subject to CORS. A POST with Content-Type: application/json is not a CORS-safelisted request, so the browser normally sends an OPTIONS preflight first, and the server must allow your origin plus the Content-Type and Authorization headers. If the server does not, the browser reports a network error while curl succeeds.
Are commas required in GraphQL?
No. Commas are insignificant in GraphQL: the lexer treats them as whitespace, so a formatter can drop them between fields without changing the schema. Descriptions are different, because a quoted or block string just before a definition is part of the schema, returned by introspection and shown in GraphiQL.
Gzip vs Brotli vs LZ4: Choosing a Compression Algorithm
What is the difference between LZ4 and gzip?
Gzip wraps DEFLATE, which combines LZ77 back-references over a 32 KB window with Huffman entropy coding. LZ4, written by Yann Collet in 2011, skips entropy coding and keeps its match finding simple, so it compresses and decompresses very fast but produces larger output. LZ4 suits databases, file systems, caches and log shipping, where CPU time is the bottleneck.
How do you calculate compression ratio?
Compression ratio is the original size divided by the compressed size, so 1,000 bytes compressed to 250 bytes is 4:1, and higher is better. Space saved is the original minus compressed, divided by original, which is 75% in that example. Some tools call the compressed fraction, 25% here, the ratio, so check before comparing numbers from two sources.
What does the gzip header add to a DEFLATE stream?
Gzip adds a 10-byte header and an 8-byte trailer holding a CRC-32 and the length, 18 bytes of overhead in total, around the same DEFLATE stream. The zlib format adds only 6 bytes: a 2-byte header and a 4-byte Adler-32 checksum. At the same level, gzip output is always exactly 12 bytes larger than zlib output.
Why does a Base64 string start with H4sI?
A Base64 string that starts with H4sI is almost certainly gzip data, because H4sI is the Base64 encoding of the gzip magic bytes 1F 8B 08. Spotting that prefix in a log line or a cookie tells you to Base64-decode and then gunzip it before reading. Raw zlib data instead starts with the bytes 78 9C at the default level.
What Brotli level should I use for dynamic content?
For dynamic HTML and API responses, use Brotli at quality 4 to 6, or gzip at level 6, for a good size without burning CPU on every request. Save Brotli quality 11 for static assets such as JavaScript, CSS, fonts and SVG that are pre-compressed once at build time. Browsers only advertise br over HTTPS, so plain HTTP falls back to gzip.
How Accurate Are RedBison's Tools? 7,331 Tests That Check the Answers
Are RedBison's online calculators accurate?
RedBison tests every tool's calculation code against values that someone else published, such as standards bodies, RFCs, textbooks and established software, and the tests run before every release. As of November 2026, 7,331 automated tests check that the tools give the right answers, and all of them pass. Calculators still use stated methods, so a different method can give a different answer.
Where do the expected answers in RedBison's tests come from?
Wherever possible, the expected values in RedBison's tests come from outside RedBison: standards, RFCs, published tables, established software such as OpenSSL, Python and the TypeScript compiler, or a hand calculation written next to the test. Saving a tool's own output as the right answer would protect a bug instead of catching it. Examples include the NIST Statistical Reference Datasets and RFC 7638.
How does RedBison test edge cases?
In November 2026 RedBison added 2,516 edge-case tests covering positive, edge, corner and negative inputs, such as zero, empty and enormous values, exact thresholds and broken files. The share of code decisions the tests exercise rose from 74.6% to 90.6%. The new tests found more than 150 bugs, each fixed in the same change as its test.
How do I report a bug in a RedBison tool?
Email team@redbison.dev or use the feedback icon in the footer of any page. A useful report includes the page link, what you entered with units and options, what you got and what you expected, and your browser and device if a page will not load. RedBison writes a test that reproduces each confirmed bug before fixing it.
What does the Updated date on a RedBison page mean?
The Updated date on a RedBison tool or guide moves when that page's write-up or the page itself changes, not when the site is rebuilt, so it shows how recently the page was revised. A fix in calculation code shared by several tools does not move the date on its own.
How Subnetting Works: CIDR Prefixes, Masks and Host Counts
What is CIDR notation?
CIDR notation writes an IPv4 network as an address followed by a slash and a prefix length, such as 192.168.10.77/26. The prefix length says how many of the 32 bits, counted from the left, identify the network, and the rest identify hosts. A /26 has 6 host bits, so the block holds 64 addresses. CIDR is defined in RFC 4632, originally RFC 1519 in 1993.
How do I split a /24 into smaller subnets?
Borrow host bits for the network: each bit borrowed doubles the number of subnets and halves their size. Splitting 192.168.10.0/24 into /26 blocks borrows two bits, giving four subnets of 64 addresses: .0 to .63, .64 to .127, .128 to .191 and .192 to .255, each with 62 usable hosts.
How many usable IP addresses are in an AWS subnet?
AWS reserves five addresses in every VPC subnet: the network address, the next three for the router, DNS and future use, and the last address. A /26 in a VPC therefore gives 59 usable addresses rather than the standard 62. Standard subnet calculators give the IP answer, so subtract the platform's reservations yourself when sizing.
How do I convert an IP address to a decimal number?
Read the four octets as one base-256 number: first octet x 256³ + second x 256² + third x 256 + fourth. For 192.168.1.1 that is 3,221,225,472 + 11,010,048 + 256 + 1 = 3,232,235,777, or 0xC0A80101 in hex. Storing IPv4 as an unsigned 32-bit integer makes database range queries simple.
Are IP address classes still used?
Not for routing. Before CIDR, addresses were classful: a Class A network was always a /8, Class B a /16 and Class C a /24, decided by the first bits of the address. That wasted space so badly that classes were abandoned for routing more than thirty years ago, and modern internet routing forwards on prefix length. 10.0.0.0/24 is a perfectly normal subnet.
How Text Diff Works: Reading Changes Like a Code Reviewer
What is the Myers diff algorithm?
The Myers diff algorithm, published by Eugene Myers in 1986 as "An O(ND) Difference Algorithm and Its Variations", finds the minimal set of whole-line insertions and deletions between two files. When files are mostly similar, it runs in time proportional to the file size times the number of differences. GNU diff uses it, and it is Git's default diff algorithm.
What is the difference between Myers, patience and histogram diff?
Myers is Git's default and finds a minimal edit script, but it can slide a change to an unintuitive position among identical lines such as closing braces or blank lines. Git's --patience and --histogram options anchor on lines that appear exactly once in both files, which often produces more readable diffs for code.
How do I compare two config files for drift?
Export both configuration files, paste them side by side in a diff tool and turn on ignore whitespace so formatting differences do not mark every line as changed. For structured configs such as JSON, sort the keys first, for example by running both through a formatter, because a line diff does not know that reordered keys mean nothing.
How do I compare logs from a good run and a bad run?
Strip the timestamps and request IDs from both logs first, since those differ on every line and would make the whole file look changed, then diff the two. The first hunk of the result often points straight at where the good and bad runs diverged. A regex tool helps remove the varying fields before comparing.
Who invented the diff command?
The original Unix diff was written by Douglas McIlroy and James Hunt at Bell Labs and shipped in 1974. Their 1976 paper, "An Algorithm for Differential File Comparison", described an approach based on finding the longest common subsequence of lines. Eugene Myers later published the faster O(ND) algorithm in 1986.
How to Read a Hex Dump: Offsets, Bytes and Magic Numbers
How do I read a hex dump?
Each line of a hex dump has three parts: an offset on the left giving the position of the line's first byte in hex, then 16 bytes as two-digit hex values, then an ASCII gutter. Offsets are hex, so 00000010 is byte 16 and 00000100 is byte 256. The gutter prints bytes from 0x20 to 0x7E as characters and everything else as a dot.
What does EF BB BF mean at the start of a file?
EF BB BF at offset 0 is the UTF-8 byte order mark. It is invisible in text editors but glued to the front of the first value, so a CSV header id can fail to match a lookup for id, or a JSON parser can report an unexpected token at position 0. Excel writes it when saving "CSV UTF-8".
Why does the PNG file signature contain 0D 0A?
The PNG signature 89 50 4E 47 0D 0A 1A 0A is designed to expose damaged transfers. The 89 is above 7F, so a transfer that strips the high bit corrupts it visibly. 0D 0A is a Windows line ending and the later 0A a Unix one, so a tool that converts line endings breaks the signature instead of silently breaking the image.
What is C2 A0 in a hex dump?
C2 A0 is a UTF-8 non-breaking space, usually pasted from a web page or word processor. It looks like a space and is not one, so code such as split(' ') misses it. Other invisible culprits include E2 80 8B, a zero-width space, and 0D 0A at line ends, which is a Windows line ending.
How do I turn hex text back into a binary file?
Use xxd -r -p hex-dump.txt output.bin. The -r -p options read plain hex, ignoring spaces and line breaks, and write the raw bytes. The Hex Editor can save edited bytes as hex text with Download Hex, which xxd then converts back into a file.
How to Write a Technical Design Doc Reviewers Actually Read
When do you need to write a design doc?
Write a design doc when a change crosses team boundaries, introduces a new dependency or data store, changes a public API, or will take more than a couple of weeks. A bug fix does not need one, while a new billing pipeline does. Changing a plan in a document costs an afternoon, while changing it after three weeks of implementation costs three weeks.
What is an RFC in software engineering?
An RFC, short for "request for comments", is the name many engineering organizations and open source projects, such as the Rust project, give to their design document process. Other companies call the same thing a design doc or a technical spec. Whatever the name, the habit is the same: write the plan, circulate it, collect objections and decide.
What goes in the alternatives considered section of a design doc?
The alternatives considered section lists the two or three serious options that were not chosen, the strongest argument for each, and why each was rejected. It is what separates a design doc from a description. If the obvious alternative is missing, someone will raise it in the review meeting, and the meeting will be spent rebuilding that comparison.
What are non-goals in a design doc?
Non-goals state what a design deliberately will not do, such as "We will not support multi-region writes in this phase." They are among the most underrated sections of a design doc, because one clear sentence can save a 40-minute tangent in review. Goals, by contrast, should carry numbers, like p95 under 300 ms at 2,000 requests per second.
What is the difference between a PRD and a design doc?
A product requirements document, or PRD, says what to build and why, from the user's side. A technical design doc says how to build it and what was rejected. In a healthy flow, the PRD sets the goal, the design doc proposes the approach, and Architecture Decision Records capture the individual decisions that come out of review.
HTTP Status Codes Explained: What Each Class Means and When to Send It
What does Cloudflare error 522 mean?
Cloudflare error 522 means Cloudflare could not even open a TCP connection to the origin server, which points at a firewall or network problem. Error 524 is different: Cloudflare connected but the origin did not send an HTTP response in time, since Cloudflare waits 100 seconds, which points at slow requests. Both are Cloudflare codes, not defined in any RFC.
What status code should a rate limit return?
A rate limit should return 429 Too Many Requests, the code RFC 6585 defines for it, with a Retry-After header giving a number of seconds or an HTTP date. Do not use 503 for one client exceeding its quota, because 503 Service Unavailable says the whole service is unavailable, which misleads retry logic and monitoring.
What is the difference between 502 Bad Gateway and 504 Gateway Timeout?
A 502 Bad Gateway means a proxy or load balancer got an invalid response from the upstream server, typically because the application crashed or closed the connection. A 504 Gateway Timeout means the proxy gave up waiting for the upstream; nginx's proxy_read_timeout defaults to 60 seconds. A plain 500 means the application itself failed, usually with an unhandled exception.
Is it OK to return HTTP 200 with an error in the body?
No. Returning 200 OK with something like {"error": "not found"} in the body is a bug, not a style choice: caches will store the response, crawlers will index it and every client library will report success. Use the right 4xx or 5xx code and put the details in the body, for example with RFC 9457 Problem Details.
What is the difference between 302, 303 and 307 redirects?
All three are temporary redirects. 303 See Other always changes the follow-up request to GET, which suits the Post/Redirect/Get pattern after a form POST. 307 Temporary Redirect requires the client to repeat the same method and body. 302 Found does not guarantee either, because early browsers turned POST into GET and RFC 9110 now allows it.
JSON Formatting, Validation and JSONPath: A Practical Guide
What does "Unexpected token } in JSON at position" mean?
It means the JSON parser was fine until that character position, then found a } where it expected another value. Nine times out of ten, the character just before that position is a trailing comma, which JavaScript allows but JSON does not. Remove the comma and the document should parse.
What does "Unexpected end of JSON input" mean?
"Unexpected end of JSON input" means the document stopped before every bracket and brace was closed, so look for truncation. It often happens when a log line or database column has a length limit and the object gets cut off mid-string. A related error, "Unexpected token u" at position 0, usually means the code tried to parse the string undefined.
Why is my JSON invalid?
Invalid JSON almost always comes from a few causes: a trailing comma in hand-edited config, truncation by a length limit, objects copied from a console with single quotes, True, None or undefined, double encoding that turns an object into a string, or invisible characters such as a byte order mark or non-breaking space pasted from a word processor.
What is double-encoded JSON?
Double-encoded JSON is a JSON value that was serialized a second time, so it arrives as "{"id":1}" instead of {"id":1}. It is still valid JSON, but it is a string, not an object, so code that expects to read fields from it will fail. It is a common cause of JSON that looks right but does not behave as an object.
What is the difference between JSONPath and jq?
JSONPath and jq both query JSON documents, but with different syntax. JSONPath, proposed by Stefan Goessner in 2007 and standardized as RFC 9535 in 2024, writes a filter as $.orders[?(@.status == 'shipped')].id. jq is a command-line tool that expresses the same query as .orders[] | select(.status == "shipped") | .id.
JSON Schema Validation: Drafts, Keywords and Reading Errors
What is the difference between additionalProperties and unevaluatedProperties?
additionalProperties only knows about properties and patternProperties in the same schema object, so combined with allOf it rejects keys declared in another branch. unevaluatedProperties, added in JSON Schema draft 2019-09, sees every property evaluated by any applicator, including allOf, $ref and if/then. Use "unevaluatedProperties": false when composing schemas and rejecting unknown keys.
What replaced the array form of items in JSON Schema 2020-12?
In JSON Schema 2020-12, prefixItems replaced the array form of items. In draft-07, "items": [{...}, {...}] validated elements positionally and additionalItems controlled the rest. In 2020-12, positional schemas go in prefixItems and items, always a single schema, applies to the remaining elements, so a draft-07 tuple read by a 2020-12 validator is no longer a tuple.
How do I read a JSON Pointer error path from a schema validator?
The error path, or instancePath, is a JSON Pointer (RFC 6901) to the failing value. /items/1/qty means the qty key of the second element of items, and the empty string is the root. A / inside a key is written ~1 and a ~ is written ~0. Missing required keys and unexpected additional keys are reported on the parent object.
Does a JSON Schema pattern have to match the whole string?
No. A JSON Schema pattern uses ECMA-262 regular expression syntax and is not anchored, so "pattern": "abc" matches any string containing abc. Add ^ at the start and $ at the end when the pattern must match the whole string, for example "^[A-Z]{3}-\d{4}
quot;.Should I use oneOf or anyOf in JSON Schema?
anyOf is often what you want. oneOf requires exactly one branch to match, which makes errors noisy when branches overlap, because a failure produces an error for every branch that did not match plus one for the combinator. When reading those errors, the branch you intended usually has the error with the deepest path.
JSON vs XML vs Protocol Buffers: Size, Speed and Trade-offs
How much smaller is Protocol Buffers than JSON?
For a small record with an id, a name and a boolean, Protocol Buffers takes roughly 9 bytes on the wire, against 41 bytes of JSON and 61 bytes of XML. Protobuf replaces field names with small numeric tags and encodes small integers as one-byte varints, while JSON repeats every key in every object and XML repeats each element name twice.
How does Protocol Buffers handle schema changes?
Protocol Buffers uses field numbers defined in a .proto schema, which makes it straightforward to add new fields without breaking old clients. The rules are strict: never reuse a field number and never change a field's type. The cost is that a protobuf payload cannot be read in a terminal without the schema and a tool such as protoc --decode or grpcurl.
Should I use JSON or Protocol Buffers for an API?
Use JSON for public web APIs, because every client can consume it and it is easy to debug. Use Protocol Buffers with gRPC for internal service-to-service calls at scale, if you can adopt the tooling, for strong contracts and efficient payloads. A sensible approach is to start with JSON, measure, and move hot paths to a binary format when the numbers justify it.
How do I benchmark serialization formats fairly?
Benchmark serialization formats with your own realistic data rather than one tiny object, run many iterations after warm-up, and look at medians and high percentiles, not just averages. Compare compressed sizes, since that is what crosses the network, make sure each format encodes exactly the same information, and check whether parsing even matters next to database time.
What are the alternatives to JSON, XML and Protocol Buffers?
Alternatives to JSON, XML and Protocol Buffers include MessagePack and CBOR, which are binary JSON-like formats without a required schema; Avro, which is schema-based and popular with Kafka; and FlatBuffers and Cap'n Proto, which offer zero-copy access for very low latency.
JSON vs YAML: Differences, Gotchas and When to Convert
Should I use JSON or YAML for configuration files?
Use YAML for configuration written by humans, if comments and readability matter and you lint it, and JSON for configuration written by programs, because generating YAML correctly is harder than it looks. JSON is the better choice for APIs and data exchange, since it is unambiguous, fast and supported everywhere. Some teams prefer TOML, which has explicit types.
Why does YAML turn version 1.10 into 1.1?
YAML guesses types for unquoted values, so version: 1.10 is read as the float 1.1. Other values suffer the same way: a zip code like 01234 may be read as octal in YAML 1.1 or lose its leading zero, and long numeric IDs can lose precision. Quote version numbers and codes with leading zeros so they stay strings.
Can YAML use tabs for indentation?
No. YAML forbids tabs for indentation and uses spaces only. A single misaligned space can also silently move a key into a different parent object rather than causing an error. Editors with YAML support and a linter such as yamllint catch most of these indentation mistakes.
What does YAML stand for?
YAML first stood for "Yet Another Markup Language", then became the recursive "YAML Ain't Markup Language" to emphasize that it is for data. It was started in 2001 by Clark Evans, Ingy döt Net and Oren Ben-Kiki with human readability as its design goal, and YAML 1.2, released in 2009, made every valid JSON document valid YAML.
What is lost when converting YAML to JSON?
Converting YAML to JSON loses comments, because JSON has nowhere to put them. Anchors and aliases are expanded into duplicated data and will not be recreated when converting back. Multiple documents in one file must become an array or separate files, and type guesses become permanent, so a NO that the parser read as false stays false.
JSON-LD Structured Data: What Still Earns Rich Results
Why does Google recommend JSON-LD for structured data?
Schema.org markup can be written as Microdata, RDFa or JSON-LD. Microdata and RDFa put properties into HTML attributes, while JSON-LD keeps them in a separate script block. Google recommends JSON-LD because it does not tangle markup with page templates and is easy to generate on the server. JSON-LD has been a W3C Recommendation since 2014, with version 1.1 in 2020.
What properties does a Product rich result require?
Google's Product snippet requires name plus at least one of offers, review or aggregateRating, with image, description and brand recommended. The price, priceCurrency and availability belong on an Offer inside offers, not on the Product itself, and availability should be a URL such as https://schema.org/InStock. Image URLs should be absolute.
Does Google still show HowTo and FAQ rich results?
Google stopped showing HowTo rich results in September 2023, and in August 2023 it limited FAQ rich results to well-known, authoritative government and health sites. The markup still validates, but it no longer produces a visible result for most sites in Google, so add FAQPage or HowTo markup only if another consumer needs it.
What is @graph in JSON-LD?
@graph lets a single JSON-LD block describe several items on one page, such as an Organization, a WebSite, a BreadcrumbList and a BlogPosting. Giving nodes @id values lets them reference each other, for example a publisher pointing at the organization, instead of repeating it in every block. Google also reads several script blocks or a top-level array.
Why is my structured data valid but not showing a rich result?
Valid markup only makes a page eligible for a rich result, not entitled to one. Each Google rich result has its own required properties, content policies and eligibility rules that change over time, and Google decides per query whether to show it. Markup must also describe content visible on the page, or it can earn a manual action.
Keyword Density: What the Number Means and What It Does Not
Does keyword density still matter for SEO?
Keyword density is worth measuring but not worth optimising toward. Modern search engines rank on many signals beyond page text and understand language well enough that repetition adds nothing after the first few clear mentions. No major search engine has published a target density, so use the number to catch repetitive writing, not to chase rankings.
What is keyword stuffing?
Keyword stuffing is repeating a keyword to game rankings, and Google's spam policies list it by name as "filling a web page with keywords or numbers in an attempt to manipulate rankings". In the 1990s, when engines ranked largely on page text, pages hid keyword lists in white text on white backgrounds and repeated phrases dozens of times.
How do you count keyword density for a multi-word phrase?
There are two conventions for multi-word phrases. The common one counts phrase occurrences over total words, so "espresso machine" appearing 4 times in 400 words is 1 percent. Some tools multiply by the number of words in the phrase, giving 4 × 2 / 400 = 2 percent. Neither is wrong, so only compare numbers from the same tool.
Does a keyword density checker count run and running as the same word?
Not in a plain frequency counter. Without stemming, "run", "runs" and "running" are three separate keywords, so a concept spread across variants such as "price", "prices" and "pricing" at 1 percent each is really at 3 percent. Search engines treat related forms as closely related, so read the counts as a profile of your vocabulary.
Why is keyword density so high on a short text?
Short samples exaggerate keyword density. On 48 words, any word used twice crosses 4 percent, and on 50 words every repeated word looks extreme. The numbers settle down on full-length copy, so on a short product description ignore the warning colour and read the sentences for repetition instead.
Linux File Permissions and chmod: 755, 644 and Beyond
Why should I not use chmod 777?
chmod 777 gives every user on the system write access, so any compromised account, service or vulnerable plugin can change the files. It also hides the real problem, which is almost always ownership: the web server runs as one user and the files belong to another. Fix it with chown, a shared group, or write access to one specific upload directory.
What does capital X do in chmod?
Capital X in chmod adds execute only to directories and to files that already have at least one execute bit. That makes chmod -R a+rX the safe way to open up a tree: directories become enterable, scripts stay runnable, and plain files do not suddenly become executable. For example, it turns 640 files into 644 and 750 directories into 755.
What is the sticky bit in Linux?
The sticky bit, octal 1 in the fourth mode digit, means only a file's owner, the directory's owner or root can delete or rename files in that directory, even if others can write to it. /tmp is 1777 for this reason and shows as drwxrwxrwt in ls -l. Linux ignores the sticky bit on regular files.
What does setgid do on a directory?
Setgid on a directory makes new files created inside inherit the directory's group instead of the creator's primary group. A shared team folder set to 2775 keeps every file in the team's group and lets members write, especially when combined with a umask of 002. In ls -l it shows as s in the group position: drwxrwsr-x.
Why do I get permission denied reading a file that is 644?
To read a file you need execute permission on every parent directory as well as read on the file. To read /srv/site/index.html you need x on /, /srv and /srv/site, so a missing x on any parent gives Permission denied even when the file itself is 644. On a directory, x means you can enter it and reach files inside by name.
MAC Addresses and OUIs: Vendors, Flag Bits and Random MACs
What is an OUI in a MAC address?
An OUI, or Organizationally Unique Identifier, is the first 24 bits of a 48-bit MAC address, a prefix the IEEE Registration Authority sells to a manufacturer. The manufacturer assigns the last 24 bits, one value per network interface, which gives 16,777,216 addresses per OUI. Large vendors such as Apple, Cisco and Intel hold hundreds of OUIs each.
What are MA-L, MA-M and MA-S MAC address blocks?
They are the three sizes of MAC address block the IEEE sells. MA-L, the classic OUI, is a 24-bit prefix with 16,777,216 addresses; MA-M is a 28-bit prefix with 1,048,576; and MA-S, formerly OUI-36, is a 36-bit prefix with 4,096. MA-M and MA-S blocks sit inside IEEE-held OUIs, so a three-byte lookup returns "IEEE Registration Authority".
What is a private Wi-Fi address on an iPhone?
A Private Wi-Fi Address is a randomised MAC address that iOS 14 and later use per network by default, so a phone cannot be tracked across places by a fixed hardware MAC. It sets the locally administered bit, so its second hex character is 2, 6, A or E, and no OUI lookup can name the manufacturer. Android 10 and later do the same.
What MAC addresses do virtual machines use?
Hypervisors usually generate virtual machine MAC addresses under their vendor's OUI, so they look up cleanly. VMware uses 00:50:56 and 00:0C:29, Hyper-V uses 00:15:5D, and VirtualBox uses 08:00:27, an OUI registered to PCS Systemtechnik GmbH, the company whose software became VirtualBox.
Is MAC address filtering secure?
No. MAC filtering on Wi-Fi stops nobody who can run ip link set dev wlan0 address to change their address. Treat a MAC address as an identifier on a trusted network, not as a credential. A MAC address is also only visible on the local link, so a server on the internet never sees it.
Markdown Syntax That Renders Everywhere: CommonMark, GFM Tables and Task Lists
What is the difference between CommonMark and GitHub Flavored Markdown?
CommonMark, started in 2014 by a group including John MacFarlane, is an unambiguous Markdown specification with hundreds of test cases. GitHub Flavored Markdown (GFM), published by GitHub in 2017, is a strict superset of CommonMark that adds tables, task lists, strikethrough and automatic links. When people say Markdown today they almost always mean CommonMark plus GFM.
How do I make a task list in Markdown?
Write a list item with square brackets: - [ ] for an empty task and - [x] for a done one. The space inside the brackets matters, because - [] with no space is just text. Task lists are a GitHub Flavored Markdown extension, and in a static render the checkboxes are read-only, so change the state by editing [ ] to [x].
Who created Markdown?
John Gruber released Markdown in 2004, with Aaron Swartz as a close collaborator on the syntax. The goal was text that reads naturally as plain text and converts cleanly to HTML. Gruber's original was a Perl script plus a syntax page that left many edge cases undefined, which is why different flavours appeared.
Why did my indented paragraph turn into a code block in Markdown?
Four leading spaces make a code block in Markdown, so a paragraph indented for visual reasons becomes a grey monospace box. Indented code also breaks inside lists, where indentation already means nesting. Avoid indenting prose and use fenced code blocks, three backticks with an optional language label, for code instead.
How do I indent a nested list in Markdown?
Indent a nested Markdown list item to line up with the text of its parent item, not just "a bit". Under a bullet written as - item, that means two spaces; under a numbered item written as 1. item, it means three. Also leave a blank line before the list so it is not treated as part of a paragraph.
Markdown Tables: Syntax, Alignment, Escaping and Limits
Does standard Markdown support tables?
Not in its core. John Gruber's original Markdown (2004) had no tables, and neither does CommonMark. Tables come from the tables extension in the GitHub Flavored Markdown (GFM) specification, which GitLab, Docusaurus, Obsidian, VS Code's preview and most static site generators also implement, and Pandoc supports as "pipe tables". Tables written the GFM way render nearly everywhere.
Can a Markdown table have no header row?
No. A GitHub Flavored Markdown table needs a header row followed directly by a delimiter row of hyphens, one cell per header cell, so there are no headerless tables. The header cells may be empty, though. Without the delimiter row there is no table at all, only a paragraph full of pipes.
What happens if Markdown table rows have different numbers of cells?
GitHub Flavored Markdown is forgiving about body rows: a row with fewer cells than the header gets empty cells at the end, and a row with more cells has the extras ignored. The header and delimiter rows, however, must have exactly the same number of cells, or the block is not recognised as a table.
Can I put a list inside a Markdown table cell?
No. Markdown table cells allow inline formatting such as bold, italics, code, links and images, but not block elements like lists, headings, code blocks or blockquotes. A common workaround is lines separated by the HTML br tag, each starting with a bullet character. For anything more complex, write an HTML table.
How do I convert a CSV file to a Markdown table?
Parse the CSV with a proper parser rather than splitting on commas, because RFC 4180 CSV wraps cells containing commas, quotes or line breaks in double quotes, and a naive split breaks on "Smith, John". The Markdown Table Generator uses Papa Parse, detects semicolon-separated files, converts multi-line cells to br tags and makes the first row the header.
MIME Types and Content-Type: Getting Files Served Correctly
What does X-Content-Type-Options: nosniff do?
The X-Content-Type-Options: nosniff response header stops browsers from MIME sniffing, guessing a response's type from its first bytes. In return, browsers refuse to run a script or apply a stylesheet whose Content-Type is not a JavaScript or CSS type. It defends sites that serve user uploads, where a photo.txt containing HTML could otherwise be sniffed as HTML and run scripts.
What is the MIME type for YAML?
The registered MIME type for YAML is application/yaml, registered by RFC 9512 in 2024. Before that, servers sent unofficial types such as application/x-yaml or text/yaml, which old tutorials still show. Other recent clean-ups include text/javascript for JavaScript under RFC 9239 and image/webp confirmed by RFC 9649.
What does +json or +xml mean in a MIME type?
A suffix such as +json, +xml or +zip is a structured syntax suffix: it says the bytes are JSON, XML or ZIP whatever the specific format is. Examples include application/ld+json, image/svg+xml and application/epub+zip. A client that has never heard of application/problem+json still knows it can parse the body as JSON.
How do I add a MIME type in nginx?
Add the entry to /etc/nginx/mime.types, or in a types block such as image/avif avif;, then reload nginx. A types block inside a server or location replaces the inherited table rather than adding to it, so either edit mime.types or include it again. In Apache the equivalent is AddType image/avif .avif.
What is application/octet-stream?
application/octet-stream is the type a server falls back to for files it has no mapping for, and setting default_type application/octet-stream in nginx makes unknown files download. Upload tools for object storage such as Amazon S3 often default to it when they cannot guess. When files that should display, such as AVIF images or files from a storage bucket, arrive as octet-stream, the server table or object metadata is missing the right type.
Public IP Addresses Explained: NAT, Geolocation and Lookups
What are the private IP address ranges?
RFC 1918 (1996) set aside three private IPv4 ranges that are never routed on the public internet: 10.0.0.0/8, 172.16.0.0/12 and 192.168.0.0/16. Home routers usually use 192.168.0.0/16, while corporate networks and cloud VPCs often use 10.0.0.0/8. A fourth range, 100.64.0.0/10, is reserved by RFC 6598 for carrier-grade NAT.
How do I check if my VPN is leaking my IP address?
Open What Is My IP Address, turn on the VPN and press Refresh. The IPv4 address, country and organisation should all change to the VPN provider's exit node. If the IPv4 changes but an IPv6 row still shows your own provider's prefix, the VPN is leaking IPv6, which is a real and common misconfiguration.
Does IPv6 use NAT?
Usually not. With IPv6 each device normally gets its own globally routable address, often several, with privacy extensions (RFC 8981) rotating the interface part every day or so. A dual-stack connection therefore has one public IPv4 address shared by the household and one IPv6 address per device, and a website sees whichever protocol the connection used.
Should I allow-list a home IP address?
Not permanently. Most residential IP addresses are dynamic and change after a router reboot or a lease expiry, and under carrier-grade NAT the same public address may belong to thousands of other customers. For the same reason, blocking an IP address on a mobile network after one abusive request may block a whole town.
QR Codes for Developers: Error Correction, Size and Scannability
Who invented the QR code?
The QR code was invented in 1994 by Masahiro Hara and his team at Denso Wave, then part of the Toyota group, to track car parts on production lines. QR stands for Quick Response. Denso Wave held the patent but chose not to enforce it, and the format became an ISO standard, ISO/IEC 18004, in 2000.
What is the quiet zone on a QR code?
The quiet zone is the blank margin of four modules that the QR code standard specifies around the code. It tells the scanner where the code ends and its surroundings begin. Codes printed right up against text, borders or busy backgrounds are a leading cause of scan failures, so the border should never be set to zero for print.
What is the difference between static and dynamic QR codes?
A static QR code simply contains your text, so a URL in it works as long as that URL works. A dynamic QR code encodes a short redirect URL controlled by a service, so the destination can be changed later and scans counted, but the code depends on that service staying in business. For long-lived print, point the code at a domain you own.
How much data can a QR code hold?
A version 40 QR code, the largest at 177 x 177 modules, holds up to 7,089 digits or 2,953 bytes at the lowest error correction level, though codes that large are impractical to scan. QR codes come in 40 versions starting at 21 x 21 modules, and encoding more data means a higher version and a denser code.
Can a QR code use brand colors?
Yes, as long as the QR code keeps strong contrast with dark modules on a light background. Avoid inverted light-on-dark codes, which not all scanners read, low-contrast pairings such as mid-grey on white or red on black, and gradients or photos behind the modules. Test with more than one phone in the lighting where the code will be used.
Quotes, NULLs and LIMIT: Writing SQL and Seed Data That Run Everywhere
What is the difference between single and double quotes in SQL?
Single quotes wrap string literals, while double quotes wrap identifiers such as column and table names in standard SQL, PostgreSQL, SQLite and Oracle. MySQL is the exception: it treats double quotes as strings by default and uses backticks for identifiers. That is why WHERE status = "active" works in MySQL but fails in PostgreSQL with column "active" does not exist.
Why does NOT IN with a subquery return no rows?
If the subquery returns even one NULL, a NOT IN condition becomes unknown for every row, because "not equal to unknown" is unknown, and WHERE keeps only rows where the condition is true. The query returns an empty result with no error. Use NOT EXISTS with a correlated subquery instead, which does not have this problem.
What is the difference between LIMIT, TOP and FETCH FIRST?
They are dialect forms of the same row limit. MySQL, MariaDB, PostgreSQL and SQLite use LIMIT 10, SQL Server uses SELECT TOP 10 or OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY, and Oracle 12c and later uses the standard FETCH FIRST 10 ROWS ONLY, which PostgreSQL also accepts. Without ORDER BY, any of them returns an arbitrary set of rows.
How do I reset a PostgreSQL sequence after loading seed data?
Seed rows that set id explicitly do not move the sequence behind a SERIAL or identity column, so the next normal insert fails with a duplicate key. Fix it once per table with SELECT setval(pg_get_serial_sequence('users', 'id'), (SELECT max(id) FROM users)); MySQL and SQLite move the auto-increment counter past the highest id automatically.
What makes good database seed data?
Good seed data looks like real customers rather than "Test User 1" to "Test User 50". It includes names with apostrophes and accents such as O'Brien and Zoë, long values and NULL optional fields, so quoting and encoding bugs show up early. Emails should use example.com, which RFC 2606 reserves, and parent tables must load before child tables so foreign keys resolve.
Random Numbers, Names and Emails for Test Data, Done Properly
Is Math.random() safe for picking raffle winners?
No. In V8, which runs Chrome, Node.js and Edge, Math.random() has been xorshift128+ since 2015: fast and statistically decent but predictable, because its internal state can be recovered from enough consecutive outputs. For anything with stakes, such as prize draws, audits or tokens, use crypto.getRandomValues() or a language's secrets module instead.
What is rejection sampling in random number generation?
Rejection sampling is the standard fix for modulo bias. It finds the largest multiple of the range size that fits in the random draw, discards any draw at or above that limit, and takes the remainder of the accepted values, so every result is equally likely. Java's nextInt(bound) and Python's secrets.randbelow use it, averaging fewer than two draws per number.
Is test.com safe to use for fake email addresses?
No. test.com, demo.com, email.com and sample.org are all registered domains, and some accept mail, so seeding staging data with them can send password resets or invoices to a stranger's inbox. Safe choices are the domains reserved by RFC 2606, example.com, example.net and example.org, or the .test top-level domain.
Which test names catch the most bugs?
Useful test names include accented letters such as García, surnames with spaces such as De Luca, very short parts such as Yu, suffixes such as Jr. or III, and common collisions such as John Smith. Hand-written cases should add an apostrophe (O'Brien), a hyphen (Smith-Jones), a single-word name and a name in a non-Latin script.
Regular Expressions in JavaScript: A Field Guide for Working Developers
What is the difference between greedy and lazy regex quantifiers?
Greedy quantifiers match as much as they can and give characters back only if the rest of the pattern fails, while lazy quantifiers such as +? match as little as possible. Against <b>bold</b>, the greedy <.+> matches the whole string and the lazy <.+?> matches <b> and </b>. A negated class like <[^>]+> is usually clearer and faster.
What is catastrophic backtracking in regex?
Catastrophic backtracking is when a regular expression takes exponential time on certain inputs, usually because of nested quantifiers over overlapping characters, such as (a+)+$. In July 2019 a regex in a Cloudflare WAF rule caused CPU exhaustion across its network and a global outage. When the pattern runs on user input, the bug becomes a denial-of-service vulnerability known as ReDoS.
How do I validate an email address with regex?
Do not try to match the full grammar: RFC 5322 email syntax is famously hard to express in a regex. For a form, a permissive pattern such as ^[^\s@]+@[^\s@]+\.[^\s@]+$ catches typos, and sending a confirmation email is the only real test that an address works.
Does \w match accented letters in JavaScript?
No. In JavaScript regex, \w means [A-Za-z0-9_], so it does not match accented letters. To match letters from any language, use a Unicode property escape such as \p{L} together with the u flag, which also gives correct handling of code points.
Why does my JavaScript regex test() alternate between true and false?
A RegExp object with the g or y flag is stateful: it remembers lastIndex between calls to test() and exec(). Reusing one regex object across different inputs can therefore give alternating true and false results. Create a new regex for each input, or reset lastIndex to 0 before each call.
Robots.txt and XML Sitemaps: How Crawlers Actually Read Them
What happens if robots.txt returns a server error?
If robots.txt answers with a 5xx status, Google treats the whole site as disallowed until it can read the file again, which is how a broken robots.txt route can stop crawling entirely. A 4xx response has the opposite effect, and crawlers treat the site as unrestricted. The file should be plain UTF-8 text served with a 200 status at the root of each host.
What is RFC 9309?
RFC 9309 is the IETF standard for the Robots Exclusion Protocol, published in September 2022. The protocol began as a mailing-list proposal by Martijn Koster in 1994 and was a convention that each crawler interpreted slightly differently for 28 years. Under RFC 9309, every rule is a prefix match and the longest matching rule wins, so line order does not matter.
Does Google support noindex in robots.txt?
No. A Noindex line inside robots.txt was never officially supported by Google, and Google stopped honouring it in September 2019. To keep a page out of results, let it be crawled and serve noindex on the page itself, because a page blocked by Disallow is never fetched and its noindex is never read.
Should I block CSS and JavaScript in robots.txt?
No. Google renders pages, so if robots.txt stops Googlebot fetching the CSS and JavaScript bundles, it judges a broken page. Keep rendering resources crawlable and reserve Disallow for paths crawlers should not visit, such as internal search result pages.
Can robots.txt hide admin pages?
No, listing them advertises them. Anyone can open /robots.txt, so every path in it is public, and the file is only a request that well-behaved crawlers honour, not access control. Sensitive areas such as an admin section need authentication, or removal from the public build.
SQL Data Types Across MySQL, PostgreSQL, SQL Server, SQLite and Oracle
Does FLOAT mean the same thing in every database?
No. In MySQL, FLOAT is a 4-byte single-precision number, but in SQL Server and PostgreSQL a bare FLOAT means 8-byte double precision, and only FLOAT(n) with n of 24 or less is single precision. REAL is also inconsistent: 4 bytes in PostgreSQL and SQL Server, 8 bytes in SQLite. Converting by name alone gets precision wrong in one direction.
Should I use DECIMAL or FLOAT for money in SQL?
Use exact decimals for money in every database: DECIMAL(p,s) in MySQL and SQL Server, NUMERIC(p,s) in PostgreSQL and NUMBER(p,s) in Oracle. SQLite is the exception, because it has no fixed-point storage and a NUMERIC column stores integers or 8-byte floats, so keep amounts as whole cents in an INTEGER column there if exactness matters.
Is TINYINT the same in MySQL and SQL Server?
No. MySQL's TINYINT is signed and holds -128 to 127, while SQL Server's TINYINT is unsigned and holds 0 to 255. Moving a MySQL TINYINT column straight to SQL Server TINYINT breaks any negative values. In PostgreSQL, a MySQL TINYINT maps to SMALLINT, and TINYINT(1) used as a flag becomes BOOLEAN.
What PostgreSQL type should an Oracle DATE become?
An Oracle DATE should become a PostgreSQL TIMESTAMP, not DATE, because Oracle's DATE includes hours, minutes and seconds. Mapping it to PostgreSQL DATE silently drops the time of day. Oracle also has no TIME type at all, and an instant with a time zone maps from Oracle TIMESTAMP WITH TIME ZONE to PostgreSQL TIMESTAMPTZ.
Should I use VARCHAR or NVARCHAR in SQL Server?
NVARCHAR is the safe default in SQL Server, especially for text migrated from MySQL's utf8mb4, because SQL Server's VARCHAR stores non-Unicode text unless you use a UTF-8 collation, available in SQL Server 2019 and later. NVARCHAR(n) allows n up to 4,000, and NVARCHAR(MAX) replaces the deprecated TEXT and NTEXT types for long text.
SQL Formatting Conventions That Make Queries Easier to Review
How should I format SQL joins?
Write every join explicitly, each on its own line with its ON condition on the same line or directly beneath, such as JOIN customers AS c ON c.id = o.customer_id. Avoid the old comma-join style that puts join conditions in the WHERE clause, because it mixes join logic with filters and makes it easy to forget a condition and produce an accidental cross join.
Where should AND and OR go in a SQL WHERE clause?
Put each SQL condition on its own line with AND or OR at the start of the line. That makes conditions easy to comment out while debugging and makes diffs show exactly which condition changed. Always use parentheses when mixing AND and OR, because AND binds tighter, and relying on that rule is a classic source of bugs.
How do I format common table expressions in SQL?
Use a WITH clause that gives each step a name, indent the CTE's own SELECT, FROM, WHERE and GROUP BY inside its parentheses, and put the main query after it so the whole thing reads top to bottom. CTEs usually read better than more than one level of nested subquery. PostgreSQL treated CTEs as optimization fences until version 12; modern versions inline them where possible.
Why should I avoid SELECT * in SQL?
SELECT * hides which columns a query actually uses, breaks when columns are added or reordered, and transfers data nobody needs, so avoid it in application code and views. Listing the columns explicitly, one per line, also gives clean diffs when a column is added later.
Who invented SQL?
SQL was designed at IBM in the early 1970s by Donald Chamberlin and Raymond Boyce, first under the name SEQUEL, with the explicit goal of reading like English. It became an ANSI standard in 1986. Short SQL queries still read that way, but ORM-generated queries with many joins and nested subqueries need formatting to stay readable.
SQL Indexes and EXPLAIN Plans: Finding Why a Query Is Slow
How do I read a PostgreSQL EXPLAIN ANALYZE plan?
Read a PostgreSQL plan from the leaves up, because that is the order rows flow. For each node, check its type (Seq Scan, Index Scan, Bitmap Heap Scan or a join), its cost share of the root's total, estimated against actual rows, and loops, since actual time and rows are reported per loop. Wrap an UPDATE or DELETE in BEGIN and ROLLBACK, because ANALYZE executes the query.
Is a Seq Scan always bad?
No. A Seq Scan reads the whole table, and on a small table, or when the filter keeps most of the rows, that is the cheapest plan, so the planner is often right to choose it. An Index Scan walks an index and fetches matching rows instead. If a new index does not replace a Seq Scan, the filter usually keeps too many rows to make it worthwhile.
Why is my SQL index not being used?
Common causes are a function around the column, such as LOWER(email) or YEAR(created_at), a leading wildcard like LIKE '%@gmail.com', a composite index whose first column is missing from the filter, and OR across different columns. Rewrite dates as ranges or create an expression index. Stale statistics can also mislead the planner, so run ANALYZE on the table.
What does a row misestimate in an EXPLAIN plan mean?
A row misestimate means the planner's estimated row count differs from the actual one, for example 1,500 estimated against 120 returned, about 13x. It matters because the planner picks join strategies from estimates, and a nested loop is perfect for 10 rows but terrible for 100,000. When estimates are off by 10x or more, run ANALYZE on the table first.
Does PostgreSQL automatically index foreign keys?
No. PostgreSQL does not index foreign key columns automatically, so joins and cascading deletes on an unindexed column such as orders.user_id are a classic cause of slow pages. Create the index yourself, and on busy tables use CREATE INDEX CONCURRENTLY so writes are not blocked while it builds.
SVG viewBox, Sizing and Script Safety for Developers
What does preserveAspectRatio do in an SVG?
preserveAspectRatio decides what happens when an SVG's viewBox and viewport have different aspect ratios. The default, xMidYMid meet, scales the drawing uniformly so all of it fits and centres it, the SVG equivalent of object-fit: contain. Setting preserveAspectRatio to none stretches the drawing to fill both the width and the height.
What size is an SVG with no width, height or viewBox?
An inline SVG with no width, height or viewBox falls back to the browser default of 300 x 150 pixels, which is rarely what you want. An SVG with a viewBox but no width or height scales to whatever CSS or its container says, which is the ideal setup for icons. Without a viewBox, a fixed-size SVG will not scale cleanly.
Do scripts in an SVG run when inserted with innerHTML?
Script elements inserted through innerHTML do not execute, but that gives false confidence, because event handler attributes such as onload can still fire. An SVG with an onload handler inserted with innerHTML or React's dangerouslySetInnerHTML can run code with the viewer's session. Displaying the same file with an img tag runs no scripts at all.
How should a site serve user-uploaded SVG files?
Display uploaded SVGs with img tags or CSS backgrounds, never by injecting their markup. Serve them from a separate user-content origin so that a file opened directly in a tab runs away from your cookies, and send a restrictive Content-Security-Policy such as default-src 'none'. If markup must be inlined, sanitise it with a maintained library such as DOMPurify configured for SVG.
Can I change the colour of an SVG shown with an img tag?
No. In an img-embedded SVG, currentColor comes from the SVG itself, not from the page's CSS, so setting color on the page does not recolour the icon. When theming is needed, use inline SVG from trusted sources or apply the icon as a CSS mask.
System Design Interviews: A Four-Step Method with Real Numbers
What do interviewers look for in a system design interview?
System design interviewers mostly score four things: whether you scoped the problem with functional requirements, non-functional requirements and scale before drawing; whether the high-level design is sound; whether you can go deep on one or two components; and whether you see the trade-offs of every cache, queue, replica and shard. Senior candidates are also expected to drive the conversation.
How do you design a URL shortener in a system design interview?
Scope it first: create short links, redirect on visit, optional custom aliases, five-year expiry. At 100 million links a month that is about 40 writes and 400 reads per second, 6 billion links and about 3 TB over five years, and 7 Base62 characters give about 3.5 trillion codes. Use a stateless API tier, a key-value store keyed by code and a cache for hot links.
Should a URL shortener use 301 or 302 redirects?
A 301 redirect is cached by browsers, which cuts load on the URL shortener but hides repeat visits from any click counting. A 302 redirect does the opposite: every visit reaches the server, so clicks can be counted at the cost of more traffic. In a system design interview, say which you choose and why.
What is the difference between cache-aside and write-through caching?
Cache-aside is the default caching pattern: the application reads from the cache and loads from the database on a miss. Write-through writes to the cache and the database together, trading extra write latency for fresher reads. Whichever pattern you choose in a system design interview, name your invalidation strategy and mention the staleness a cache introduces.
How should I practise for system design interviews?
Do one prompt every two or three days for two to four weeks, first alone and then with a partner playing interviewer, timed to 45 minutes. Note the numbers you used and one thing to do differently, and redraw the design from memory the next day. Cover prompts that stress different things, such as a feed, chat app, rate limiter, ride-sharing service and video platform.
Testing REST APIs from the Browser: Methods, cURL and CORS
What is a CORS preflight request?
A CORS preflight is an OPTIONS request the browser sends before a non-simple cross-origin request, carrying Access-Control-Request-Method and Access-Control-Request-Headers. The server must answer with matching Access-Control-Allow-Origin, Allow-Methods and Allow-Headers before the browser sends the real request. If the preflight fails, the real request is never sent, so server logs show only OPTIONS.
Why does Content-Type application/json trigger a CORS preflight?
A request is only simple when its Content-Type is application/x-www-form-urlencoded, multipart/form-data or text/plain, and it uses GET, HEAD or POST with safelisted headers. Content-Type: application/json falls outside that list, so almost every JSON API call is preflighted. Sending that header on a GET with no body is pointless and turns it into a preflighted request.
How do I fix a CORS error?
Fix a CORS error on the server, not in the client, because no client-side setting can grant permission the server did not give. The API must send Access-Control-Allow-Origin for your page's origin and answer the OPTIONS preflight for your method and headers, or you can call it through a backend proxy you control.
Which headers can't JavaScript set in a fetch request?
The Fetch standard lists forbidden request headers that JavaScript cannot set, including Host, Cookie, Origin, Referer, Connection, Content-Length, Accept-Encoding and anything starting with Sec- or Proxy-. The fetch API drops them silently. For testing authenticated calls from the browser, use an Authorization header or an API key instead of cookies.
What is the difference between safe and idempotent HTTP methods?
Under RFC 9110, a safe method such as GET, HEAD or OPTIONS should not change anything on the server, while an idempotent method has the same effect whether it is sent once or twice. PUT and DELETE are idempotent but not safe, and POST is neither, which is why payment APIs ask for an idempotency key on POST.
Text to Speech and Speech Recognition in the Browser: What Really Happens
What is the Web Speech API?
The Web Speech API is a browser interface, written up by a W3C Community Group in 2012, with two largely separate halves. speechSynthesis reads text aloud and works in Chrome, Edge, Safari and Firefox, mostly with local system voices. SpeechRecognition turns microphone audio into text, is exposed as webkitSpeechRecognition in Chrome, Edge and Safari, and is not available in Firefox.
Is browser speech to text private?
Not usually. In Chrome the microphone stream is sent to Google's speech servers and the text comes back over the network, which is why recognition fails offline with a network error, and Edge sends audio to Microsoft's service. Safari may process speech on Apple's servers or on the device. Treat browser dictation like any cloud transcription service, and avoid it for passwords or confidential data.
Why does speech recognition stop on its own in Chrome?
Even with continuous set to true, the recognition service decides when a session is over, and Chrome typically ends it after several seconds of silence. The browser then fires the onend event, and the page has to call start() again to keep listening. A tool that records the microphone in parallel must also stop that recorder in onend.
What is the difference between interim and final speech recognition results?
With interimResults turned on, the recognizer sends a stream of guesses that it keeps revising as you speak, and only a result marked isFinal is settled. For example, "schedule the deep" may flicker past before "schedule the deploy for nine thirty" arrives. Only final results should be appended to a transcript; interim text belongs in a separate, replaceable line.
Can MediaRecorder record audio as WAV or MP3?
No. MediaRecorder only writes compressed containers: WebM with Opus in Chrome, Edge and Firefox, Ogg in Firefox, and MP4 with AAC in Safari. Asking for audio/wav or audio/mpeg throws NotSupportedError, so check MediaRecorder.isTypeSupported before choosing a format, and convert the downloaded file afterwards if another program needs WAV.
Time Zones for Developers: Offsets, DST and IANA Zone Names
What is the difference between a UTC offset and a time zone?
A UTC offset is a fixed distance from UTC at one moment, such as -05:00 or +05:30, while a time zone is a region's full set of rules about which offset applies on which dates. America/New_York is a time zone that is UTC-5 in winter and UTC-4 in summer, so storing -05:00 for a July meeting stores the wrong time.
What is the IANA time zone database?
The IANA Time Zone Database, also called tzdata or the Olson database after Arthur David Olson, holds the clock rules for every region. It has been hosted by IANA since 2011, is maintained by volunteers with several releases a year, and ships with every major operating system, browser, language runtime and database. Zone names follow an Area/Location pattern such as Europe/Paris.
Should I store timestamps in UTC?
Store instants such as log lines, created-at columns and event timestamps in UTC, or in ISO 8601 with an explicit offset. Store future local events, such as a 09:00 Europe/Berlin meeting next year, as local time plus an IANA zone, because the rules might change first. Mexico abolished most daylight saving in 2022, making earlier UTC conversions wrong.
Why are New York and London sometimes four hours apart?
New York and London switch daylight saving on different dates. The US changes on the second Sunday in March and the first Sunday in November, while the EU and UK change on the last Sundays in March and October. For two or three weeks each spring and one week each autumn, the cities are four hours apart instead of five.
What happens to a time that occurs twice when clocks fall back?
When clocks fall back, an hour of local time happens twice: in New York on 1 November 2026, 01:00 to 01:59 occurs first in EDT and then in EST. The common convention, used by most date libraries, resolves such an ambiguous time to its first occurrence, so 01:30 becomes 01:30 EDT, which is 05:30 UTC.
TOML Explained: Syntax, Types and Converting to JSON and YAML
What is TOML?
TOML, short for Tom's Obvious, Minimal Language, is a configuration format created by Tom Preston-Werner in 2013 that maps unambiguously to a hash table. Version 1.0.0 of the specification was released in January 2021. It supports comments, is strongly typed and ignores indentation, and it is read by Rust's Cargo, Python's pyproject.toml, Hugo, Netlify, Ruff, uv and Black.
What is an array of tables in TOML?
An array of tables is a list of tables written with double-bracket headers. Each [[name]] header appends a new table to the array named name, and the keys below it belong to that entry until the next header. Two [[bin]] sections in Cargo.toml, for example, become "bin": [{...}, {...}] in JSON, an array of two objects.
How do TOML inline tables work?
An inline table puts a small table on one line inside curly braces, such as serde = { version = "1.0", features = ["derive"] } in a Cargo.toml dependency list. Inline tables must stay on a single line and cannot be extended later in the file, so a later [owner] header or owner.age key after owner = { name = "Tom" } is an error.
Should I use TOML, YAML or JSON?
Use TOML for flat-ish configuration that humans edit, such as tool and package config, since it has comments, native dates and no whitespace sensitivity. Deeply nested data such as a Kubernetes manifest reads better in YAML, which TOML makes verbose. Data exchanged between programs belongs in JSON, which has no comments but does support null.
Can a key be defined twice in TOML?
No. Defining the same key twice, such as title = "a" followed by title = "b", is a parse error in TOML rather than "last one wins". Defining the same table twice with two [database] headers is also an error, as is adding a [database] header after already setting database.host with a dotted key at the top level.
User-Agent Strings Explained: Reading Them, Reduction and Bots
What is User-Agent reduction in Chrome?
User-Agent reduction is Google's phased change, rolled out from 2022 through Chrome 101 to 113, that freezes detail in the User-Agent string. Chrome now reports versions like 130.0.0.0, every Mac shows macOS 10_15_7, and Android phones show Android 10 with the model replaced by K. Other Chromium browsers followed, so detailed OS versions in User-Agent analytics are frozen values.
What are User-Agent Client Hints?
User-Agent Client Hints are HTTP headers that carry the browser details removed from the User-Agent string. Chromium browsers send Sec-CH-UA, Sec-CH-UA-Mobile and Sec-CH-UA-Platform by default, and a site can request more, such as Sec-CH-UA-Platform-Version or Sec-CH-UA-Model, with an Accept-CH response header. Safari and Firefox do not implement them, so code still needs a User-Agent fallback.
What user agents do AI crawlers use?
AI crawlers identify themselves with their own User-Agent names: GPTBot, OAI-SearchBot and ChatGPT-User from OpenAI, ClaudeBot from Anthropic, PerplexityBot, CCBot from Common Crawl and Bytespider from ByteDance. A User-Agent is only a claim, though, so verify a crawler by reverse and forward DNS or the operator's published IP ranges before giving it special treatment.
How can I tell an iPad from a Mac by user agent?
You usually cannot from the string alone, because iPadOS Safari requests the desktop site by default and sends a Macintosh User-Agent. In the page, check navigator.maxTouchPoints: a value greater than 1 on a device claiming to be a Mac almost always means an iPad. Feature detection like this is more reliable than User-Agent sniffing.
Should I use user agent sniffing or feature detection?
Use feature detection, such as checking 'IntersectionObserver' in window or CSS @supports, for layout and capability decisions rather than sniffing the User-Agent. Browsers copy each other's tokens, so a hand-written regular expression easily misclassifies next year's browser. When server-side branching is unavoidable, use a maintained parser library and keep it updated.
UTF-8, Mojibake and Byte Order Marks: Text Encoding for Developers
What is mojibake?
Mojibake is text decoded with the wrong encoding. Bytes do not say which encoding produced them, so when the UTF-8 bytes C3 A9 for é are read as Latin-1 or Windows-1252 they appear as é. The right fix is to find the step that decoded with the wrong charset, not to reverse the damage in code, because the next record may be clean or double-encoded.
How many bytes does a character take in UTF-8?
UTF-8 uses one to four bytes per code point. U+0000 to U+007F take one byte, which is why ASCII text is already valid UTF-8. U+0080 to U+07FF take two bytes, U+0800 to U+FFFF take three, and U+10000 to U+10FFFF take four. For example, é (U+00E9) is C3 A9 and 😀 (U+1F600) is F0 9F 98 80.
What is a surrogate pair in JavaScript?
A surrogate pair is how UTF-16 stores a code point above U+FFFF, such as most emoji: a high surrogate from D800 to DBFF followed by a low surrogate from DC00 to DFFF. JavaScript strings count UTF-16 code units, so '😀'.length is 2, and charCodeAt, substring and slice can see or cut only half of the character.
What is a byte order mark in UTF-8?
A byte order mark is the character U+FEFF placed at the start of a file. UTF-16 needs it to say whether the file is big-endian (FE FF) or little-endian (FF FE), but UTF-8 has no byte order, so its BOM (EF BB BF) only acts as a signature. Parsers that do not expect it can mangle the first column name or fail JSON at position 0.
Why can't MySQL utf8 store emoji?
MySQL's old utf8 character set stores only up to three bytes per character, while emoji such as 😀 (U+1F600) need four bytes in UTF-8, so they cannot be saved. Create tables with utf8mb4 instead, and declare UTF-8 explicitly at every other boundary the text crosses, including the HTML page, the HTTP header and the database connection.
Video Formats Explained: Containers, Codecs, Bitrate and CRF
What is the difference between a container and a codec?
The container is the file format named by the extension, such as MP4, MOV or MKV: it interleaves the streams, keeps sound and picture in sync and carries metadata. The codec, such as H.264 or AAC, is how each stream inside was compressed. When a player says "unsupported format", the codec is usually the problem, and renaming a file never converts it.
Is H.265 better than H.264?
H.265 (HEVC) reaches similar quality to H.264 at a substantially lower bitrate, commonly quoted as up to half, but H.264 plays almost everywhere. Every phone, browser, TV and editor decodes H.264, while HEVC support in Windows, Android and web browsers depends on hardware decoders and extensions. HEVC is a fine archive format and a risky sharing format.
What CRF value should I use?
For the x264 encoder, CRF runs from 0 (lossless) to 51 with 23 as the default, and each step of 6 roughly halves or doubles the file size. Around 18 to 20 is visually close to the source, 23 to 26 is a good everyday range, and above 30 softness and blocking become obvious. Use a target bitrate instead only when a hard size limit applies.
How do I convert MKV to MP4 without re-encoding?
Remux it: copy the compressed streams into an MP4 container without decoding any frames, for example with ffmpeg -i input.mkv -c copy output.mp4. This is lossless and fast, and it works when the MKV holds codecs MP4 allows, such as H.264 video and AAC audio. Changing resolution, frame rate or file size always requires a re-encode.
Why is a GIF so much bigger than the same clip as MP4?
GIF uses LZW compression, which handles flat colour well but noise poorly, and limits each frame to a palette of 256 colours. A clip that is 1 MB as MP4 is often 5 to 10 MB as GIF, and GIF has no sound. For anything longer than a few seconds, a short MP4 or WebM is smaller and sharper.
WAV, MP3, AAC, FLAC and Opus: Audio Formats Explained
What is the difference between a container and a codec?
A file extension usually names a container, the wrapper that holds audio plus metadata, while the codec is how the samples inside are encoded. An .m4a file is an MPEG-4 container usually holding AAC, and a .webm file from a browser recorder is almost always Opus audio in a WebM wrapper. When a player refuses a file, the codec is usually the problem.
How big is a WAV file per minute?
A WAV file's size is 44 header bytes plus seconds x sample rate x channels x bytes per sample. At CD quality, 44.1 kHz stereo 16-bit, that is 176,400 bytes per second, so a 3-minute song is 31,752,044 bytes, about 30.28 MB. A 1-minute 16 kHz mono speech file is 1,920,044 bytes, about 1.83 MB.
Is FLAC better than WAV?
FLAC and WAV hold the same audio quality, because FLAC is lossless and decodes back to PCM bit for bit. The difference is size: FLAC compresses PCM to roughly 50 to 70 percent of its size, which makes it the choice for archiving music. WAV is uncompressed and read by every editor, game engine and speech toolkit.
Does converting MP3 to FLAC improve quality?
No. Converting a lossy MP3 to a lossless format such as FLAC or WAV produces a faithful copy of what the MP3 contains, and the MP3 no longer contains what its encoder discarded. The result sounds identical, only bigger. Keep a lossless master and encode lossy copies from it, never from each other.
What is the difference between kbps and kHz in audio?
Bitrate, in kbps, controls the quality and size of lossy formats such as MP3, AAC and Opus. Sample rate, in kHz, sets the frequency range of PCM audio: the highest storable frequency is half the rate, so 44.1 kHz captures up to 22.05 kHz. A "320 kbps WAV" setting therefore means nothing.
Why 0.1 + 0.2 Is Not 0.3: Calculator Precision, Precedence and Radians
Why is 0.1 + 0.2 not equal to 0.3 in JavaScript?
JavaScript stores numbers as IEEE 754 double-precision floats, which use a binary mantissa. One tenth is a repeating fraction in binary, so 0.1 and 0.2 are each rounded slightly high when stored. Their sum rounds to the double just above 0.3, which prints as 0.30000000000000004. A calculator shows 0.3 only because it rounds the display.
How do I compare floating point numbers in code?
Never compare floating point numbers with ===, because 0.1 + 0.2 === 0.3 is false in every IEEE 754 language. Compare with a tolerance instead, such as Math.abs(a - b) < 1e-9. For money, store integer cents or use a decimal type such as BigDecimal in Java, decimal in Python and C#, or NUMERIC in SQL.
What is 2^3^2?
2^3^2 is 512 in mathjs, Python and JavaScript, because exponentiation groups to the right: it means 2^(3^2), which is 2^9. Excel evaluates ^ left to right, so =2^3^2 in a spreadsheet returns 64, which is (2^3)^2. Adding parentheses removes the ambiguity when a formula moves between tools.
Why do two calculators give different answers for 2 + 3 × 4?
Standard operator precedence does multiplication before addition, so 2 + 3 × 4 is 14. Cheap four-function calculators evaluate strictly left to right and give 20 instead. Mainstream programming languages and mathjs agree on the order: parentheses first, then exponentiation, then multiplication and division, then addition and subtraction.
How many significant digits does a double-precision float hold?
An IEEE 754 double-precision float holds about 15 to 17 significant decimal digits. It has a sign bit, 11 exponent bits and 52 stored mantissa bits, or 53 with the implied leading 1. Two systems that agree to 14 or 15 significant digits are giving the same answer, so differences in the 16th digit are rounding noise.
ZIP vs 7z vs tar.gz vs bz2: Choosing an Archive Format
What is solid compression?
Solid compression concatenates many files into one block and compresses them together, so redundancy between files is exploited. 7z uses it by default with LZMA2, and tar.gz works the same way. It shines on many similar files such as source trees and logs, but getting one file out of a large solid block can mean decompressing much of it first.
What is zip slip?
Zip slip is an archive entry whose name contains ../ segments or an absolute path, such as ../../home/me/.bashrc, so a naive extractor writes outside the target folder. Snyk documented the pattern in 2018 across dozens of libraries in many languages. The fix is to normalise each path and refuse anything that would leave the destination.
Is ZIP encryption secure?
It depends on the method. The original ZipCrypto is weak: known-plaintext attacks have been public since the 1990s and cracking tools are freely available. AES-256 ZIP encryption, from WinZip's AE-2 extension, is strong, but built-in Windows and macOS tools cannot open it. In both ZIP schemes the file names stay visible.
How is 7z encryption different from ZIP encryption?
7z encrypts with AES-256 and can also encrypt the header, using -mhe=on in 7-Zip, which hides the file names until the right password is entered. ZIP encryption always leaves file names visible. tar, gzip, bzip2 and xz have no encryption at all, so people pair them with GPG or age instead.
Can I open a 7z file on a Mac?
macOS has no built-in support for 7z files, so a Mac needs a tool such as Keka or 7-Zip to open them. Windows 11 added 7z, RAR and tar support to File Explorer in a 2023 update, and Linux typically uses the 7z command. When the recipient's system is unknown, ZIP is the safe choice.