Skip to main content

ChatGPT Founder Sam Altman's Secrets to Effective Productivity

· 5 min read

This is a blog post written by ChatGPT founder Sam Altman in 2018, offering effective advice on how to improve productivity.

What Are You Doing?

The Essence of Long-termism is the Compound Interest Formula

Compound interest is a financial term, but it also applies to personal careers. If you produce output every day, your compound returns after 50 years will be enormous. Improving your productivity is extremely important - increasing from 1% to 10% daily improvement will make compound returns even greater.

See the compound interest formula at 👉 The Essence of Long-termism is the Compound Interest Formula

The Core of Improving Productivity: Do What You Love

Moving forward in the wrong direction is moving backward. Take time to think deeply about what you love to do. Only things you're passionate about can truly improve your productivity.

Delegate What You Don't Like to People Who Do

Doing what you love multiplies your efficiency, but for things you don't like, try not to do them - delegate, avoid, or find other ways. When delegating, make sure to delegate to people who enjoy doing those things, because based on the principle that "doing what you love improves efficiency," the delegate should also be able to complete the task efficiently.

Stick to Your Convictions

What has left a deep impression on me over the years are people with strong convictions - such people are rare in the general population. If you find yourself always agreeing with others, that's not a good thing. Stick to your convictions. Sometimes you might be wrong, but when others are confused and you do what's right and important, you'll become more brave and extraordinary.

Avoid People Who Drain You

To accomplish something great, you should strive to be around smart, positive, productive, and cheerful people who won't casually belittle your ideals and ambitions, who can push you forward and bring you inspiration. Within your ability, avoid being with people who drag you into mental exhaustion - otherwise the cost will be enormous.

Find the Right Problems and Solve Them

We're basically all in red ocean industries with fierce competition. What we need to do is work smartly and diligently, find the right problems and solve them correctly. There aren't many shortcuts here.

Priorities

Three Basic Principles

  1. Get important things done
  2. Don't waste time on BS
  3. Make lots of lists

Strongly Recommend Using Lists

Write down annual, monthly, and daily tasks in lists. Lists help you focus on current tasks and allow you to handle multiple tasks (because your brain is freed up from having to remember so many tasks).

You can write lists on paper for easy addition and removal, and taking notes during meetings won't offend others.

Review lists frequently, modify or delete tasks promptly. Don't waste time on categorizing and sorting - just mark important things with a "⭐️".

Prioritize Things That Build Momentum

Prioritize things that can generate "momentum" - when you complete one thing and feel accomplished, you continue to the next.

Learn to Be Ruthless

"To complete my most important projects, I become tough and ruthless - I've found that if I really want something to happen and I push hard enough, it usually happens."

I am relentless about getting my most important projects done—I've found that if I really want something to happen and I push hard enough, it usually happens.

"I try to be ruthless, saying no to irrelevant things, and implementing non-critical tasks in the fastest way possible. I probably take this too far—for example, I am almost sure I am terse to the point of rudeness when replying to emails."

"I try to be ruthless about saying no to stuff, and doing non-critical things in the quickest way possible. I probably take this too far—for example, I am almost sure I am terse to the point of rudeness when replying to emails."

Maintain an Open Social Network

Try to avoid meetings and conferences as they waste lots of time and energy. But keep some openness in your schedule to meet new people and ideas - maintaining an open social network is important. At conferences, while 90% is wasted time, the 10% that's valuable can make up for the loss.

Physical Aspects

This section covers sleep, exercise, and nutrition. Some are clichés, and Sam is an extreme vegetarian, so I'll skip this part. See the original text if interested.

Other Aspects

Comfortable Office Environment

An office that's quiet without interruptions, with natural light and a beautiful desk, plus multiple 4K monitors.

Some Tips

  • Write custom tools to handle annoying, repetitive tasks
  • Improve typing speed
  • Learn keyboard shortcuts

The Terrible "Period"

Like many people, occasionally there are one or two weeks of lost motivation, with no interest in anything.

There's no good solution yet, but believe that the "period" will always pass, and afterward you'll be energetic again to continue fighting.

Also, when in a bad mood, avoid contact with others - this is sincere advice.

Value Your Loved Ones and Family

Don't ignore your loved ones and family for the sake of efficiency - you've improved efficiency but lost happiness.

Finally

Sam's views on improving efficiency are worth considering, and he also emphasizes: Don't fall into the efficiency trap - improving efficiency isn't the goal, our goal is to complete tasks quickly and with quality.

10 Ways for Programmers to Improve Efficiency

· 6 min read

1. No Meetings in the Morning 📅

Everyone has 24 hours in a day, time is equal, but the value of time is not equal. One hour in the morning is worth 4 times that of the evening. Why?

Because morning is the golden time for the brain. After a night's sleep, the brain has been organized, recorded, and rested. Its state is at its fullest, suitable for high-concentration work like programming and learning foreign languages. If we waste time on low-concentration activities like meetings or scrolling through phones, we waste the value of the morning.

2. Don't Use the Pomodoro Technique 🍅

Sometimes when programming intently, we enter a "flow state" - a state of high concentration. When our focused state is broken, it takes 15 minutes to re-enter that state.

Many people recommend the Pomodoro Technique - setting a 25-minute countdown, forcing a 5-minute break, then entering the next Pomodoro. In my actual use of this method, I often encounter the problem of just entering the "flow" focused state when the Pomodoro timer rings, breaking concentration. It takes another 15 minutes to re-enter this focused state.

A good alternative is using a stopwatch. Like the Pomodoro, it visualizes time but counts forward, not breaking our "flow". When our programming concentration decreases, we can check the stopwatch to determine our break time.

3. Don't Use Your Phone During Breaks 📱

The brain needs to use 90% of its capacity to process visual information, and flickering screens excite the brain. This is why we still feel tired when returning to work despite having rested.

During break time, we should block visual information input. Recommendations:

  • Close your eyes and rest 😪
  • Listen to music 🎶
  • Walk around the office 🏃‍♂️
  • Chat with colleagues 💑
  • Stretch your neck 💁‍♂️
  • Meditate or practice mindfulness 🧘

4. Don't Eat Lunch at Your Desk 🥣

After a morning of intensive programming, the brain's concentration has dropped by 40%-50%. At this time, we need to restart our concentration. A good method is eating out. Benefits of eating out include:

  • Promoting serotonin secretion: Serotonin is a neurotransmitter that controls our sleep and wakefulness. Eating out can restore our serotonin, making us refreshed:
    • Sunbathing: Sun exposure while out promotes serotonin secretion
    • Rhythmic exercise: Walking is rhythmic exercise that also promotes serotonin secretion
  • Activating place neurons: Place neurons control location and space, existing in the hippocampus. Changing locations when eating out activates place neurons, promoting hippocampus activity and improving memory
  • Activating acetylcholine: Going to new restaurants, streets, and trying new things activates acetylcholine, which plays a huge role in "creation" and "inspiration"

5. Take a Nap 😴

Science has shown that napping is very important. It can:

  • Restore our physical state: A 26-minute nap can increase afternoon work efficiency by 34% and concentration by 54%
  • Extend lifespan: People who don't nap are more likely to die earlier than those who do
  • Prevent diseases: Reduces Alzheimer's, cancer, cardiovascular disease, obesity, diabetes, depression, etc.

Napping has many benefits, but should be appropriate - 15 to 30 minutes is optimal. More than that can be harmful.

6. Exercise Before Afternoon Work 🚴

2-4 PM is when people are least alert. 10 minutes of exercise can re-awaken our bodies and improve concentration. For programmers with limited workspace, recommendations:

  • 1️⃣ Squats
  • 2️⃣ Push-ups
  • 3️⃣ Jumping jacks
  • 4️⃣ Climb stairs (don't go down - it's hard on knees. Climb to the top floor, then take the elevator down)

7. 2-Minute Rule and 30-Second Decision 🖖

⚒️ 2-Minute Rule means if something can be completed within 2 minutes, strike while the iron is hot and complete it. This is a trick to solve procrastination. As programmers, we often encounter various unexpected problems. For some issues, we can't decide whether to complete them immediately. The 2-minute rule is a good auxiliary decision-making method.

💣 30-Second Decision means for daily matters, we only need 30 seconds to make decisions. This comes from "speed chess theory" - researchers had a famous chess player observe a game, then gave him 30 seconds and 1 hour respectively to decide the next move. They found 90% of decisions made in 30 seconds and 1 hour were identical.

8. Don't Work Overtime, Get Enough Sleep 💤

As programmers, we might often work overtime until 9 PM, get home at 10:30, shower and get to bed by midnight, then play with our phones until 2-3 AM.

Compressing sleep time means the brain doesn't get effective rest, reducing next day's concentration and work efficiency - creating a vicious cycle.

Think about our daytime work - much time is wasted ineffectively. If we force ourselves to set leaving time, innovate and change work methods, complete work with high efficiency, quality, and density, couldn't we reduce overtime, have more free time to learn new knowledge and technology, thereby improving our work efficiency and creating a positive cycle?

9. 2 Hours Before Bed 🛌

  1. Things not to do 2 hours before bed:
    • 🍲 Eating: Empty stomach promotes growth hormone, which increases blood sugar and eliminates fatigue. But eating raises blood sugar, stopping growth hormone secretion
    • 🥃 Drinking alcohol
    • ⛹️ Intense exercise
    • 💦 Hot baths
    • 🎮 Visual entertainment (gaming, movies, etc.)
    • 📺 Bright things (phones, computers, TV)
    • 💡 Being in overly bright places
  2. Things suitable to do:
    • 📖 Reading
    • 🎶 Listening to music
    • 🎨 Non-visual entertainment
    • 🧘‍♂️ Light exercise that relaxes the body

10. Don't Deliberately Sleep In on Weekends 🚫

Many people rest on a weekly basis, compressing sleep Monday to Friday, then catching up on weekends, sleeping until noon on Saturday and Sunday. But this conflicts with workday sleep rhythms, resulting in feeling particularly tired and anxious on Monday mornings.

Actually, weekends don't need catch-up sleep. The human body has a daily biological clock. Breaking the current biological clock cycle affects the next cycle, and readjustment takes time.

We should rest on a daily basis, go to bed early and wake up early, maintaining daily concentration.

References

Most of the above comes from the book "Why All Elites Are Time Controllers" by Shion Kabasawa, a neuroscientist.

Transform Your Web App to Desktop App in 10 Minutes

· 5 min read

In desktop applications, Electron has long been strong and successful. GitHub Desktop, VSCode, Figma, Notion, Feishu, CapCut, and Dewu are all based on it. But recently, the rising star Tauri has also attracted attention. It solves one of Electron's major pain points - extremely large bundle sizes.

We know that Electron is built on Google's Chromium core. After packaging, no matter how small the application is, it starts at least at 70MB. Tauri uses the operating system's built-in Webview1, dynamically linking to the webview at runtime. This makes its packaging very fast and the packaged applications much smaller.

Tauri differs from Electron in one aspect: Electron uses JavaScript to write backend services, while Tauri uses Rust. Rust has gained tremendous momentum in recent years - it's safer and performs better. Many applications have started embracing Rust, and it will likely become a frontend essential soon.

This article uses Tauri as the framework for building desktop applications. With just a little time, you can transform a Web application into a desktop application.

1. Open a Web Application

We'll use FocusTide as our conversion target. It's an open-source timer web application on GitHub:

First, let's clone the repository locally:

$ git clone git@github.com:Hanziness/FocusTide.git

Then install and run it:

# Install dependencies
$ yarn install

# Start service at localhost:3000
$ yarn dev

2. Install Tauri Dependencies

Using Mac as an example, you need to install CLang and macOS development dependencies:

$ xcode-select --install

Install Tauri:

$ curl --proto '=https' --tlsv1.2 https://sh.rustup.rs -sSf | sh

This command will install Rustup, which downloads and installs Rust-related dependencies. When installation succeeds, the console will display:

$ Rust is installed now. Great!

Installing Tauri on other operating systems:

  1. Windows: https://tauri.app/v1/guides/getting-started/prerequisites/#windows
  2. Linux: https://tauri.app/v1/guides/getting-started/prerequisites/#linux

3. Integrate Tauri into the Project

In the web application, first install Tauri-related npm packages:

$ npm install --save-dev @tauri-apps/cli

Add script command to package.json:

"scripts": {
"tauri": "tauri"
}

Then run Tauri initialization command:

$ npm run tauri init

After executing this command, it will generate the following Tauri project structure in the current web project:

After execution, there will be some questions to answer:

  1. What is your app name? Application name. This will be the official name of the packaged application.

  2. What should the window title be? Default window title. This will be the window title when opening the application. If we don't need this window later, we can hide it using the hiddenTitle field in tauri.conf.json.

  3. Where are your web assets (HTML/CSS/JS) located relative to the < current dir > /src-tauri/tauri.conf.json file that will be created? Production file path. This is the path of the frontend project after building, relative to /src-tauri/tauri.conf.json. FocusTide's build output is in the project's dist folder, so we enter ../dist.

  4. What is the URL of your dev server? Development server URL. FocusTide's development server URL is http://localhost:3000.

  5. What is your frontend dev command? Frontend development command. FocusTide's development command is yarn dev.

  6. What is your frontend build command? Frontend build command. FocusTide's build command is yarn generate.

After execution, src-tauri is generated, and we can run the project:

$ npm run tauri dev

We can see our application running in a window:

4. Build and Release

If development is complete, we can package the application:

$ npm run tauri build

After executing the build command, the packaged application will be stored in src-tauri/target/release/bundle. As you can see, the package is very small:

During Tauri packaging, it builds according to the current system platform. For example, on Mac it can only package .dmg and .app files, while on Windows it packages .msi and .exe files.

5. Deployment

After downloading, if we want to make this application public, we need to deploy it. Here we recommend Laf. We can use its cloud storage file management to upload our application and get a download link:

6. Finally

The entire conversion process is actually very simple and fast. If you spent more than 10 minutes, we apologize. If you want to dive deeper into desktop backend services, check out the Tauri official website.

Finally, I've uploaded the converted FocusTide project to my personal GitHub and named it "Lai Todo". Currently only available for Mac. Welcome to download it 👏🏻

Footnotes

  1. Tauri vs. Electron: A comparison, how-to, and migration guide: https://blog.logrocket.com/tauri-electron-comparison-migration-guide/

bit, byte, KB, GB, MG, TB, PB

· One min read

1bit 是计算机中最小的数据单位,1bit 就对应一个高低电位。

在计算机上下文中,各单位的换算关系如下:

1bit×8=1byte1bit \times 8 = 1byte 1byte×1024=1KB(kilobyte)1byte \times 1024 = 1KB (kilobyte) 1KB×1024=1MB(megabyte)1KB \times 1024 = 1MB (megabyte) 1MB×1024=1GB(gigabyte)1MB \times 1024 = 1GB (gigabyte) 1GB×1024=1TB(terabyte)1GB \times 1024 = 1TB (terabyte) 1TB×1024=1PB(petabyte)1TB \times 1024 = 1PB (petabyte)
warning

在十进制或者国际单位制中,会用 1000 作为进率,而不是 1024。注意区分上下文。


在 UTF-8 编码中

  1. 一个 US-ASCII 字符只需要 1byte
  2. 带有变音符号的拉丁文、希腊文、西里尔字母、亚美尼亚语、希伯来文、阿拉伯文、叙利亚文等字符需要 2byte
  3. 其他语言(包括中日韩文字、东南亚文字、中东文字等)使用 3byte
  4. 极少数语言用 4byte

包含块如何决定元素的尺寸和位置

· 11 min read

一、包含块

在学习 CSS In Depth 的 3.2.2 节时,被一个关于循环定义(circular definition)困住了:

Percentage refers to the size of an element's containing block; the height of that container, however, is typically determined by the height of tis children. This produces a circular definition that the browser can't resolve, so it'll ignore the declaration. For percentage-based heights to work, the parent must have an explicitly defined height.

百分比指的是元素的“包含块”的大小;然而,该容器的高度通常由其子元素的高度决定。这会产生一个浏览器无法解决的循环定义,因此浏览器会忽略该声明。要使基于百分比的高度起作用,父元素必须有明确定义的高度。

这里提到了一个包含块(Containing Block),What is Containing Block?

别慌,相信学完之后,你同样能够对这个问题的答案醍醐灌顶。

首先,看一下 MDN 关于包含块的文章:

image.png

一个元素的尺寸和位置经常被包含块所影响。大部分情况下,包含块指向一个元素最近的块级祖先元素的内容区域,小部分情况下不是这样的。在这篇文章中,我们会研究那些确定一个元素包含块的因素。

虽然这里翻译为祖先元素(ancestor),但其实更贴切是长辈元素,因为这里不仅指祖先元素,也指父类元素。想象一下,一个 <div> 被嵌套了几层,它的包含块就是第一个遇到的外层块级元素(注意是块级元素,也就是会忽略掉内联元素),第一个遇到的无论是父类还是祖父类们,都可以。

image.png

当一个用户代理(例如你的浏览器)展开一份文档,它会为每个元素生成一个盒子,每个盒子可以分成四个区域

  1. 内容区域
  2. 内边距区域
  3. 边框区域
  4. 外边距区域

box-model.png

其实也就是盒模型。

image.png

许多开发者坚信一个元素的包含块一定是它父类的内容区域,但这一结论不一定总是成立。让我们来研究一下确定一个元素的包含块的因素。

这里重复强调了下,元素的包含块是根据不同条件确定的。

二、包含块的效果

image-20220113223746573.png

在我们学习确定一个元素的包含块之前,了解一下为什么包含块的作用性是很重要的。

一个元素的尺寸和位置经常被它的包含块所影响。应用在 width, height, padding, margin 上的百分比值,还有 absolute 定位的元素偏移属性,都是根据元素的包含块计算出来的。

像百分比这样的值,肯定根据一个基准来进行计算,得到最后的结果值,而包含块就是那个基准。

三、标识一个包含块

image.png

标志包含块的程序完成取决于元素的 position 属性

  1. 如果 position 属性是 static, relative 或者 sticky,包含块通过最近长辈元素的内容盒的边界来形成,这个长辈*素可以是一个块级容器(例如 inline-block, block 或者 list-item 元素),也可以是建立了格式化的上下文(例如一个 table 容器,flex 容器,grid 容器,或者块级容器本身)

一个元素如果不显示定义 position 的值的话,那么元素 position 的默认值为 static。大部分元素都是不定义 position 值的,也就导致了前文提到的:许多开发者坚信一个元素的包含块一定是它父类的内容区域。

image.png

如果 position 的属性值是 absolute,包含块变成了最近的长辈元素的内边距区域,这个最近的长辈元素指它的 position 属性值不是 static(可以是 fixed, absolute, relative 或者 sticky)的元素。

注意包含块的变化,position 的值从 static 的最近长辈元素的内容区域(见下图绿色线条区域)改为 absolute 确定的最近长辈元素的内边距区域(下图红色线圈出来的区域,是包括内边距的边缘的)。

image.png

❓ 为什么内容区域变为了内边距区域?

这样做的目的是为了忽略内边距,体现了绝对定位(absolutely position)的效果

image.png

如果position属性是fixed,包含块由窗口(在连续媒体情况下)或者页面区域(在页面媒体情况下)所确定。

根据MDN的另一篇文章,连续媒体一般指音频或者运动视频。

image.png

  1. 如果 position 的属性是 absolute 或者 fixed,包含块同样会变成最近长辈元素的内边距区域,这个最近的长辈元素符合下面条件:
    1. transform 或者 perspective 的值不是 none
    2. will-change 属性值是 transform 或者 perspective
    3. filter 的值不是 none 或者 will-change 的值不是 filter(仅在 firefox 有效);
    4. contain 的值是 paint(例如:contain:paint;)。

will-change 这个比较少见,它是 CSS 的一个属性,作用是向浏览器表明元素即将做出变化,浏览器因此可以对此进行针对性的优化,从而提高页面响应性能。

image.png

包含根元素(<html>)的矩形包含块称之为初始包含块。它有视口(对于连续媒体)或者页面区域(对于页面媒体)的尺寸。

根元素<html>也有他自己的包含块,那么对于html页面上每一个元素来说,都会拥有自己的包含块。

四、从包含块中计算百分比值

image.png

如上所述,但某个属性给定一个百分比值,它计算出来的结果取决与元素的包含块。这些属性包括盒模型属性还有偏移属性:

  1. height,top 还有 bottom 属性从包含块的 height 中计算它的百分比值
  2. width,left,right,padding 还有 margin 属性从它的包含块的 width 中计算它的百分比值。

五、一些例子

以下是一段简单的 html 代码:

<body>
<section>
<p>This is a paragraph!</p>
</section>
</body>

以下例子共用上面这一份 HTML 代码,只是 CSS 代码有所变化,当这些 CSS 代码变化的时候,推断一下元素的包含块,以及元素的百分比计算结果。

例1

body {
background: beige;
}

section {
display: block;
width: 400px;
height: 160px;
background: lightgray;
}

p {
width: 50%;
height: 25%;
margin: 5%;
padding: 5%;
background: cyan;
}

image.png

在这个例子中,<p>position 属性是 static,它的包含块是 <section>,因为它是块级容器,并且也是距离 <p> 最近的长辈元素。

那么,<p> 的各个百分比值计算等于

p {
width: 50%; /* 值等于 400px * 50% = 200px */
height: 25%; /* 值等于 160px * 25% = 40px */
margin: 5%; /* 值等于 400px * 5% = 20px */
padding: 5%; /* 值等于 400px * 5% = 20px */
background: cyan;
}

width,left,right,padding 还有 margin 属性从它的包含块的 width 中计算它的百分比值。

例2

body {
background-color: beige;
}

section {
display: inline;
background: lightgray;
}

p {
width: 50%;
height: 200px;
background-color: cyan;
}

image.png

在这个例子中,<p> 的包含块是 <body> 元素,因为 <section> 不是一个块级容器(因为display:inline)并且也没有建立格式化上下文。

<p> 的宽度百分比计算如下:

p {
width: 50%; /* 值等于 <body> 宽度的一半 */
height: 200px;
background-color: cyan;
}

例3

body {
background-color: beige;
}

section {
position: absolute;
left: 30px;
top: 30px;
width: 400px;
height: 160px;
padding: 30px 20px;
background: lightgray;
}

p {
position: absolute;
width: 50%;
height: 25%;
margin: 5%;
padding: 5%;
background-color: cyan;
}

image.png

在这个例子中,<p> 的包含块是 <section>,因为后者的 position 值是absolute<p> 的百分比值会被包含块的 padding 所影响,如果包含块的 box-sizing 属性值是 border-box 的话,那么情况就不一样了。

<p> 的宽度百分比计算如下:

p {
position: absolute;
width: 50%; /* (400 + 20 * 2)px * 50% = 220px */
height: 25%; /* (160 + 30 * 2)px * 25% = 55px */
margin: 5%; /* (400 + 20 * 2)px * 5% = 22px */
padding: 5%; /* (400 + 20 * 2)px * 5% = 22px */
background-color: cyan;
}

box-sizing: border-box; 属性的作用是 widthheight 包含 content + padding + margin,也就是 IE 盒模型(标准的 W3C 盒模型 widthheight 只指定content,不包含 padding 和 margin)。

<section> 添加了 box-sizing: border-box;,那么 <p> 的宽度百分比计算会变为:

p {
position: absolute;
width: 50%; /* 400px * 50% = 200px */
height: 25%; /* 160px * 25% = 40px */
margin: 5%; /* 400px * 5% = 20px */
padding: 5%; /* 400px * 5% = 20px */
background-color: cyan;
}

这里读者可以自行验证下。

例4

body {
background-color: beige;
}

section {
width: 400px;
height: 480px;
margin: 30px;
padding: 15px;
background: lightgray;
}

p {
position: fixed;
width: 50%;
height: 50%;
margin: 5%;
padding: 5%;
background-color: cyan;
}

image.png

在这个例子中,<p>positionfixed,所以它的包含块是初始包含块(在屏幕上,那个视窗)。因此,<p> 的尺寸根据浏览器窗口的尺寸改变而改变。

<p> 的各个属性百分比计算如下:

p {
/* 假设视窗的宽高比为:562px*612px */
position: fixed;
width: 50%; /* 562px * 50% = 281px */
height: 50%; /* 612px * 50% = 306px */
margin: 5%; /* 562px * 5% = 28.1px */
padding: 5%; /* 562px * 5% = 28.1px */
background-color: cyan;
}

这里的视窗尺寸可以用浏览器的小手机图标来模拟:

image.png

例5

body {
background-color: beige;
}

section {
transform: rotate(0deg);
width: 400px;
height: 160px;
background: lightgray;
}

p {
position: absolute;
left: 80px;
top: 30px;
width: 50%;
height: 25%;
margin: 5%;
padding: 5%;
background-color: cyan;
}

image.png

在这个例子中,<p>positionabsolute,所以它的包含块是<section><section>transform属性不为none,所以它能够称为<p>的最近长辈元素。

<p> 的各个属性百分比计算如下:

p {
position: absolute;
left: 80px;
top: 30px;
width: 50%; /* 400px*50%=200px */
height: 25%; /* 160px*25%=40px */
margin: 5%; /* 400px*5%=20px */
padding: 5%; /* 400px*5%=20px */
background-color: cyan;
}

六、总结

看到这里的话,恭喜你完成了对包含块的所有学习 🎉🎉🎉

我们来总结下,包含块就是用于确定元素的尺寸和位置的,每一个元素都拥有自己的包含块(<html>的包含块称之为初始包含块)。

如果 positionstatic,relative,sticky,那么元素的包含块是最近的长辈元素(displayblock,table,flex,grid元素的内容区域)。

如果是 absolute,那么是内边距区域。

如果是 fixed,那么有视窗来决定。

并且对于 absolutfixed,还有其他一些规则可以确定他们的长辈元素(比如 tranform 属性不为 none 时)。这一块无需记忆,需要的时候查阅一下即可。

Swapping Values Without Intermediate Variables

· One min read

Here are three methods to swap values without using intermediate variables.

1. Addition and Subtraction

Assume we have variables:

let a = 2, b = 5

Swap:

a = a + b // a = 7

b = a - b // b = 2

a = a - b // a = 5

Disadvantages:

  • Can only handle numeric values
  • May overflow when adding large numbers

2. Multiplication and Division

Since we have addition and subtraction, we can naturally think of multiplication and division:

a = a * b // a = 10

b = a / b // b = 2

a = a / b // a = 5

Disadvantages:

  • Precision loss
  • Divisor cannot be 0

3. XOR Method

XOR is a mathematical operation where different values yield 1, same values yield 0:

Result
000
011
101
110

To perform XOR operations in computers, we need to convert values to binary first. a in binary is 010, b in binary is 101:

a = a ^ b // 010 ^ 101 = 111

b = a ^ b // 111 ^ 101 = 010

a = a ^ b // 111 ^ 010 = 101

Disadvantages:

  • Cannot handle floating-point variables

Summary

All three methods are clever tricks, only for learning purposes. It's best not to use them in production environments.

Simple Distinction Between Concurrency and Parallelism

· 2 min read

When I first started learning about concurrency and parallelism, I always got a bit confused. Now I'm finally taking the time to properly clarify the relationship between the two.

First, the word for concurrency is "Concurrency". The root "con-" means "together", and the root "current-" means "current", so the overall meaning is "things happening together".

The word for parallelism is "Parallelism". The root "parallel-" means parallel or side by side, so the overall meaning is "things happening in parallel", which can also be said as "things happening simultaneously".

Here's a vivid example mentioned by a Zhihu answerer:

You're eating a meal when the phone rings. You wait until you finish eating before answering. This means you support neither concurrency nor parallelism.

You're eating a meal when the phone rings. You stop to answer the phone, then continue eating after the call. This means you support concurrency.

You're eating a meal when the phone rings. You answer the phone while continuing to eat. This means you support parallelism.

The key to concurrency is having the ability to handle multiple tasks, not necessarily simultaneously. The key to parallelism is having the ability to handle multiple tasks simultaneously. So I think the most crucial point is: whether it's simultaneous.

From this Zhihu answerer, we can actually understand that: parallelism is a special case of concurrency. Concurrency only requires the ability to handle multiple tasks, while parallelism requires the ability to handle multiple tasks simultaneously.

With this in mind, let's clarify the concurrency and parallelism of multi-core and single-core CPUs.

First, for single-core CPUs: A single-core CPU is very clear - it can only do one thing at a time, so it cannot have parallelism, but it may have concurrency (if this CPU supports the ability to handle multiple tasks).

Second, for multi-core CPUs: Multi-core CPUs are composed of multiple single-core CPUs, so handling multiple tasks at the same time becomes effortless, thus having parallelism (having parallelism means definitely having concurrency, as we've already said parallelism is a special case of concurrency).

简要介绍进制和 ASCII 码表

· 4 min read

1. What is a Number System

  • Number System A number system, officially called "positional notation system", is a counting method. The most commonly used is the decimal system.
    • Decimal System The decimal system follows the "carry over at ten" rule, so it has 10 digits to represent numbers—0,1,2,3,4,5,6,7,8,9

In daily life, besides the decimal system, there are many other common number systems that you might not have noticed. For example, clocks use a base-60 system for seconds. The second hand goes from 0 to 59, then after one more second, it carries over to become one minute.

Speaking of computers, computers could also use the decimal system to represent numbers. So why do they specifically use binary? The reason is simple: binary only has 0 and 1, making it very simple to represent.

Why is binary simple? Because computers are fundamentally hardware, and choosing between two pathways versus ten pathways is definitely easier with the former. The only trade-off is that binary needs to take more steps to reach the same destination.

2. About Binary

Let's first look at how decimal numbers are represented. Suppose we have a decimal number (3107)10(3107)_{10}

Note

  1. Here the number (3107)10(3107)_{10} is enclosed in parentheses with a subscript 10, indicating it's in base 10 This subscript is used to indicate the number system. For example, (3107)8(3107)_{8} - notice the subscript is 8, so it's no longer decimal but octal Also, why don't we usually write it this way? Because decimal is so common that it's assumed by default
  2. Besides this notation, there's also the suffix letter method you might encounter: For example, 3107H - adding the letter H after a number indicates it's a hexadecimal number

This (3107)10(3107)_{10} can be broken down as:

3×103+1×102+0×101+7×1003×10^3+1×10^2+0×10^1+7×10^0

Now let's look at a binary number (1101)2(1101)_2, which can also be represented as:

1×23+1×22+0×21+1×201×2^3+1×2^2+0×2^1+1×2^0

Can you now understand why they're called decimal and binary systems?

For number system conversion, binary to decimal is simple. You take:

1×23+1×22+0×21+1×201×2^3+1×2^2+0×2^1+1×2^0

Then calculate in decimal:

8+4+0+18+4+0+1

Which equals (13)10(13)_{10}, so we can write (1101)2(1101)_2=(13)10(13)_{10}

3. What is ASCII Code

  • ASCII (American Standard Code for Information Interchange) - the name is quite long, but let's focus on the word "code"

We know that representing numbers in computers is relatively simple, but how do we represent text? For example, letters like a, b, c, d, punctuation marks, Chinese characters, etc.

Our predecessors came up with an excellent solution: create a table that stores these text symbols

Text Symbol
a
b
c

Then assign numbers to these text symbols in order:

NumberText Symbol
0a
1b
2c

When you need to retrieve them, just use the numbers. Want 'a'? Input 1. Want 'b'? Input 2, and so on (now you might understand the meaning of "code")

So ASCII code table was an early symbol table. How early? 1967, when Americans invented it. Americans only use 26 letters, plus various other symbols, so 128 characters were sufficient to cover everything.

Why 128? As mentioned earlier, computers use binary representation. Starting from number 0, going up to 127, that's exactly 128 numbers.

The smallest number is 0, the largest is 127. If we can represent the largest number, we can represent all smaller numbers too. (1111111)2(1111111)_2 equals 127, which we can expand as:

1×26+1×25+1×24+1×23+1×22+1×21+1×201×2^6+1×2^5+1×2^4+1×2^3+1×2^2+1×2^1+1×2^0

Also, this (1111111)2(1111111)_2 has 7 bits total, so we can say it's a 7-bit ASCII code table.