惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

GbyAI
GbyAI
博客园_首页
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
阮一峰的网络日志
阮一峰的网络日志
酷 壳 – CoolShell
酷 壳 – CoolShell
博客园 - 司徒正美
V
V2EX
Cloudbric
Cloudbric
Hugging Face - Blog
Hugging Face - Blog
腾讯CDC
量子位
博客园 - 三生石上(FineUI控件)
博客园 - 叶小钗
K
Kaspersky official blog
博客园 - 【当耐特】
T
Tenable Blog
L
Lohrmann on Cybersecurity
The Cloudflare Blog
S
Schneier on Security
A
Arctic Wolf
Latest news
Latest news
C
Cyber Attacks, Cyber Crime and Cyber Security
罗磊的独立博客
T
The Exploit Database - CXSecurity.com
Cisco Talos Blog
Cisco Talos Blog
小众软件
小众软件
P
Privacy & Cybersecurity Law Blog
WordPress大学
WordPress大学
Simon Willison's Weblog
Simon Willison's Weblog
雷峰网
雷峰网
NISL@THU
NISL@THU
人人都是产品经理
人人都是产品经理
月光博客
月光博客
J
Java Code Geeks
V
Visual Studio Blog
S
Security Affairs
博客园 - Franky
T
Tailwind CSS Blog
Apple Machine Learning Research
Apple Machine Learning Research
H
Heimdal Security Blog
有赞技术团队
有赞技术团队
V2EX - 技术
V2EX - 技术
AWS News Blog
AWS News Blog
G
GRAHAM CLULEY
T
Troy Hunt's Blog
SecWiki News
SecWiki News
Spread Privacy
Spread Privacy
宝玉的分享
宝玉的分享
www.infosecurity-magazine.com
www.infosecurity-magazine.com
博客园 - 聂微东

Stonecharioteer on Tech

I Traced My Traffic Through a Home Tailscale Exit Node What Was I Reading Last? In Three Not-So-Easy Pieces Dogfooding Is Hard Code blocks in your books, finally GoForGo v0.9.0 Merrilin - We built an app to read books I use a Macbook now Data Structures & Algorithms - Preparing for Interviews Using a local DNS namespace for local service discovery Direction KOllector - Publishing KOReader Highlights gbt: branches touched in the last 24 hours A Soiree into Symbols in Ruby Some Smalltalk about Ruby Loops Ruby Blocks Returning from Ruby Blocks, Procs and Lambdas My Linux Laptop Finally Works: How Claude Helped Me Fix Years of Annoyances TIL: Watchexec - Modern File Watching for Development Workflows A Less Busy Mind GoForGo - Learn Go through live examples Migrating My Old Blog to Hugo with Claude The Qtile Window Manager: A Python-Powered Tiling Experience Read the RFCs that Built the Internet Py-x-Protobuf - Or How I Learned to Stop Worrying and Love Protocol Buffers Python Reverse a List New Beginnings Leaving ChainSafe Systems Screen Lock for Cinnamon Desktop using Zenity and Terminal Commands Crews Not Teams A System for Getting Better at LeetCode So Far So Rust Retrying HTTP Requests with Rust A Primer on Control Charts Learning Rust Explicit is Better than Implicit: Rust for Pythonistas Using Custom Delimiters in Jinja Templates TIL: Creating Fixed Length Iterables in Python Documentation Without Assumption Vagrant Python - A Reflection in 2022 Learning Golang No, A Virtual Machine Is Not Enough: Why Developers Need Native Linux Empathy in Tech For Those Who Came in Late A Weekend With PostgreSQL TIL: Gooey and Python Fire for Quick GUIs and CLIs TIL: 2ality - Dr. Axel Rauschmayer's JavaScript Blog TIL: MassDNS - High-Performance Bulk DNS Lookups TIL: Matomo Analytics, Google Tech Writing, Memory Programming, and NES TV Signals TIL: MontyDB - MongoDB Implemented in Python Returning to the Craft of Programming TIL: CPUFetch, OneFetch, and Learn CSS TIL: DNS Performance Testing and Pi-hole with Unbound TIL: Eli Bendersky's Blog, Awesome By Example, NoCoDB, and Martin Kleppmann TIL: CRDTs, Extreme HTTP Performance, and BYTEPATH Game TIL: AutoInvent, ASGI, Python Packaging, RAPIDS GPU Computing, and FlaskCon TIL: MangaDesk - Terminal Client for MangaDex TIL: McFly - Smart Shell History Search TIL: Siege Load Testing and Awesome FastAPI Resources TIL: Ventoy Bootable USB and Justniffer Network Analysis TIL: CLI Code Review, Git Split Diffs, and Internal Combustion Engine TIL: Benford's Law, Web Security Headers, Event Sourcing, and Mozilla Security Guidelines How to Write Documentation - The README.md File The Importance of Documentation TIL: NNgroup UX Research, SponsorBlock, and Labella Python Library TIL: The Little Book of Rust Macros and Rust Performance Book TIL: Git-Bug Distributed Issue Tracker and Omni Kubernetes Monitoring TIL: Zellij - Modern Terminal Multiplexer TIL: How Discord Handles 2.5 Million Concurrent Voice Users TIL: Volumio - The Audiophile Music Player TIL: Areopagitica - Milton's Defense of Free Speech TIL: Fast Node Manager, Zoxide Smart CD, Technical Writing, PyO3, and Qubes OS TIL: Slurm Workload Manager for HPC Clusters TIL: Data Visualization Guide and Oso Authorization Academy TIL: CORS Deep Dive, Piku Tiny PaaS, Rust Strings, and Deno Standard Library TIL: Raspberry Pi OS Development, Vim Beginner Guide, Password Management, and QueryBook TIL: uBlock Origin Performance Optimization on Firefox TIL: Breaking PostgreSQL at Scale and LeetCode Problem Patterns TIL: Awesome Tmux Resources for Terminal Multiplexing TIL: Grit - A Multitree-Based Personal Task Manager TIL: Lens 4.2 Kubernetes IDE, Shell Scripting Guide, and Dark HTTP Server Do The Job You Hate So You Won't Hate The Job You Love TIL: Innernet VPN Solution and NoteCalc Calculator App TIL: Argo CD for GitOps and Lens Kubernetes IDE TIL: Modern Rust CLI Tools - System Monitoring, HTTP Requests, and DNS TIL: tz - A Time Zone Helper Tool TIL: Distributed Systems Education, Fallacies, and Self-Hosted Internet Archiving TIL: Real-Time Voice Cloning Technology TIL: ChartMuseum for Helm, AMD's Corporate Journey, and Kubernetes Pod Scaling TIL: Docker and Kubernetes Tools - Whaler, Descheduler, and Dive TIL: Post-Mortem Collection, Terminal Plotting, and Technical Twitter TIL: Dark Mode Toggle Web Component by Google Chrome Labs TIL: Python eval(), exec(), and compile() Functions TIL: Camelot PDF Tables, PostgreSQL Row Level Security, Zerodha Varsity, and Write Yourself a Git TIL: fuser Command for Process and File Investigation TIL: i Hate Regex - The Ultimate Regex Cheat Sheet TIL: Dolt - Git for Data and Database Version Control TIL: x86 Assembly Programming and SafeEyes Break Reminder TIL: Comprehensive Distributed Systems Reading List TIL: Cosmopolitan C Library, Distributed Systems Book, High Performance Browser Networking, and Rust Roguelike Tutorial
TIL: NuShell Structured Data Shell, Async Python Performance Reality, and Go Programming Fundamentals
2020-08-25 · via Stonecharioteer on Tech

Today’s discoveries challenged conventional wisdom about async programming while exploring innovative shell design and comprehensive language learning resources.

NuShell reimagines the command-line interface with structured data as a first-class concept:

Core Philosophy:

Structured Data Pipeline:

1
2
3
4
5
# Traditional shell - text-based
ps aux | grep python | awk '{print $2}' | head -5

# NuShell - structured data
ps | where name =~ python | select pid | first 5

Built-in Data Types:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# Working with JSON directly
http get https://api.github.com/repos/nushell/nushell | get stargazers_count

# CSV processing
open data.csv | where salary > 50000 | select name age department

# File system as structured data
ls | where size > 1mb | sort-by modified | reverse

# System information
sys | get host.name

Advanced Features:

Custom Commands:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
# Define custom command
def weather [city: string] {
    http get $"https://wttr.in/($city)?format=j1" | get current_condition.0
}

# Use custom command
weather "New York" | get temp_C

# Command with multiple parameters
def git-summary [--author(-a): string] {
    if ($author | is-empty) {
        git log --oneline | lines | length
    } else {
        git log --oneline --author $author | lines | length
    }
}

Data Transformation:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
# Convert between formats
open data.json | to csv | save data.csv
open config.toml | to json | save config.json

# Advanced filtering and grouping
open sales.csv
| where date >= 2023-01-01
| group-by region
| each { |group|
    {
        region: ($group.0),
        total_sales: ($group.1 | get amount | math sum),
        avg_sale: ($group.1 | get amount | math avg)
    }
}

Cross-Platform Compatibility:

1
2
3
4
5
6
7
8
9
# File operations work consistently across platforms
ls **/*.rs | where size > 10kb | get name

# Network operations with structured output
port 8080 | get state  # Check if port is open
which python | get path  # Find command location

# Environment variables as structured data
$env | where name =~ PATH | get value

Integration with Traditional Tools:

1
2
3
4
5
6
7
8
# Mix NuShell with external commands
docker ps | from ssv | where IMAGE =~ nginx

# Transform and pipe to traditional tools
ls | where name =~ ".log" | get name | lines | xargs tail -f

# Use traditional commands when needed
^ls -la /usr/bin | lines | length  # ^ prefix runs external command

Async Python Performance Reality

Async Python is Not Faster challenges common misconceptions about async programming:

Performance Myths vs Reality:

CPU-Bound Tasks:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import asyncio
import time
import threading
from concurrent.futures import ThreadPoolExecutor

# CPU-intensive function
def cpu_bound_task(n):
    """Simulate CPU-intensive work"""
    total = 0
    for i in range(n):
        total += i ** 2
    return total

# Synchronous version
def sync_cpu_test():
    start = time.time()
    results = [cpu_bound_task(100000) for _ in range(4)]
    end = time.time()
    return end - start, results

# Async version (misleading - still blocks)
async def async_cpu_test_wrong():
    start = time.time()
    results = [cpu_bound_task(100000) for _ in range(4)]  # Still synchronous!
    end = time.time()
    return end - start, results

# Proper async with thread pool
async def async_cpu_test_correct():
    start = time.time()
    loop = asyncio.get_event_loop()

    with ThreadPoolExecutor() as executor:
        tasks = [
            loop.run_in_executor(executor, cpu_bound_task, 100000)
            for _ in range(4)
        ]
        results = await asyncio.gather(*tasks)

    end = time.time()
    return end - start, results

# Benchmark results show:
# sync_cpu_test: ~2.1 seconds
# async_cpu_test_wrong: ~2.1 seconds (no improvement!)
# async_cpu_test_correct: ~0.6 seconds (real improvement through parallelism)

I/O-Bound Tasks - Where Async Shines:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import aiohttp
import requests

# Synchronous HTTP requests
def sync_http_test(urls):
    start = time.time()
    results = []
    for url in urls:
        response = requests.get(url)
        results.append(response.status_code)
    end = time.time()
    return end - start, results

# Async HTTP requests
async def async_http_test(urls):
    start = time.time()
    results = []

    async with aiohttp.ClientSession() as session:
        tasks = []
        for url in urls:
            tasks.append(fetch_url(session, url))
        results = await asyncio.gather(*tasks)

    end = time.time()
    return end - start, results

async def fetch_url(session, url):
    async with session.get(url) as response:
        return response.status

# Results for 10 HTTP requests:
# sync_http_test: ~5.2 seconds (sequential)
# async_http_test: ~1.1 seconds (concurrent)

Memory and Overhead Considerations:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import sys
import asyncio
import threading

def measure_memory_usage():
    """Compare memory usage of different approaches"""

    # Thread-based approach
    def thread_worker():
        time.sleep(1)

    threads = [threading.Thread(target=thread_worker) for _ in range(1000)]
    thread_memory = sys.getsizeof(threads) + sum(sys.getsizeof(t) for t in threads)

    # Async approach
    async def async_worker():
        await asyncio.sleep(1)

    tasks = [async_worker() for _ in range(1000)]
    task_memory = sys.getsizeof(tasks) + sum(sys.getsizeof(t) for t in tasks)

    print(f"1000 threads: ~{thread_memory} bytes")
    print(f"1000 async tasks: ~{task_memory} bytes")
    # Async tasks typically use much less memory

measure_memory_usage()

When to Use Async:

Good Use Cases:

  • High-concurrency I/O operations (web scraping, API calls)
  • Network servers handling many connections
  • Database operations with connection pooling
  • File I/O with many small files

Poor Use Cases:

  • CPU-intensive computations
  • Simple sequential programs
  • Legacy code integration
  • When debugging complexity isn’t worth performance gains

Go Programming Fundamentals

Go 101 provides comprehensive Go language education:

Core Go Concepts:

Goroutines and Channels:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package main

import (
    "fmt"
    "time"
)

// Producer goroutine
func producer(ch chan<- int) {
    for i := 1; i <= 5; i++ {
        ch <- i
        fmt.Printf("Produced: %d\n", i)
        time.Sleep(time.Millisecond * 500)
    }
    close(ch)
}

// Consumer goroutine
func consumer(ch <-chan int, done chan<- bool) {
    for value := range ch {
        fmt.Printf("Consumed: %d\n", value)
        time.Sleep(time.Millisecond * 300)
    }
    done <- true
}

func main() {
    ch := make(chan int, 2) // Buffered channel
    done := make(chan bool)

    go producer(ch)
    go consumer(ch, done)

    <-done // Wait for consumer to finish
    fmt.Println("All done!")
}

Interface-Based Design:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// Define behavior through interfaces
type Writer interface {
    Write([]byte) (int, error)
}

type Logger interface {
    Log(message string)
}

// Concrete implementations
type FileLogger struct {
    filename string
}

func (f *FileLogger) Log(message string) {
    // Write to file
    fmt.Printf("File: %s\n", message)
}

type ConsoleLogger struct{}

func (c *ConsoleLogger) Log(message string) {
    fmt.Printf("Console: %s\n", message)
}

// Function that works with any Logger
func doWork(logger Logger) {
    logger.Log("Starting work")
    // ... do work ...
    logger.Log("Work completed")
}

func main() {
    fileLogger := &FileLogger{filename: "app.log"}
    consoleLogger := &ConsoleLogger{}

    doWork(fileLogger)
    doWork(consoleLogger)
}

Error Handling Patterns:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import (
    "errors"
    "fmt"
)

// Custom error types
type ValidationError struct {
    Field string
    Value interface{}
    Reason string
}

func (v *ValidationError) Error() string {
    return fmt.Sprintf("validation failed for field '%s' with value '%v': %s",
                       v.Field, v.Value, v.Reason)
}

// Function with multiple return values
func validateUser(name string, age int) (*User, error) {
    if name == "" {
        return nil, &ValidationError{
            Field: "name",
            Value: name,
            Reason: "name cannot be empty",
        }
    }

    if age < 0 || age > 150 {
        return nil, &ValidationError{
            Field: "age",
            Value: age,
            Reason: "age must be between 0 and 150",
        }
    }

    return &User{Name: name, Age: age}, nil
}

// Error handling in action
func main() {
    user, err := validateUser("", 25)
    if err != nil {
        var validationErr *ValidationError
        if errors.As(err, &validationErr) {
            fmt.Printf("Validation error: %s\n", validationErr.Error())
        } else {
            fmt.Printf("Unknown error: %v\n", err)
        }
        return
    }

    fmt.Printf("Valid user: %+v\n", user)
}

Effective Technical Questions

How to ask questions of experts and gain more than just an answer provides guidance for productive technical discussions:

Question Framework:

Context-Rich Questions:

Poor: "My code doesn't work. Help!"

Better: "I'm trying to implement a REST API in Go using Gin framework.
When I send a POST request to /api/users, I get a 500 error. Here's my code:
[code snippet]. The error message is [specific error]. I've tried
[what you've attempted]. What might be causing this issue?"

Show Your Work:

Include:
- What you're trying to accomplish
- What you expected to happen
- What actually happened
- What you've already tried
- Minimal reproducible example
- Relevant error messages/logs
- Environment details (versions, OS, etc.)

Follow-Up Strategy:

1. Ask clarifying questions about the solution
2. Explain what you learned in your own words
3. Share how you applied the solution
4. Report back on results
5. Ask about related concepts or edge cases

These discoveries highlight the importance of understanding the true characteristics of tools and techniques rather than accepting conventional wisdom, while also providing practical frameworks for effective learning and communication.