@clawhub-xueyetianya-5e1be6a645
Lookup Redis commands by category, test Redis server connections, and monitor database key counts and memory usage, with offline cheatsheet support.
# redis **Redis Command Reference & Connection Tool** — Instantly look up Redis commands, test your connection, and monitor key statistics. Works offline too — shows the full cheatsheet even without a Redis instance. ## Commands | Command | Description | Example | |---------|-------------|---------| | `cheatsheet` | Display Redis command reference by category | `cheatsheet` / `cheatsheet string` | | `test` | Test a Redis connection and show server info | `test` / `test redis://localhost:6379` | | `monitor` | Show key count and memory stats per DB | `monitor` / `monitor localhost 6379` | ## Usage ```bash bash script.sh cheatsheet [category] bash script.sh test [host] [port] [password] bash script.sh monitor [host] [port] [password] ``` ## Categories for `cheatsheet` | Category | Commands Covered | |----------|-----------------| | `string` | SET, GET, MSET, INCR, APPEND, STRLEN, SETNX… | | `list` | LPUSH, RPUSH, LRANGE, LLEN, LPOP, BRPOP… | | `hash` | HSET, HGET, HMGET, HGETALL, HDEL, HKEYS… | | `set` | SADD, SMEMBERS, SISMEMBER, SUNION, SINTER… | | `zset` | ZADD, ZRANGE, ZRANK, ZSCORE, ZREM, ZCOUNT… | | `key` | DEL, EXISTS, EXPIRE, TTL, RENAME, TYPE, SCAN… | | `server` | INFO, DBSIZE, CONFIG GET, FLUSHDB, DEBUG… | | `scripting` | EVAL, EVALSHA, SCRIPT LOAD/EXISTS/FLUSH | ## Requirements - `bash` >= 4.0 - `redis-cli` (optional — required only for `test` and `monitor` commands; offline mode activates automatically if not found) ## Install Redis CLI ```bash # Debian/Ubuntu sudo apt install redis-tools # macOS brew install redis # Alpine apk add redis ``` ## Examples ``` $ bash script.sh cheatsheet string 🔴 Redis Cheatsheet — Strings ───────────────────────────────────────────── SET key value [EX seconds] [PX ms] [NX|XX] Set key to value. Options: EX (expire secs), NX (only if not exists) Example: SET user:1:name "Alice" EX 3600 GET key Get the value of a key. Returns nil if not exists. Example: GET user:1:name MSET key value [key value ...] Set multiple keys atomically. Example: MSET k1 v1 k2 v2 k3 v3 ... ``` ``` $ bash script.sh test localhost 6379 🔴 Redis Connection Test ───────────────────────────────────────────── Host : localhost Port : 6379 Status : ✅ CONNECTED Server Info: redis_version : 7.2.3 uptime_days : 4 connected_clients: 3 used_memory : 1.23M maxmemory : 0 (unlimited) role : master aof_enabled : 0 ``` ``` $ bash script.sh monitor 🔴 Redis Key Monitor ───────────────────────────────────────────── Host : localhost:6379 DB Keys Avg TTL ──────────────────── db0 1247 — db1 89 — Total keys : 1336 Memory : 4.56M ``` FILE:scripts/script.sh #!/usr/bin/env bash # redis skill - Redis command cheatsheet, connection test, key monitor # Usage: bash script.sh <cheatsheet|test|monitor> [args...] set -euo pipefail COMMAND="-" ARG1="-localhost" ARG2="-6379" ARG3="-" BOLD='\033[1m' RED_C='\033[0;31m' GREEN='\033[0;32m' CYAN='\033[0;36m' YELLOW='\033[1;33m' RESET='\033[0m' SEP="─────────────────────────────────────────────" REDIS_ICON="🔴" usage() { cat <<EOF BOLDredis skillRESET — Redis command reference & connection tool Commands: cheatsheet [category] Show Redis command reference test [host] [port] [pass] Test Redis connection monitor [host] [port] [pass] Show key statistics per DB Categories: string list hash set zset key server scripting Examples: bash script.sh cheatsheet bash script.sh cheatsheet string bash script.sh test localhost 6379 bash script.sh monitor 127.0.0.1 6379 mypassword EOF exit 0 } # ── Cheatsheet content ─────────────────────────────────────────────────────── show_cheatsheet_string() { cat <<'EOF' STRING COMMANDS ─────────────── SET key value [EX seconds] [PX ms] [NX|XX] Set key to value. Options: EX — expire in seconds PX — expire in milliseconds NX — only set if key does NOT exist XX — only set if key DOES exist Example: SET user:1:name "Alice" EX 3600 GET key Get the value of a key. Returns nil if not exists. Example: GET user:1:name MSET key value [key value ...] / MGET key [key ...] Set / get multiple keys atomically. Example: MSET k1 v1 k2 v2 MGET k1 k2 INCR key / INCRBY key n / INCRBYFLOAT key f Atomically increment a numeric value. Example: INCR pageviews:home INCRBY stock:item1 -5 APPEND key value Append value to existing string. Example: APPEND log:today "entry\n" STRLEN key Return the length of the string at key. Example: STRLEN user:1:name SETNX key value Set key only if it does not exist (legacy; use SET ... NX). Example: SETNX lock:job 1 GETEX key [EX s|PX ms|EXAT ts|PERSIST] Get value and set/reset expiry (Redis 6.2+). Example: GETEX session:abc EX 1800 GETDEL key Get value and delete the key atomically. Example: GETDEL one_time_token EOF } show_cheatsheet_list() { cat <<'EOF' LIST COMMANDS ───────────── LPUSH key val [val ...] / RPUSH key val [val ...] Push values to the left/right of the list. Example: RPUSH queue:jobs job1 job2 job3 LPOP key [count] / RPOP key [count] Remove and return elements from left/right. Example: LPOP queue:jobs RPOP queue:jobs 3 LRANGE key start stop Get a range of elements (0-indexed, -1 = last). Example: LRANGE mylist 0 -1 LLEN key Return the length of the list. Example: LLEN queue:jobs LINDEX key index Get element at index. Example: LINDEX mylist 0 LSET key index value Set element at index. Example: LSET mylist 0 "newval" LINSERT key BEFORE|AFTER pivot value Insert value before/after pivot element. LREM key count value Remove count occurrences of value. BLPOP key [key ...] timeout / BRPOP key [key ...] timeout Blocking left/right pop — useful for queues. Example: BLPOP queue:jobs 5 EOF } show_cheatsheet_hash() { cat <<'EOF' HASH COMMANDS ───────────── HSET key field value [field value ...] Set one or more hash fields. Example: HSET user:1 name "Alice" age 30 email "[email protected]" HGET key field Get the value of a hash field. Example: HGET user:1 name HMGET key field [field ...] Get multiple hash fields. Example: HMGET user:1 name age HGETALL key Get all fields and values. Example: HGETALL user:1 HDEL key field [field ...] Delete hash fields. Example: HDEL user:1 email HEXISTS key field Check if field exists (returns 0 or 1). HKEYS key / HVALS key / HLEN key Get all fields / values / count. HINCRBY key field n / HINCRBYFLOAT key field f Increment a numeric hash field. Example: HINCRBY user:1 logincount 1 HSCAN key cursor [MATCH pattern] [COUNT n] Iteratively scan hash fields (safe for large hashes). EOF } show_cheatsheet_set() { cat <<'EOF' SET COMMANDS ──────────── SADD key member [member ...] Add one or more members to a set. Example: SADD tags:post1 redis nosql cache SMEMBERS key Return all members of a set. Example: SMEMBERS tags:post1 SISMEMBER key member / SMISMEMBER key member [member ...] Check membership. Example: SISMEMBER tags:post1 redis SREM key member [member ...] Remove members from a set. SCARD key Return the number of members. SUNION key [key ...] / SUNIONSTORE dest key [key ...] Union of multiple sets. Example: SUNION tags:post1 tags:post2 SINTER key [key ...] / SINTERSTORE dest key [key ...] Intersection of multiple sets. SDIFF key [key ...] / SDIFFSTORE dest key [key ...] Difference of sets. SRANDMEMBER key [count] Get random member(s). SSCAN key cursor [MATCH pattern] [COUNT n] Iteratively scan set members. EOF } show_cheatsheet_zset() { cat <<'EOF' SORTED SET (ZSET) COMMANDS ─────────────────────────── ZADD key [NX|XX] [GT|LT] [CH] [INCR] score member [score member ...] Add members with scores. Example: ZADD leaderboard 1500 "alice" 2000 "bob" ZRANGE key start stop [BYSCORE|BYLEX] [REV] [LIMIT offset count] [WITHSCORES] Get members by rank, score, or lex range (Redis 6.2+). Example: ZRANGE leaderboard 0 -1 WITHSCORES REV ZRANK key member / ZREVRANK key member Get the rank of a member (0-indexed). ZSCORE key member Get the score of a member. ZINCRBY key increment member Increment the score of a member. Example: ZINCRBY leaderboard 50 "alice" ZREM key member [member ...] Remove members. ZCOUNT key min max Count members with scores between min and max. Example: ZCOUNT leaderboard 1000 2000 ZPOPMIN key [count] / ZPOPMAX key [count] Remove and return members with lowest/highest scores. ZCARD key Return number of members. ZSCAN key cursor [MATCH pattern] [COUNT n] Iteratively scan sorted set members. EOF } show_cheatsheet_key() { cat <<'EOF' KEY COMMANDS ──────────── DEL key [key ...] Delete one or more keys. Example: DEL user:1 session:abc EXISTS key [key ...] Check if key(s) exist. Returns count of existing keys. Example: EXISTS user:1 EXPIRE key seconds / PEXPIRE key ms Set expiry in seconds / milliseconds. Example: EXPIRE session:abc 1800 EXPIREAT key unix-time / PEXPIREAT key unix-ms Set expiry to a Unix timestamp. TTL key / PTTL key Get remaining TTL in seconds / milliseconds. Returns -1 (no expiry) or -2 (key does not exist). PERSIST key Remove expiry from a key (make it permanent). RENAME key newkey / RENAMENX key newkey Rename a key (NX variant: only if newkey does not exist). TYPE key Return the type of a key: string, list, hash, set, zset, stream. OBJECT ENCODING key Show internal encoding (e.g., ziplist, listpack, hashtable). SCAN cursor [MATCH pattern] [COUNT n] [TYPE type] Iteratively scan all keys safely (preferred over KEYS in prod). Example: SCAN 0 MATCH user:* COUNT 100 KEYS pattern Find all keys matching a glob pattern. ⚠️ Use SCAN in production — KEYS blocks the server. Example: KEYS session:* DUMP key / RESTORE key ttl serialized Serialize / deserialize a key's value. COPY source dest [DB db] [REPLACE] Copy a key to another key or database. OBJECT FREQ key / OBJECT IDLETIME key Get LFU frequency or idle time of a key. EOF } show_cheatsheet_server() { cat <<'EOF' SERVER COMMANDS ─────────────── INFO [section] Get server information and statistics. Sections: server, clients, memory, stats, replication, cpu, keyspace Example: INFO memory DBSIZE Return the number of keys in the selected database. SELECT db Switch to a database (0-15 by default). Example: SELECT 1 FLUSHDB [ASYNC|SYNC] Delete all keys in the current database. ⚠️ Irreversible! FLUSHALL [ASYNC|SYNC] Delete all keys in all databases. ⚠️ Irreversible! CONFIG GET parameter Get config values (supports glob). Example: CONFIG GET maxmemory CONFIG GET save CONFIG SET parameter value Set a config value at runtime. Example: CONFIG SET maxmemory 512mb CONFIG REWRITE Persist current config to redis.conf. DEBUG SLEEP seconds Make the server sleep (for testing). COMMAND COUNT / COMMAND INFO cmd [cmd ...] Get count of commands / info about specific commands. SLOWLOG GET [count] / SLOWLOG RESET Get / reset the slow query log. MONITOR Stream all commands received by the server (debugging only). ⚠️ High overhead — do not use in production. BGSAVE / BGREWRITEAOF Trigger background RDB save / AOF rewrite. LASTSAVE Get Unix timestamp of last successful RDB save. REPLICAOF host port / REPLICAOF NO ONE Configure replication. EOF } show_cheatsheet_scripting() { cat <<'EOF' SCRIPTING COMMANDS ────────────────── EVAL script numkeys [key [key ...]] [arg [arg ...]] Execute a Lua script. KEYS and ARGV are 1-indexed inside the script. Example: EVAL "return redis.call('GET', KEYS[1])" 1 mykey EVALSHA sha1 numkeys [key ...] [arg ...] Execute a script by its SHA1 hash (cached on server). Example: EVALSHA abc123def 1 mykey SCRIPT LOAD script Load a script into the cache without executing it. Returns the SHA1 hash. SCRIPT EXISTS sha1 [sha1 ...] Check if scripts are cached (returns 0/1 per sha1). SCRIPT FLUSH [ASYNC|SYNC] Remove all cached scripts. SCRIPT KILL Kill the currently running script (if it hasn't written). FCALL function numkeys [key ...] [arg ...] Call a Redis Function (Redis 7.0+). Example: FCALL myfunc 1 mykey FUNCTION LIST [LIBRARYNAME name] [WITHCODE] List registered functions/libraries. FUNCTION LOAD [REPLACE] function-code Load a function library from Lua code. FUNCTION DELETE library-name Delete a function library. EOF } do_cheatsheet() { local cat="-all" local cat_lower cat_lower="$(echo "$cat" | tr '[:upper:]' '[:lower:]')" echo -e "\nBOLDREDIS_ICON Redis Cheatsheet+ — ${cat^^}RESET" echo "$SEP" case "$cat_lower" in string|str) show_cheatsheet_string ;; list) show_cheatsheet_list ;; hash) show_cheatsheet_hash ;; set) show_cheatsheet_set ;; zset|sorted) show_cheatsheet_zset ;; key|keys) show_cheatsheet_key ;; server|srv) show_cheatsheet_server ;; scripting|lua|script) show_cheatsheet_scripting ;; all|"") show_cheatsheet_string show_cheatsheet_list show_cheatsheet_hash show_cheatsheet_set show_cheatsheet_zset show_cheatsheet_key show_cheatsheet_server show_cheatsheet_scripting ;; *) echo -e "YELLOWUnknown category: $catRESET" echo "Available: string list hash set zset key server scripting all" exit 1 ;; esac echo } # ── Connection helpers ──────────────────────────────────────────────────────── check_redis_cli() { if ! command -v redis-cli &>/dev/null; then echo -e "YELLOW⚠️ redis-cli not found.RESET" echo "Install with:" echo " Ubuntu/Debian : sudo apt install redis-tools" echo " macOS : brew install redis" echo " Alpine : apk add redis" return 1 fi return 0 } build_redis_cmd() { local host="$1" local port="$2" local pass="$3" local cmd="redis-cli -h $host -p $port" if [[ -n "$pass" ]]; then cmd="$cmd -a $pass --no-auth-warning" fi echo "$cmd" } do_test() { local host="-localhost" local port="-6379" local pass="-" echo -e "\nBOLDREDIS_ICON Redis Connection TestRESET" echo "$SEP" echo -e "Host : CYAN$hostRESET" echo -e "Port : CYAN$portRESET" if ! check_redis_cli; then return 1 fi RCMD="$(build_redis_cmd "$host" "$port" "$pass")" # Test PING PONG="$($RCMD PING 2>&1 || true)" if [[ "$PONG" == "PONG" ]]; then echo -e "Status : GREEN✅ CONNECTEDRESET" else echo -e "Status : RED_C❌ FAILEDRESET" echo -e "Response : $PONG" echo echo "Troubleshooting:" echo " • Is Redis running? sudo systemctl status redis" echo " • Is the port open? ss -tlnp | grep $port" echo " • Is auth required? redis-cli -h $host -p $port -a <password> PING" return 1 fi echo echo -e "BOLDServer Info:RESET" # Parse INFO output INFO="$($RCMD INFO server INFO clients INFO memory INFO replication 2>&1 || true)" extract() { echo "$INFO" | grep "^1:" | head -1 | cut -d: -f2 | tr -d '[:space:]' } ver="$(extract redis_version)" uptime="$(extract uptime_in_days)" clients="$(extract connected_clients)" mem="$(extract used_memory_human)" maxmem="$(extract maxmemory_human)" role="$(extract role)" aof="$(extract aof_enabled)" [[ -n "$ver" ]] && printf " %-22s: %s\n" "redis_version" "$ver" [[ -n "$uptime" ]] && printf " %-22s: %s days\n" "uptime" "$uptime" [[ -n "$clients" ]] && printf " %-22s: %s\n" "connected_clients" "$clients" [[ -n "$mem" ]] && printf " %-22s: %s\n" "used_memory" "$mem" if [[ -n "$maxmem" && "$maxmem" != "0B" ]]; then printf " %-22s: %s\n" "maxmemory" "$maxmem" else printf " %-22s: 0 (unlimited)\n" "maxmemory" fi [[ -n "$role" ]] && printf " %-22s: %s\n" "role" "$role" [[ -n "$aof" ]] && printf " %-22s: %s\n" "aof_enabled" "$aof" echo } do_monitor() { local host="-localhost" local port="-6379" local pass="-" echo -e "\nBOLDREDIS_ICON Redis Key MonitorRESET" echo "$SEP" echo -e "Host : CYAN$host:$portRESET" echo if ! check_redis_cli; then return 1 fi RCMD="$(build_redis_cmd "$host" "$port" "$pass")" # Test connection first PONG="$($RCMD PING 2>&1 || true)" if [[ "$PONG" != "PONG" ]]; then echo -e "RED_C❌ Cannot connect to Redis at $host:$portRESET" echo "Run: bash script.sh test $host $port" return 1 fi # Get keyspace info KEYSPACE="$($RCMD INFO keyspace 2>&1 || true)" MEMORY="$($RCMD INFO memory 2>&1 | grep used_memory_human | head -1 | cut -d: -f2 | tr -d '[:space:]' || true)" DBSIZE="$($RCMD DBSIZE 2>&1 || true)" printf "%-6s %-8s %s\n" "DB" "Keys" "Avg TTL" printf "%-6s %-8s %s\n" "────" "────────" "────────" TOTAL=0 if echo "$KEYSPACE" | grep -q "^db"; then while IFS= read -r line; do if [[ "$line" =~ ^db([0-9]+):keys=([0-9]+) ]]; then dbnum="BASH_REMATCH[1]" keys="BASH_REMATCH[2]" TOTAL=$((TOTAL + keys)) # Extract avg_ttl if present avg_ttl="—" if [[ "$line" =~ avg_ttl=([0-9]+) ]]; then ttl_ms="BASH_REMATCH[1]" if [[ "$ttl_ms" -gt 0 ]]; then avg_ttl="ttl_msms" fi fi printf "%-6s %-8s %s\n" "dbdbnum" "$keys" "$avg_ttl" fi done < <(echo "$KEYSPACE") else printf "%-6s %-8s %s\n" "db0" "$DBSIZE" "—" TOTAL="$DBSIZE" fi echo echo -e "Total keys : BOLD$TOTALRESET" echo -e "Memory : BOLD-unknownRESET" echo } # ── Main ───────────────────────────────────────────────────────────────────── case "$COMMAND" in cheatsheet|cs|ref) do_cheatsheet "-all" ;; test|ping|connect) do_test ;; monitor|stats|keys) do_monitor ;; help|--help|-h|"") usage ;; *) echo -e "RED_CUnknown command: $COMMANDRESET" echo "Run: bash script.sh help" exit 1 ;; esac
Generate 7-day learning plans, quizzes, and track your study progress locally for 20+ topics without needing an internet connection or account.
# education
**Learning Plan Generator** — Generate structured learning paths, quizzes, and track your study progress — all stored locally, no account required.
## Commands
| Command | Description | Example |
|---------|-------------|---------|
| `plan` | Generate a structured learning plan for a topic | `plan "Python for Data Science"` |
| `quiz` | Generate quiz questions to test your knowledge | `quiz "Python for Data Science" 5` |
| `progress` | Track and display your study progress | `progress show` / `progress done "Day 1"` |
## Usage
```bash
bash script.sh plan "topic name"
bash script.sh quiz "topic name" [num_questions]
bash script.sh progress show
bash script.sh progress done "milestone name"
bash script.sh progress reset
```
## Features
- Generates 7-day learning plans with daily goals and curated free resources
- Covers 20+ topic areas: programming languages, frameworks, DevOps, math, and more
- Quiz generator with multiple-choice and open-ended questions
- Local JSON progress tracking (stored in `~/.local/share/education-skill/progress.json`)
- No internet required — all content is built-in
## Requirements
- `bash` >= 4.0
- `python3` >= 3.7
- No external packages required (uses only stdlib)
## Examples
```
$ bash script.sh plan "Docker"
📚 Learning Plan: Docker
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Duration : 7 days
Level : Beginner → Intermediate
Day 1: Introduction to Containers
Goals:
• Understand what containers are vs VMs
• Install Docker Desktop / Docker Engine
• Run your first container: docker run hello-world
Resources:
• Docker Official Docs — Get Started: https://docs.docker.com/get-started/
• Play with Docker (free browser sandbox): https://labs.play-with-docker.com/
...
```
```
$ bash script.sh quiz "Python" 3
📝 Quiz: Python (3 questions)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Q1. What is the output of: print(type([]))
A) <class 'tuple'>
B) <class 'list'> ✓
C) <class 'array'>
D) <class 'dict'>
Q2. Which keyword is used to define a function in Python?
A) function
B) fn
C) def ✓
D) lambda
...
```
```
$ bash script.sh progress show
📊 Study Progress
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Topic : Docker
Started : 2024-01-15
Completed : Day 1, Day 2
Remaining : Day 3, Day 4, Day 5, Day 6, Day 7
Progress : ██████░░░░░░░░░░░░░░ 2/7 days (29%)
```
FILE:scripts/script.sh
#!/usr/bin/env bash
# education skill - Learning plan generator, quiz, progress tracker
# Usage: bash script.sh <plan|quiz|progress> [args...]
set -euo pipefail
COMMAND="-"
ARG1="-"
ARG2="-"
BOLD='\033[1m'
CYAN='\033[0;36m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
RESET='\033[0m'
STORAGE_DIR="HOME/.local/share/education-skill"
PROGRESS_FILE="STORAGE_DIR/progress.json"
usage() {
cat <<EOF
BOLDeducation skillRESET — Learning plan generator & progress tracker
Commands:
plan <topic> Generate a 7-day learning plan
quiz <topic> [num] Generate quiz questions (default: 5)
progress show Show current progress
progress done "<milestone>" Mark a milestone as completed
progress reset Reset progress
Examples:
bash script.sh plan "Python"
bash script.sh quiz "Docker" 3
bash script.sh progress show
bash script.sh progress done "Day 1"
EOF
exit 0
}
# ── Python core ──────────────────────────────────────────────────────────────
run_python() {
python3 -u - "$@" <<'PYEOF'
import sys
import json
import os
import re
import hashlib
import datetime
cmd = sys.argv[1]
args = sys.argv[2:]
STORAGE_DIR = os.path.expanduser("~/.local/share/education-skill")
PROGRESS_FILE = os.path.join(STORAGE_DIR, "progress.json")
BOLD = "\033[1m"
GREEN = "\033[0;32m"
CYAN = "\033[0;36m"
YELLOW= "\033[1;33m"
RED = "\033[0;31m"
RESET = "\033[0m"
BAR = "━" * 42
# ── Knowledge base ────────────────────────────────────────────────────────────
PLANS = {
"_default": {
"days": [
{"title": "Foundations & Setup",
"goals": ["Understand the core concepts", "Set up your environment", "Complete a hello-world example"],
"resources": ["Official documentation (search: '{topic} official docs')",
"freeCodeCamp YouTube channel", "Wikipedia overview article"]},
{"title": "Core Concepts Deep Dive",
"goals": ["Study the main concepts in detail", "Take notes on key terminology", "Find 3 real-world use cases"],
"resources": ["Official tutorial (Getting Started section)",
"MDN Web Docs / language reference"]},
{"title": "Hands-On Practice",
"goals": ["Build a small project", "Solve 3 beginner exercises", "Review solutions and patterns"],
"resources": ["Exercism.io — free coding exercises", "Codewars — kata challenges"]},
{"title": "Intermediate Topics",
"goals": ["Explore advanced features", "Read source code of a popular library", "Understand error handling"],
"resources": ["Official advanced guides", "Dev.to articles on the topic"]},
{"title": "Real-World Project",
"goals": ["Build a slightly larger project", "Use best practices", "Write basic tests"],
"resources": ["GitHub — search for '{topic} examples'", "Stack Overflow Q&A"]},
{"title": "Community & Ecosystem",
"goals": ["Explore popular libraries/tools", "Read changelog / release notes", "Join a community forum"],
"resources": ["Reddit r/{topic}", "Official community forums or Discord"]},
{"title": "Review & Next Steps",
"goals": ["Review all notes", "Identify gaps — revisit weak areas", "Plan your next learning goal"],
"resources": ["Your own notes", "Roadmap.sh — structured roadmaps"]},
]
},
"python": {
"days": [
{"title": "Python Basics",
"goals": ["Install Python 3 and set up a virtual env", "Learn variables, types, and control flow", "Write your first script"],
"resources": ["Python Official Tutorial: https://docs.python.org/3/tutorial/",
"freeCodeCamp Python Full Course (YouTube)"]},
{"title": "Functions & Modules",
"goals": ["Define and call functions", "Understand scope and closures", "Import standard library modules"],
"resources": ["Real Python — Functions: https://realpython.com/defining-your-own-python-function/",
"Python stdlib docs: https://docs.python.org/3/library/"]},
{"title": "Data Structures",
"goals": ["Master lists, dicts, sets, tuples", "List comprehensions and generators", "Practice with LeetCode easy problems"],
"resources": ["Python Data Structures docs", "Exercism Python track: https://exercism.org/tracks/python"]},
{"title": "OOP in Python",
"goals": ["Classes, inheritance, dunder methods", "dataclasses and properties", "Build a small OOP project"],
"resources": ["Real Python OOP guide", "Python docs: classes"]},
{"title": "File I/O & Error Handling",
"goals": ["Read/write files with context managers", "Exception handling patterns", "JSON and CSV processing"],
"resources": ["Python exceptions docs", "Real Python file I/O guide"]},
{"title": "Testing & Packaging",
"goals": ["Write tests with pytest", "Package a module with pyproject.toml", "Run CI with GitHub Actions"],
"resources": ["pytest docs: https://docs.pytest.org/", "Python Packaging Guide: https://packaging.python.org/"]},
{"title": "Python Ecosystem",
"goals": ["Explore pip, virtualenv, poetry", "Intro to popular libs: requests, click, pydantic", "Build and share a small CLI tool"],
"resources": ["Awesome Python: https://awesome-python.com/", "PyPI: https://pypi.org/"]},
]
},
"docker": {
"days": [
{"title": "Containers & Docker Basics",
"goals": ["Understand containers vs VMs", "Install Docker Engine", "Run: docker run hello-world"],
"resources": ["Docker Get Started: https://docs.docker.com/get-started/",
"Play with Docker: https://labs.play-with-docker.com/"]},
{"title": "Images & Dockerfile",
"goals": ["Pull and inspect images", "Write your first Dockerfile", "Build and tag an image"],
"resources": ["Dockerfile reference: https://docs.docker.com/engine/reference/builder/",
"Docker Hub: https://hub.docker.com/"]},
{"title": "Containers & Networking",
"goals": ["Run containers with port mapping", "Understand bridge networks", "Link containers together"],
"resources": ["Docker networking docs: https://docs.docker.com/network/"]},
{"title": "Volumes & Data",
"goals": ["Bind mounts vs named volumes", "Persist database data", "Inspect volumes"],
"resources": ["Docker storage docs: https://docs.docker.com/storage/"]},
{"title": "Docker Compose",
"goals": ["Write docker-compose.yml", "Multi-container apps (app + db)", "docker compose up/down/logs"],
"resources": ["Compose docs: https://docs.docker.com/compose/",
"Awesome Compose examples: https://github.com/docker/awesome-compose"]},
{"title": "Best Practices & Security",
"goals": ["Multi-stage builds", "Minimize image size", "Scan images with docker scout"],
"resources": ["Docker best practices: https://docs.docker.com/develop/dev-best-practices/"]},
{"title": "Kubernetes Intro",
"goals": ["Understand k8s vs Docker Compose", "Run a pod with kubectl", "Explore minikube locally"],
"resources": ["Kubernetes official tutorial: https://kubernetes.io/docs/tutorials/",
"KillerCoda free k8s labs: https://killercoda.com/"]},
]
},
"javascript": {
"days": [
{"title": "JS Fundamentals",
"goals": ["Variables (let/const/var), types", "Control flow and functions", "Run JS in browser and Node.js"],
"resources": ["MDN JavaScript Guide: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide",
"javascript.info: https://javascript.info/"]},
{"title": "Arrays & Objects",
"goals": ["Array methods: map, filter, reduce", "Object destructuring and spread", "Practice on Exercism"],
"resources": ["MDN Array reference", "javascript.info Objects"]},
{"title": "Async JavaScript",
"goals": ["Callbacks, Promises, async/await", "fetch() API basics", "Error handling in async code"],
"resources": ["javascript.info Promises: https://javascript.info/promise-basics",
"MDN async/await guide"]},
{"title": "DOM & Browser APIs",
"goals": ["Select and modify DOM elements", "Event listeners", "LocalStorage and SessionStorage"],
"resources": ["MDN DOM API", "javascript30.com — 30 vanilla JS projects"]},
{"title": "Modern JS (ES6+)",
"goals": ["Modules (import/export)", "Classes and iterators", "Optional chaining and nullish coalescing"],
"resources": ["javascript.info Modern JS"]},
{"title": "Node.js & npm",
"goals": ["Create an HTTP server", "Use npm packages", "Build a small CLI tool"],
"resources": ["Node.js Getting Started: https://nodejs.org/en/docs/guides/getting-started-guide",
"npm docs: https://docs.npmjs.com/"]},
{"title": "Testing & Tooling",
"goals": ["Write tests with Jest", "Lint with ESLint", "Bundle with Vite or esbuild"],
"resources": ["Jest docs: https://jestjs.io/", "ESLint: https://eslint.org/"]},
]
},
"go": {
"days": [
{"title": "Go Basics",
"goals": ["Install Go, run hello world", "Variables, types, functions", "Understand packages and imports"],
"resources": ["A Tour of Go: https://go.dev/tour/", "Go by Example: https://gobyexample.com/"]},
{"title": "Control Flow & Arrays",
"goals": ["for loops (only loop in Go)", "Arrays, slices, maps", "Structs and methods"],
"resources": ["Go by Example: https://gobyexample.com/"]},
{"title": "Interfaces & Error Handling",
"goals": ["Define and implement interfaces", "Error type and idiomatic handling", "Multiple return values"],
"resources": ["Effective Go: https://go.dev/doc/effective_go"]},
{"title": "Goroutines & Channels",
"goals": ["Launch goroutines", "Send/receive on channels", "Select statement"],
"resources": ["Go concurrency guide: https://go.dev/blog/concurrency-is-not-parallelism"]},
{"title": "Standard Library",
"goals": ["net/http — build a web server", "encoding/json — marshal/unmarshal", "os and io packages"],
"resources": ["Go stdlib reference: https://pkg.go.dev/std"]},
{"title": "Testing & Modules",
"goals": ["Write tests with testing package", "Benchmarks and examples", "Manage deps with go.mod"],
"resources": ["Go testing docs: https://pkg.go.dev/testing"]},
{"title": "Real-World Go",
"goals": ["Build a REST API", "Explore popular libs: chi, sqlx, zap", "Deploy with Docker"],
"resources": ["Awesome Go: https://awesome-go.com/"]},
]
},
}
QUIZZES = {
"_default": [
{"q": "What does '{topic}' primarily help with?", "options": ["A) General purpose", "B) Specific domain tasks", "C) Both A and B", "D) Neither"], "ans": "C"},
{"q": "Which is a best practice when learning '{topic}'?", "options": ["A) Reading only theory", "B) Hands-on practice with projects", "C) Memorizing syntax", "D) Avoiding documentation"], "ans": "B"},
{"q": "What is the first step when starting with '{topic}'?", "options": ["A) Advanced optimization", "B) Setting up the environment", "C) Production deployment", "D) Team coordination"], "ans": "B"},
{"q": "How do you handle errors in most '{topic}' workflows?", "options": ["A) Ignore them", "B) Crash and restart", "C) Log and handle gracefully", "D) Delete the code"], "ans": "C"},
{"q": "Where can you find community help for '{topic}'?", "options": ["A) Only paid courses", "B) Official docs and community forums", "C) Only YouTube", "D) Only books"], "ans": "B"},
],
"python": [
{"q": "What is the output of: print(type([]))", "options": ["A) <class 'tuple'>", "B) <class 'list'>", "C) <class 'array'>", "D) <class 'dict'>"], "ans": "B"},
{"q": "Which keyword defines a function in Python?", "options": ["A) function", "B) fn", "C) def", "D) lambda"], "ans": "C"},
{"q": "What does list(range(3)) return?", "options": ["A) [1, 2, 3]", "B) [0, 1, 2]", "C) [0, 1, 2, 3]", "D) [1, 2]"], "ans": "B"},
{"q": "How do you open a file safely in Python?", "options": ["A) f = open('x')", "B) with open('x') as f:", "C) file.open('x')", "D) import open('x')"], "ans": "B"},
{"q": "What does 'self' refer to in a class method?", "options": ["A) The class itself", "B) The instance of the class", "C) A global variable", "D) The parent class"], "ans": "B"},
{"q": "Which is a valid list comprehension?", "options": ["A) [x*2 for x in range(5)]", "B) {x*2 : range(5)}", "C) list(x*2, range(5))", "D) (x*2 range(5))"], "ans": "A"},
{"q": "What does 'pip install requests' do?", "options": ["A) Installs Python", "B) Installs the requests HTTP library", "C) Runs an HTTP request", "D) Updates pip itself"], "ans": "B"},
],
"docker": [
{"q": "What command runs a Docker container interactively?", "options": ["A) docker start -i", "B) docker run -it", "C) docker exec bash", "D) docker attach"], "ans": "B"},
{"q": "What does a Dockerfile FROM instruction specify?", "options": ["A) Output directory", "B) Base image", "C) Port to expose", "D) Entry command"], "ans": "B"},
{"q": "How do you list running containers?", "options": ["A) docker list", "B) docker ps", "C) docker show", "D) docker containers"], "ans": "B"},
{"q": "What is the purpose of EXPOSE in a Dockerfile?", "options": ["A) Opens firewall port", "B) Documents that a port is used", "C) Binds port to host", "D) Starts a service"], "ans": "B"},
{"q": "What file does Docker Compose read by default?", "options": ["A) dockerfile.yml", "B) compose.yaml or docker-compose.yml", "C) container.json", "D) services.yml"], "ans": "B"},
{"q": "How do you stop and remove all compose services?", "options": ["A) docker stop all", "B) docker compose down", "C) docker rm -f", "D) docker purge"], "ans": "B"},
{"q": "What does a named volume do?", "options": ["A) Exposes a port", "B) Persists data across container restarts", "C) Sets environment vars", "D) Limits CPU usage"], "ans": "B"},
],
"javascript": [
{"q": "What does 'typeof null' return in JavaScript?", "options": ["A) 'null'", "B) 'object'", "C) 'undefined'", "D) 'number'"], "ans": "B"},
{"q": "Which array method returns a new array with transformed elements?", "options": ["A) filter()", "B) map()", "C) reduce()", "D) find()"], "ans": "B"},
{"q": "What is the correct way to declare a constant?", "options": ["A) var x = 1", "B) let x = 1", "C) const x = 1", "D) int x = 1"], "ans": "C"},
{"q": "What does async/await help with?", "options": ["A) Synchronous code", "B) Writing asynchronous code more readably", "C) Type checking", "D) Memory management"], "ans": "B"},
{"q": "Which method adds an element to the end of an array?", "options": ["A) unshift()", "B) push()", "C) append()", "D) add()"], "ans": "B"},
],
"go": [
{"q": "What is Go's only loop keyword?", "options": ["A) while", "B) loop", "C) for", "D) each"], "ans": "C"},
{"q": "How do you declare an error in Go?", "options": ["A) throw new Error()", "B) raise Exception()", "C) return fmt.Errorf('msg')", "D) panic('msg')"], "ans": "C"},
{"q": "What does 'go' keyword do before a function call?", "options": ["A) Imports a package", "B) Starts a goroutine", "C) Defines a method", "D) Runs tests"], "ans": "B"},
{"q": "How do you handle multiple return values in Go?", "options": ["A) result, _ := fn()", "B) result = fn()", "C) [result, err] = fn()", "D) fn() -> result, err"], "ans": "A"},
{"q": "What is the zero value of a string in Go?", "options": ['A) null', 'B) ""', 'C) None', 'D) undefined'], "ans": "B"},
],
}
# ── Helper functions ─────────────────────────────────────────────────────────
def load_progress():
if os.path.exists(PROGRESS_FILE):
with open(PROGRESS_FILE) as f:
return json.load(f)
return {"topic": None, "started": None, "completed": []}
def save_progress(data):
os.makedirs(os.path.dirname(PROGRESS_FILE), exist_ok=True)
with open(PROGRESS_FILE, 'w') as f:
json.dump(data, f, indent=2)
def get_plan(topic):
key = topic.lower().strip()
for k in PLANS:
if k != "_default" and k in key:
return PLANS[k]
return PLANS["_default"]
def get_quizzes(topic):
key = topic.lower().strip()
for k in QUIZZES:
if k != "_default" and k in key:
return QUIZZES[k]
return QUIZZES["_default"]
def progress_bar(done, total, width=20):
filled = int(width * done / total) if total else 0
return "█" * filled + "░" * (width - filled)
# ── Commands ─────────────────────────────────────────────────────────────────
if cmd == "plan":
topic = args[0] if args else "General"
plan = get_plan(topic)
print(f"\n{BOLD}📚 Learning Plan: {topic}{RESET}")
print(BAR)
print(f"Duration : 7 days")
print(f"Level : Beginner → Intermediate\n")
for i, day in enumerate(plan["days"], 1):
print(f"{BOLD}Day {i}: {day['title']}{RESET}")
print(f" {CYAN}Goals:{RESET}")
for g in day["goals"]:
print(f" • {g.replace('{topic}', topic)}")
print(f" {CYAN}Resources:{RESET}")
for r in day["resources"]:
print(f" → {r.replace('{topic}', topic)}")
print()
print(f"{YELLOW}Tip:{RESET} Use 'bash script.sh progress done \"Day N\"' to track your progress.")
print()
elif cmd == "quiz":
topic = args[0] if args else "General"
num = int(args[1]) if len(args) > 1 else 5
pool = get_quizzes(topic)
# Deterministically select questions
selected = pool[:num] if num <= len(pool) else pool * (num // len(pool) + 1)
selected = selected[:num]
print(f"\n{BOLD}📝 Quiz: {topic} ({num} questions){RESET}")
print(BAR + "\n")
for i, q in enumerate(selected, 1):
question = q["q"].replace("{topic}", topic)
print(f"{BOLD}Q{i}. {question}{RESET}")
ans_key = q["ans"]
for opt in q["options"]:
letter = opt[0]
if letter == ans_key:
print(f" {GREEN}{opt} ✓{RESET}")
else:
print(f" {opt}")
print()
elif cmd == "progress":
subcmd = args[0] if args else "show"
if subcmd == "show":
data = load_progress()
topic = data.get("topic") or "—"
started = data.get("started") or "—"
completed = data.get("completed") or []
plan = get_plan(topic) if data.get("topic") else get_plan("_default")
total = len(plan["days"])
done_n = len(completed)
print(f"\n{BOLD}📊 Study Progress{RESET}")
print(BAR)
print(f"Topic : {topic}")
print(f"Started : {started}")
if completed:
print(f"Completed : {', '.join(completed)}")
else:
print(f"Completed : (none yet)")
bar = progress_bar(done_n, total)
pct = int(100 * done_n / total) if total else 0
print(f"Progress : {GREEN}{bar}{RESET} {done_n}/{total} days ({pct}%)")
print()
elif subcmd == "done":
milestone = args[1] if len(args) > 1 else "Day 1"
data = load_progress()
if not data.get("topic"):
data["topic"] = "General"
data["started"] = str(datetime.date.today())
if milestone not in data["completed"]:
data["completed"].append(milestone)
save_progress(data)
print(f"{GREEN}✅ Marked as done: {milestone}{RESET}")
else:
print(f"{YELLOW}Already completed: {milestone}{RESET}")
elif subcmd == "reset":
save_progress({"topic": None, "started": None, "completed": []})
print(f"{YELLOW}Progress reset.{RESET}")
elif subcmd == "set-topic":
topic = args[1] if len(args) > 1 else "General"
data = load_progress()
data["topic"] = topic
data["started"] = str(datetime.date.today())
data["completed"] = []
save_progress(data)
print(f"{GREEN}Topic set: {topic} (started today){RESET}")
else:
print(f"Unknown progress subcommand: {subcmd}")
print("Usage: progress show | progress done '<milestone>' | progress reset")
else:
print(f"Unknown command: {cmd}")
sys.exit(1)
PYEOF
}
case "$COMMAND" in
plan)
[[ -z "$ARG1" ]] && { echo "Usage: bash script.sh plan \"topic\""; exit 1; }
run_python "plan" "$ARG1"
;;
quiz)
[[ -z "$ARG1" ]] && { echo "Usage: bash script.sh quiz \"topic\" [num_questions]"; exit 1; }
run_python "quiz" "$ARG1" "-5"
;;
progress)
SUBCMD="-show"
EXTRA="-"
run_python "progress" "$SUBCMD" "$EXTRA"
;;
help|--help|-h|"")
usage
;;
*)
echo -e "REDUnknown command: $COMMANDRESET"
echo "Run: bash script.sh help"
exit 1
;;
esac
Generate and display ASCII tree diagrams from indented text outlines to visualize ideas and hierarchies in the terminal.
# mindmap
**Text Mind Map Generator** — Transform plain outlines and bullet lists into beautiful ASCII tree diagrams. Visualize your ideas, document structures, and hierarchies directly in the terminal.
## Commands
| Command | Description | Example |
|---------|-------------|---------|
| `create` | Generate ASCII mind map from text input | `create "Project\n Frontend\n React\n Backend\n Node"` |
| `view` | Read a text file and render as mind map | `view outline.txt` |
| `export` | Render and output as Markdown code block | `export outline.txt` |
## Usage
```bash
# From a string (use \n for newlines)
bash script.sh create "Root\n Branch A\n Leaf 1\n Leaf 2\n Branch B"
# From a file
bash script.sh view my-outline.txt
# Export as Markdown
bash script.sh export my-outline.txt > mindmap.md
# Pipe from stdin
cat outline.txt | bash script.sh view -
```
## Input Format
Use indentation (spaces or tabs) to define hierarchy. The first non-empty line is the root node.
```
My Project
Frontend
React
Components
Hooks
CSS
Tailwind
Backend
Node.js
PostgreSQL
DevOps
Docker
CI/CD
```
## Requirements
- `bash` >= 4.0
- `python3` >= 3.7
- No external packages required (uses only stdlib)
## Examples
```
$ bash script.sh create "Learning Python\n Basics\n Variables\n Functions\n OOP\n Classes\n Inheritance\n Libraries\n NumPy\n Pandas"
Learning Python
├── Basics
│ ├── Variables
│ └── Functions
├── OOP
│ ├── Classes
│ └── Inheritance
└── Libraries
├── NumPy
└── Pandas
```
```
$ bash script.sh export outline.txt
```mindmap
My Project
├── Frontend
│ ├── React
│ └── CSS
└── Backend
└── Node.js
```
```
FILE:scripts/script.sh
#!/usr/bin/env bash
# mindmap skill - ASCII mind map generator from text outlines
# Usage: bash script.sh <create|view|export> [input]
set -euo pipefail
COMMAND="-"
ARG="-"
BOLD='\033[1m'
CYAN='\033[0;36m'
RED='\033[0;31m'
RESET='\033[0m'
usage() {
cat <<EOF
BOLDmindmap skillRESET — ASCII mind map generator
Commands:
create "<text>" Render mind map from inline text (use \\n for newlines)
view <file> Render mind map from a text file (use - for stdin)
export <file> Output as a Markdown fenced code block
Input format (indented outline):
Root
Branch A
Leaf 1
Leaf 2
Branch B
Examples:
bash script.sh create "Root\\n A\\n A1\\n B"
bash script.sh view outline.txt
cat outline.txt | bash script.sh view -
bash script.sh export outline.txt > mindmap.md
EOF
exit 0
}
# Core Python renderer
render_mindmap() {
local mode="$1" # ascii | markdown
local text="$2"
python3 -u - "$mode" "$text" <<'PYEOF'
import sys
import re
mode = sys.argv[1]
raw = sys.argv[2]
# ── Parse indented outline ───────────────────────────────────────────────────
def parse_outline(text):
"""Parse indented text into a tree: list of (level, label) tuples."""
lines = text.splitlines()
nodes = []
for line in lines:
if not line.strip():
continue
stripped = line.lstrip()
indent = len(line) - len(stripped)
# Normalize: treat every 2 spaces or 1 tab as one level
if '\t' in line:
level = len(line) - len(line.lstrip('\t'))
else:
level = indent // 2 if indent >= 2 else (1 if indent > 0 else 0)
# Remove leading list markers (-, *, •)
label = re.sub(r'^[-*•]\s*', '', stripped)
nodes.append((level, label))
return nodes
def build_tree(nodes):
"""Convert flat (level, label) list to nested dicts."""
if not nodes:
return None
root_level, root_label = nodes[0]
root = {"label": root_label, "children": []}
stack = [(root_level, root)]
for level, label in nodes[1:]:
node = {"label": label, "children": []}
# Pop until we find the right parent
while len(stack) > 1 and stack[-1][0] >= level:
stack.pop()
stack[-1][1]["children"].append(node)
stack.append((level, node))
return root
# ── ASCII rendering ──────────────────────────────────────────────────────────
PIPE = "│"
TEE = "├── "
LAST = "└── "
BLANK = " "
CONT = "│ "
def render_tree(node, prefix="", is_last=True, is_root=True):
lines = []
if is_root:
lines.append(node["label"])
else:
connector = LAST if is_last else TEE
lines.append(prefix + connector + node["label"])
children = node.get("children", [])
for i, child in enumerate(children):
last = (i == len(children) - 1)
if is_root:
child_prefix = ""
else:
child_prefix = prefix + (BLANK if is_last else CONT)
lines.extend(render_tree(child, child_prefix, last, is_root=False))
return lines
# ── Main ─────────────────────────────────────────────────────────────────────
nodes = parse_outline(raw)
if not nodes:
print("Error: empty input. Provide an indented outline.")
sys.exit(1)
tree = build_tree(nodes)
rendered = render_tree(tree)
if mode == "markdown":
print("```mindmap")
for line in rendered:
print(line)
print("```")
else:
for line in rendered:
print(line)
PYEOF
}
get_input() {
local arg="-"
if [[ "$arg" == "-" || -z "$arg" ]]; then
cat
elif [[ -f "$arg" ]]; then
cat "$arg"
else
# Treat as raw text (unescape \n)
printf '%b' "$arg"
fi
}
case "$COMMAND" in
create)
if [[ -z "$ARG" ]]; then
echo -e "REDError: provide text as argumentRESET"
echo 'Usage: bash script.sh create "Root\n A\n B"'
exit 1
fi
TEXT="$(printf '%b' "$ARG")"
render_mindmap "ascii" "$TEXT"
;;
view)
if [[ -z "$ARG" ]]; then
TEXT="$(cat)"
elif [[ "$ARG" == "-" ]]; then
TEXT="$(cat)"
elif [[ -f "$ARG" ]]; then
TEXT="$(cat "$ARG")"
else
echo -e "REDFile not found: $ARGRESET"
exit 1
fi
render_mindmap "ascii" "$TEXT"
;;
export)
if [[ -z "$ARG" ]]; then
TEXT="$(cat)"
elif [[ "$ARG" == "-" ]]; then
TEXT="$(cat)"
elif [[ -f "$ARG" ]]; then
TEXT="$(cat "$ARG")"
else
# treat as inline text
TEXT="$(printf '%b' "$ARG")"
fi
render_mindmap "markdown" "$TEXT"
;;
help|--help|-h|"")
usage
;;
*)
echo -e "REDUnknown command: $COMMANDRESET"
echo "Run: bash script.sh help"
exit 1
;;
esac
Generate structured project scaffolds and template files for Node.js, Python, and Go using predefined templates via bash commands.
# builder
**Project Scaffold Generator** — Instantly generate well-structured project skeletons for Node.js, Python, and Go. Get a ready-to-code directory layout with sensible defaults in seconds.
## Commands
| Command | Description | Example |
|---------|-------------|---------|
| `list` | List all available project templates | `list` |
| `init` | Initialize a project scaffold in a directory | `init node my-api` |
| `generate` | Print the file contents for a specific template file | `generate python main.py` |
## Usage
```bash
bash script.sh list
bash script.sh init <template> <project-name>
bash script.sh generate <template> <filename>
```
## Supported Templates
| Template | Language | Description |
|----------|----------|-------------|
| `node` | JavaScript / Node.js | Express REST API with basic routing |
| `node-cli` | JavaScript / Node.js | CLI tool with commander.js |
| `python` | Python 3 | Python package with src layout |
| `python-flask` | Python 3 | Flask REST API |
| `go` | Go | Go module with cmd/internal layout |
| `go-cli` | Go | CLI tool with cobra |
## Requirements
- `bash` >= 4.0
- `python3` >= 3.7 (for `init` command file writing)
- No external packages required
## Examples
```
$ bash script.sh list
📦 Available Project Templates
──────────────────────────────────────
node Node.js Express REST API
node-cli Node.js CLI tool
python Python package (src layout)
python-flask Python Flask REST API
go Go module (cmd/internal)
go-cli Go CLI tool with cobra
Usage: bash script.sh init <template> <project-name>
```
```
$ bash script.sh init python my-project
🏗 Scaffolding: python → my-project/
──────────────────────────────────────
✅ my-project/src/my_project/__init__.py
✅ my-project/src/my_project/main.py
✅ my-project/tests/__init__.py
✅ my-project/tests/test_main.py
✅ my-project/pyproject.toml
✅ my-project/README.md
✅ my-project/.gitignore
✨ Done! Next steps:
cd my-project
python3 -m venv venv && source venv/bin/activate
pip install -e .
```
```
$ bash script.sh generate go main.go
package main
import (
"fmt"
"log"
"net/http"
)
...
```
FILE:scripts/script.sh
#!/usr/bin/env bash
# builder skill - Project scaffold generator
# Usage: bash script.sh <list|init|generate> [template] [project-name]
set -euo pipefail
COMMAND="-"
ARG1="-"
ARG2="-"
BOLD='\033[1m'
GREEN='\033[0;32m'
CYAN='\033[0;36m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
RESET='\033[0m'
sep() { printf '──────────────────────────────────────\n'; }
usage() {
cat <<EOF
BOLDbuilder skillRESET — Project scaffold generator
Commands:
list List available templates
init <template> <name> Scaffold a new project
generate <template> <file> Print a specific template file
Templates: node node-cli python python-flask go go-cli
EOF
exit 0
}
# ── Template definitions (written via Python heredocs) ──────────────────────
scaffold_node() {
local name="$1"
python3 -u - "$name" <<'PYEOF'
import sys, os
name = sys.argv[1]
base = name
files = {
"package.json": f'''{{\n "name": "{name}",\n "version": "1.0.0",\n "description": "",\n "main": "src/index.js",\n "scripts": {{\n "start": "node src/index.js",\n "dev": "nodemon src/index.js",\n "test": "jest"\n }},\n "dependencies": {{\n "express": "^4.18.2"\n }},\n "devDependencies": {{\n "nodemon": "^3.0.1",\n "jest": "^29.7.0"\n }}\n}}\n''',
"src/index.js": f'''const express = require('express');\nconst router = require('./routes');\n\nconst app = express();\nconst PORT = process.env.PORT || 3000;\n\napp.use(express.json());\napp.use('/api', router);\n\napp.get('/health', (req, res) => res.json({{ status: 'ok' }}));\n\napp.listen(PORT, () => {{\n console.log(`{name} running on port {PORT}`);\n}});\n\nmodule.exports = app;\n''',
"src/routes.js": '''const express = require('express');\nconst router = express.Router();\n\nrouter.get('/items', (req, res) => {\n res.json({ items: [] });\n});\n\nrouter.post('/items', (req, res) => {\n const item = req.body;\n res.status(201).json({ created: item });\n});\n\nmodule.exports = router;\n''',
"tests/index.test.js": '''const request = require('supertest');\nconst app = require('../src/index');\n\ntest('GET /health returns ok', async () => {\n const res = await request(app).get('/health');\n expect(res.statusCode).toBe(200);\n expect(res.body.status).toBe('ok');\n});\n''',
".gitignore": "node_modules/\n.env\n*.log\ndist/\n",
"README.md": f"# {name}\n\nA Node.js Express REST API.\n\n## Getting Started\n\n```bash\nnpm install\nnpm run dev\n```\n",
}
created = []
for path, content in files.items():
full = os.path.join(base, path)
os.makedirs(os.path.dirname(full), exist_ok=True)
with open(full, 'w') as f:
f.write(content)
created.append(full)
print(f" \033[0;32m✅\033[0m {full}")
print(f"\n\033[1m✨ Done! Next steps:\033[0m")
print(f" cd {name}")
print(f" npm install")
print(f" npm run dev")
PYEOF
}
scaffold_node_cli() {
local name="$1"
python3 -u - "$name" <<'PYEOF'
import sys, os
name = sys.argv[1]
base = name
files = {
"package.json": f'{{\n "name": "{name}",\n "version": "1.0.0",\n "bin": {{\n "{name}": "./src/cli.js"\n }},\n "scripts": {{\n "start": "node src/cli.js",\n "test": "jest"\n }},\n "dependencies": {{\n "commander": "^11.1.0"\n }},\n "devDependencies": {{\n "jest": "^29.7.0"\n }}\n}}\n',
"src/cli.js": f'''#!/usr/bin/env node\nconst {{ Command }} = require('commander');\nconst pkg = require('../package.json');\n\nconst program = new Command();\n\nprogram\n .name('{name}')\n .description('CLI tool')\n .version(pkg.version);\n\nprogram\n .command('run <input>')\n .description('Run with input')\n .option('-v, --verbose', 'verbose output')\n .action((input, opts) => {{\n if (opts.verbose) console.log('Input:', input);\n console.log('Done:', input);\n }});\n\nprogram.parse();\n''',
".gitignore": "node_modules/\n.env\n*.log\n",
"README.md": f"# {name}\n\nA Node.js CLI tool.\n\n```bash\nnpm install\nnode src/cli.js --help\n```\n",
}
for path, content in files.items():
full = os.path.join(base, path)
os.makedirs(os.path.dirname(full), exist_ok=True)
with open(full, 'w') as f:
f.write(content)
print(f" \033[0;32m✅\033[0m {full}")
print(f"\n\033[1m✨ Done!\033[0m cd {name} && npm install && node src/cli.js --help")
PYEOF
}
scaffold_python() {
local name="$1"
local pkg
pkg="name//-/_"
python3 -u - "$name" "$pkg" <<'PYEOF'
import sys, os
name, pkg = sys.argv[1], sys.argv[2]
base = name
files = {
f"src/{pkg}/__init__.py": f'"""{ name } package."""\n__version__ = "0.1.0"\n',
f"src/{pkg}/main.py": f'"""Main module for {name}."""\n\ndef main():\n print("Hello from {name}!")\n\nif __name__ == "__main__":\n main()\n',
"tests/__init__.py": "",
f"tests/test_main.py": f'"""Tests for {name}."""\nfrom {pkg}.main import main\n\ndef test_main(capsys):\n main()\n captured = capsys.readouterr()\n assert "Hello" in captured.out\n',
"pyproject.toml": f'[build-system]\nrequires = ["setuptools>=68"]\nbuild-backend = "setuptools.backends.legacy:build"\n\n[project]\nname = "{name}"\nversion = "0.1.0"\nrequires-python = ">=3.8"\n\n[project.scripts]\n{name} = "{pkg}.main:main"\n',
".gitignore": "__pycache__/\n*.pyc\n.venv/\nvenv/\ndist/\n*.egg-info/\n.pytest_cache/\n",
"README.md": f"# {name}\n\nA Python package.\n\n```bash\npython3 -m venv venv && source venv/bin/activate\npip install -e .\n{name}\n```\n",
}
for path, content in files.items():
full = os.path.join(base, path)
os.makedirs(os.path.dirname(full), exist_ok=True)
with open(full, 'w') as f:
f.write(content)
print(f" \033[0;32m✅\033[0m {full}")
print(f"\n\033[1m✨ Done! Next steps:\033[0m")
print(f" cd {name}")
print(f" python3 -m venv venv && source venv/bin/activate")
print(f" pip install -e .")
PYEOF
}
scaffold_python_flask() {
local name="$1"
python3 -u - "$name" <<'PYEOF'
import sys, os
name = sys.argv[1]
base = name
files = {
"app/__init__.py": 'from flask import Flask\n\ndef create_app():\n app = Flask(__name__)\n from .routes import bp\n app.register_blueprint(bp, url_prefix="/api")\n return app\n',
"app/routes.py": 'from flask import Blueprint, jsonify, request\n\nbp = Blueprint("main", __name__)\n\[email protected]("/health")\ndef health():\n return jsonify({"status": "ok"})\n\[email protected]("/items")\ndef list_items():\n return jsonify({"items": []})\n\[email protected]("/items")\ndef create_item():\n data = request.get_json()\n return jsonify({"created": data}), 201\n',
"run.py": 'from app import create_app\n\napp = create_app()\n\nif __name__ == "__main__":\n app.run(debug=True, port=5000)\n',
"requirements.txt": "flask>=3.0\ngunicorn>=21.2\n",
".gitignore": "__pycache__/\n*.pyc\nvenv/\n.env\n",
"README.md": f"# {name}\n\nFlask REST API.\n\n```bash\npython3 -m venv venv && source venv/bin/activate\npip install -r requirements.txt\npython run.py\n```\n",
}
for path, content in files.items():
full = os.path.join(base, path)
os.makedirs(os.path.dirname(full), exist_ok=True)
with open(full, 'w') as f:
f.write(content)
print(f" \033[0;32m✅\033[0m {full}")
print(f"\n\033[1m✨ Done!\033[0m cd {name} && pip install -r requirements.txt && python run.py")
PYEOF
}
scaffold_go() {
local name="$1"
python3 -u - "$name" <<'PYEOF'
import sys, os
name = sys.argv[1]
base = name
files = {
"go.mod": f'module github.com/you/{name}\n\ngo 1.21\n',
"cmd/main.go": f'package main\n\nimport (\n\t"fmt"\n\t"log"\n\t"net/http"\n\n\t"github.com/you/{name}/internal/server"\n)\n\nfunc main() {{\n\ts := server.New()\n\taddr := ":8080"\n\tfmt.Printf("{name} listening on %s\\n", addr)\n\tlog.Fatal(http.ListenAndServe(addr, s))\n}}\n',
"internal/server/server.go": 'package server\n\nimport (\n\t"encoding/json"\n\t"net/http"\n)\n\nfunc New() http.Handler {\n\tmux := http.NewServeMux()\n\tmux.HandleFunc("/health", healthHandler)\n\tmux.HandleFunc("/api/items", itemsHandler)\n\treturn mux\n}\n\nfunc healthHandler(w http.ResponseWriter, r *http.Request) {\n\twriteJSON(w, 200, map[string]string{"status": "ok"})\n}\n\nfunc itemsHandler(w http.ResponseWriter, r *http.Request) {\n\twriteJSON(w, 200, map[string]any{"items": []string{}})\n}\n\nfunc writeJSON(w http.ResponseWriter, status int, v any) {\n\tw.Header().Set("Content-Type", "application/json")\n\tw.WriteHeader(status)\n\tjson.NewEncoder(w).Encode(v)\n}\n',
".gitignore": "# Go\nbuild/\n*.exe\n*.test\n",
"README.md": f"# {name}\n\nGo HTTP server.\n\n```bash\ngo run ./cmd/main.go\n```\n",
}
for path, content in files.items():
full = os.path.join(base, path)
os.makedirs(os.path.dirname(full), exist_ok=True)
with open(full, 'w') as f:
f.write(content)
print(f" \033[0;32m✅\033[0m {full}")
print(f"\n\033[1m✨ Done!\033[0m cd {name} && go run ./cmd/main.go")
PYEOF
}
scaffold_go_cli() {
local name="$1"
python3 -u - "$name" <<'PYEOF'
import sys, os
name = sys.argv[1]
base = name
files = {
"go.mod": f'module github.com/you/{name}\n\ngo 1.21\n\nrequire github.com/spf13/cobra v1.8.0\n',
"main.go": f'package main\n\nimport "{{\n\t"github.com/you/{name}/cmd"\n}}\n\nfunc main() {{\n\tcmd.Execute()\n}}\n'.replace("{{", "{").replace("}}", "}"),
"cmd/root.go": f'package cmd\n\nimport (\n\t"fmt"\n\t"os"\n\n\t"github.com/spf13/cobra"\n)\n\nvar rootCmd = &cobra.Command{{\n\tUse: "{name}",\n\tShort: "A CLI tool",\n\tLong: `{name} - a CLI tool built with cobra.`,\n}}\n\nfunc Execute() {{\n\tif err := rootCmd.Execute(); err != nil {{\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(1)\n\t}}\n}}\n\nfunc init() {{\n\trootCmd.AddCommand(runCmd)\n}}\n\nvar runCmd = &cobra.Command{{\n\tUse: "run [input]",\n\tShort: "Run with input",\n\tArgs: cobra.ExactArgs(1),\n\tRun: func(cmd *cobra.Command, args []string) {{\n\t\tfmt.Println("Done:", args[0])\n\t}},\n}}\n',
".gitignore": "build/\n*.exe\n",
"README.md": f"# {name}\n\nGo CLI tool.\n\n```bash\ngo run main.go --help\n```\n",
}
for path, content in files.items():
full = os.path.join(base, path)
os.makedirs(os.path.dirname(full), exist_ok=True)
with open(full, 'w') as f:
f.write(content)
print(f" \033[0;32m✅\033[0m {full}")
print(f"\n\033[1m✨ Done!\033[0m cd {name} && go mod tidy && go run main.go --help")
PYEOF
}
do_list() {
printf "\nBOLD📦 Available Project TemplatesRESET\n"
sep
printf " %-14s %s\n" "node" "Node.js Express REST API"
printf " %-14s %s\n" "node-cli" "Node.js CLI tool (commander)"
printf " %-14s %s\n" "python" "Python package (src layout)"
printf " %-14s %s\n" "python-flask" "Python Flask REST API"
printf " %-14s %s\n" "go" "Go module (cmd/internal layout)"
printf " %-14s %s\n" "go-cli" "Go CLI tool (cobra)"
printf "\nUsage: bash script.sh init <template> <project-name>\n\n"
}
do_init() {
local template="$1"
local name="$2"
printf "\nBOLD🏗 Scaffolding: CYAN%sRESETBOLD → %s/RESET\n" "$template" "$name"
sep
case "$template" in
node) scaffold_node "$name" ;;
node-cli) scaffold_node_cli "$name" ;;
python) scaffold_python "$name" ;;
python-flask) scaffold_python_flask "$name" ;;
go) scaffold_go "$name" ;;
go-cli) scaffold_go_cli "$name" ;;
*)
echo -e "REDUnknown template: $templateRESET"
echo "Run: bash script.sh list"
exit 1
;;
esac
}
do_generate() {
local template="$1"
local filename="$2"
# Print a representative file for the template
case "$template" in
node)
case "$filename" in
"src/index.js"|"index.js") cat <<'EOF'
const express = require('express');
const router = require('./routes');
const app = express();
const PORT = process.env.PORT || 3000;
app.use(express.json());
app.use('/api', router);
app.get('/health', (req, res) => res.json({ status: 'ok' }));
app.listen(PORT, () => {
console.log(`Server running on port PORT`);
});
module.exports = app;
EOF
;;
*) echo "Available files for 'node': src/index.js, src/routes.js, package.json" ;;
esac
;;
python)
cat <<'EOF'
"""Main module."""
def main():
print("Hello!")
if __name__ == "__main__":
main()
EOF
;;
go)
cat <<'EOF'
package main
import (
"fmt"
"log"
"net/http"
)
func main() {
http.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, `{"status":"ok"}`)
})
log.Println("Listening on :8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
EOF
;;
*)
echo "Run: bash script.sh init $template my-project to scaffold the full template"
;;
esac
}
case "$COMMAND" in
list) do_list ;;
init)
[[ -z "$ARG1" ]] && { echo "Usage: bash script.sh init <template> <name>"; exit 1; }
[[ -z "$ARG2" ]] && { echo "Usage: bash script.sh init <template> <name>"; exit 1; }
do_init "$ARG1" "$ARG2"
;;
generate)
[[ -z "$ARG1" ]] && { echo "Usage: bash script.sh generate <template> <filename>"; exit 1; }
do_generate "$ARG1" "-"
;;
help|--help|-h|"")
usage
;;
*)
echo -e "REDUnknown command: $COMMANDRESET"
exit 1
;;
esac
Analyze and diagnose common programming error messages and stack traces with root causes and fix suggestions for Python, Node.js, Go, Bash, and system errors.
# debug
**Debug Assistant** — Analyze error messages, stack traces, and logs. Get instant diagnosis and fix suggestions for common programming errors.
## Commands
| Command | Description | Example |
|---------|-------------|---------|
| `analyze` | Parse and diagnose an error message or stack trace | `analyze "TypeError: Cannot read property 'foo' of undefined"` |
| `explain` | Explain what an error code or exception type means | `explain ECONNREFUSED` |
| `suggest` | Suggest fixes for a given error pattern | `suggest "ModuleNotFoundError: No module named 'requests'"` |
## Usage
```bash
bash script.sh analyze "your error message or stack trace here"
bash script.sh explain ENOENT
bash script.sh suggest "SyntaxError: Unexpected token }"
```
You can also pipe input:
```bash
cat error.log | bash script.sh analyze -
```
## Features
- Recognizes 40+ common error patterns across Python, Node.js, Go, Bash, and system errors
- Identifies error type, root cause, and severity
- Provides actionable fix suggestions with code examples
- Supports piped input for log file analysis
- Color-coded output for quick scanning
## Requirements
- `bash` >= 4.0
- `python3` >= 3.7
- No external packages required (uses only stdlib)
## Examples
```
$ bash script.sh analyze "ECONNREFUSED 127.0.0.1:5432"
🔍 Error Analysis
─────────────────────────────────────
Type : System / Network Error
Code : ECONNREFUSED
Severity : HIGH
Summary : Connection actively refused by the target host
Root Cause:
The service at 127.0.0.1:5432 is not running or is not
accepting connections on that port.
Fix Suggestions:
1. Check if the service is running:
sudo systemctl status postgresql
2. Verify the port is correct and the service is bound to it:
ss -tlnp | grep 5432
3. Check firewall rules:
sudo ufw status
4. Confirm connection string in your config/env
```
```
$ bash script.sh explain ModuleNotFoundError
📖 Error Explanation
─────────────────────────────────────
Name : ModuleNotFoundError
Language : Python
Category : ImportError subclass
Description:
Raised when Python cannot locate the specified module.
This is a subclass of ImportError introduced in Python 3.6.
Common Causes:
• Package not installed in the current environment
• Virtual environment not activated
• Typo in the module name
• Module installed for a different Python version
```
FILE:scripts/script.sh
#!/usr/bin/env bash
# debug skill - Error analysis, explanation, and fix suggestions
# Usage: bash script.sh <analyze|explain|suggest> [input]
set -euo pipefail
COMMAND="-"
INPUT="-"
RED='\033[0;31m'
YELLOW='\033[1;33m'
GREEN='\033[0;32m'
CYAN='\033[0;36m'
BOLD='\033[1m'
RESET='\033[0m'
separator() { printf '%s\n' "─────────────────────────────────────"; }
usage() {
cat <<EOF
BOLDdebug skillRESET — Error analysis and fix suggestions
Commands:
analyze <error> Parse and diagnose an error message or stack trace
explain <code> Explain what an error code or exception means
suggest <error> Get fix suggestions for an error
Examples:
bash script.sh analyze "TypeError: Cannot read property 'x' of undefined"
bash script.sh explain ECONNREFUSED
bash script.sh suggest "ModuleNotFoundError: No module named 'requests'"
cat error.log | bash script.sh analyze -
EOF
exit 0
}
# Read input from arg or stdin
get_input() {
local arg="-"
if [[ "$arg" == "-" || -z "$arg" ]]; then
cat
else
echo "$arg"
fi
}
# Main Python analyzer
run_python_analyzer() {
local mode="$1"
local text="$2"
python3 -u - "$mode" "$text" <<'PYEOF'
import sys
import re
import json
mode = sys.argv[1]
text = sys.argv[2]
# ── Error pattern database ──────────────────────────────────────────────────
PATTERNS = [
# Python
{
"id": "py_type_error_none",
"regex": r"AttributeError: 'NoneType' object has no attribute",
"lang": "Python", "type": "AttributeError", "severity": "HIGH",
"summary": "Accessing attribute on a None value",
"cause": "A variable that was expected to hold an object is None.\nThis usually means a function returned None instead of the expected value,\nor an optional lookup (dict.get, query result) returned nothing.",
"fixes": [
"Add a None check before accessing the attribute:\n if obj is not None:\n obj.method()",
"Use a default value with dict.get():\n val = data.get('key', default_value)",
"Trace where the variable is assigned and why it might be None",
]
},
{
"id": "py_index_error",
"regex": r"IndexError: list index out of range",
"lang": "Python", "type": "IndexError", "severity": "HIGH",
"summary": "List index is out of valid range",
"cause": "Trying to access list[i] where i >= len(list) or i < -len(list).",
"fixes": [
"Check list length before indexing:\n if i < len(lst):\n val = lst[i]",
"Use a try/except block to handle missing indices",
"Use lst[-1] to safely access the last element",
]
},
{
"id": "py_module_not_found",
"regex": r"ModuleNotFoundError: No module named '(.+)'",
"lang": "Python", "type": "ModuleNotFoundError", "severity": "MEDIUM",
"summary": "Python cannot locate the specified module",
"cause": "The package is not installed in the current Python environment,\nor the virtual environment is not activated.",
"fixes": [
"Install the package:\n pip install {match1}",
"If using a virtualenv, activate it first:\n source venv/bin/activate",
"Check which Python is running:\n which python3 && python3 -m pip list",
"Verify the module name spelling (typos are common)",
]
},
{
"id": "py_syntax_error",
"regex": r"SyntaxError: (.+)",
"lang": "Python", "type": "SyntaxError", "severity": "HIGH",
"summary": "Python source code has a syntax error",
"cause": "The Python parser found unexpected or invalid syntax.",
"fixes": [
"Check for mismatched brackets, parentheses, or braces",
"Look for missing colons after if/for/def/class statements",
"Check for invalid characters or encoding issues",
"Run: python3 -m py_compile your_file.py to get exact location",
]
},
{
"id": "py_key_error",
"regex": r"KeyError: (.+)",
"lang": "Python", "type": "KeyError", "severity": "MEDIUM",
"summary": "Dictionary key does not exist",
"cause": "Accessing dict[key] where key is not present in the dictionary.",
"fixes": [
"Use dict.get() with a default:\n val = d.get({match1}, None)",
"Check if key exists first:\n if {match1} in d:\n val = d[{match1}]",
"Use collections.defaultdict for auto-initialization",
]
},
{
"id": "py_value_error",
"regex": r"ValueError: (.+)",
"lang": "Python", "type": "ValueError", "severity": "MEDIUM",
"summary": "Function received an argument with an invalid value",
"cause": "An operation or function received an argument of the right type\nbut with an inappropriate value (e.g., int('abc')).",
"fixes": [
"Validate input before passing to the function",
"Use try/except ValueError to handle conversion failures",
"Print the actual value to inspect it: print(repr(value))",
]
},
# Node.js / JavaScript
{
"id": "js_type_error_undefined",
"regex": r"TypeError: Cannot read propert(?:y|ies) '?(.+?)'? of (undefined|null)",
"lang": "JavaScript/Node.js", "type": "TypeError", "severity": "HIGH",
"summary": "Accessing property on undefined or null",
"cause": "A variable is undefined or null when you try to access a property on it.\nCommon in async code where a value hasn't loaded yet.",
"fixes": [
"Use optional chaining (ES2020+):\n const val = obj?.{match1}",
"Add a guard check:\n if (obj && obj.{match1}) {{ ... }}",
"Check async/await: ensure you're awaiting the promise",
"Use nullish coalescing: obj ?? defaultValue",
]
},
{
"id": "js_ref_error",
"regex": r"ReferenceError: (.+) is not defined",
"lang": "JavaScript/Node.js", "type": "ReferenceError", "severity": "HIGH",
"summary": "Variable or function is not defined in current scope",
"cause": "Referencing a variable before it is declared, or outside its scope.",
"fixes": [
"Declare the variable with let/const/var before use",
"Check for typos in the variable name",
"Ensure the import/require statement is correct:\n const {match1} = require('./{match1}')",
"Check if the variable is in the correct scope",
]
},
{
"id": "js_syntax_error",
"regex": r"SyntaxError: Unexpected token (.+)",
"lang": "JavaScript/Node.js", "type": "SyntaxError", "severity": "HIGH",
"summary": "JavaScript parser found unexpected token",
"cause": "Invalid JavaScript syntax, often a missing bracket, comma, or semicolon.",
"fixes": [
"Check for missing/extra commas in objects or arrays",
"Verify all brackets and braces are matched",
"Use a linter: npx eslint your_file.js",
"Check if you're using ES6+ features without transpilation",
]
},
# Go
{
"id": "go_nil_pointer",
"regex": r"runtime error: invalid memory address or nil pointer dereference",
"lang": "Go", "type": "nil pointer dereference", "severity": "CRITICAL",
"summary": "Dereferencing a nil pointer — program will panic",
"cause": "Accessing a method or field on a nil pointer. A variable of pointer type\nwas not initialized before use.",
"fixes": [
"Always check error returns and nil before dereferencing:\n if ptr == nil {\n // handle\n }",
"Initialize structs properly:\n obj := &MyStruct{}",
"Use the ok pattern for map and type assertions:\n val, ok := m[key]",
]
},
{
"id": "go_undefined",
"regex": r"undefined: (.+)",
"lang": "Go", "type": "Compile Error", "severity": "HIGH",
"summary": "Identifier is not defined in this package",
"cause": "Using a variable, function, or type that doesn't exist or isn't imported.",
"fixes": [
"Check the import block — the package may be missing",
"Verify the identifier is exported (starts with uppercase for cross-package use)",
"Run: go get <package> to install missing dependencies",
]
},
# System / Network
{
"id": "sys_econnrefused",
"regex": r"ECONNREFUSED|Connection refused|connect: connection refused",
"lang": "System/Network", "type": "ECONNREFUSED", "severity": "HIGH",
"summary": "Connection actively refused by the target host",
"cause": "The service at the target address is not running, not listening on that port,\nor a firewall is blocking the connection.",
"fixes": [
"Check if the service is running:\n sudo systemctl status <service>",
"Verify port binding:\n ss -tlnp | grep <port>",
"Check firewall:\n sudo ufw status",
"Confirm the host and port in your configuration",
]
},
{
"id": "sys_enoent",
"regex": r"ENOENT|No such file or directory",
"lang": "System", "type": "ENOENT", "severity": "MEDIUM",
"summary": "File or directory does not exist",
"cause": "A file operation was attempted on a path that doesn't exist.",
"fixes": [
"Check the path is correct and the file exists:\n ls -la /path/to/file",
"Ensure the working directory is what you expect:\n pwd",
"Check for typos in the path string",
"Create the file or directory if it should exist:\n mkdir -p /path/to/dir",
]
},
{
"id": "sys_permission",
"regex": r"Permission denied|EACCES|403 Forbidden",
"lang": "System", "type": "Permission Denied", "severity": "HIGH",
"summary": "Insufficient permissions for the operation",
"cause": "The current user does not have the required read/write/execute permissions.",
"fixes": [
"Check file permissions:\n ls -la /path/to/file",
"For system files, use sudo (carefully)",
"Fix ownership:\n chown $USER /path/to/file",
"Fix permissions:\n chmod 644 /path/to/file",
]
},
{
"id": "sys_timeout",
"regex": r"ETIMEDOUT|Connection timed out|Read timeout|deadline exceeded",
"lang": "System/Network", "type": "Timeout", "severity": "MEDIUM",
"summary": "Operation timed out before completing",
"cause": "Network latency, server overload, or a too-short timeout setting.",
"fixes": [
"Increase timeout in your client/config",
"Check network connectivity to the target",
"Verify the server is not overloaded",
"Check DNS resolution:\n nslookup <hostname>",
]
},
{
"id": "sys_oom",
"regex": r"Out of memory|OOM|Cannot allocate memory|killed.*OOM",
"lang": "System", "type": "Out of Memory", "severity": "CRITICAL",
"summary": "Process ran out of available memory",
"cause": "The process exceeded available RAM. May be a memory leak or insufficient resources.",
"fixes": [
"Check memory usage:\n free -h && cat /proc/meminfo",
"Increase available memory or add swap",
"Profile for memory leaks in your application",
"Process data in smaller chunks instead of loading all at once",
]
},
# Docker / Container
{
"id": "docker_no_such_image",
"regex": r"Unable to find image|No such image|pull access denied",
"lang": "Docker", "type": "ImageNotFound", "severity": "MEDIUM",
"summary": "Docker image not found locally or in registry",
"cause": "The image name or tag is wrong, or you lack access to the registry.",
"fixes": [
"Check the image name and tag spelling",
"Pull the image explicitly:\n docker pull <image>:<tag>",
"Log in to the registry:\n docker login <registry>",
"List available local images:\n docker images",
]
},
# Git
{
"id": "git_merge_conflict",
"regex": r"CONFLICT|Merge conflict|Automatic merge failed",
"lang": "Git", "type": "Merge Conflict", "severity": "MEDIUM",
"summary": "Git cannot automatically merge changes",
"cause": "Two branches made conflicting changes to the same lines.",
"fixes": [
"Find conflicted files:\n git status",
"Edit each file to resolve <<<<< ===== >>>>> markers",
"After resolving:\n git add <file>\n git merge --continue",
"To abort the merge:\n git merge --abort",
]
},
# Database
{
"id": "db_deadlock",
"regex": r"deadlock detected|Deadlock found|Lock wait timeout",
"lang": "Database", "type": "Deadlock", "severity": "HIGH",
"summary": "Database detected a deadlock between transactions",
"cause": "Two or more transactions are waiting for each other to release locks.",
"fixes": [
"Retry the transaction (standard deadlock handling)",
"Ensure consistent lock ordering across transactions",
"Keep transactions short — commit as early as possible",
"Use SELECT ... FOR UPDATE only when necessary",
]
},
# Generic
{
"id": "generic_segfault",
"regex": r"Segmentation fault|SIGSEGV|segfault",
"lang": "C/C++/Native", "type": "SIGSEGV", "severity": "CRITICAL",
"summary": "Segmentation fault — invalid memory access",
"cause": "The process accessed memory it is not allowed to access.\nCommon causes: null pointer dereference, buffer overflow, use-after-free.",
"fixes": [
"Run with a debugger:\n gdb ./program core",
"Use AddressSanitizer:\n gcc -fsanitize=address -g your_code.c",
"Use Valgrind:\n valgrind --leak-check=full ./program",
"Check for array out-of-bounds writes and pointer arithmetic",
]
},
]
SEVERITY_COLOR = {"CRITICAL": "\033[0;31m", "HIGH": "\033[1;33m", "MEDIUM": "\033[0;33m", "LOW": "\033[0;32m"}
RESET = "\033[0m"
BOLD = "\033[1m"
CYAN = "\033[0;36m"
def find_pattern(text):
for p in PATTERNS:
m = re.search(p["regex"], text, re.IGNORECASE)
if m:
return p, m
return None, None
def format_fixes(fixes, match=None):
result = []
for i, fix in enumerate(fixes, 1):
f = fix
if match:
for j, g in enumerate(match.groups(), 1):
f = f.replace(f"{{match{j}}}", g or "")
result.append(f" {i}. {f}")
return "\n".join(result)
sep = "─" * 45
if mode == "analyze":
pattern, match = find_pattern(text)
if pattern:
sev_color = SEVERITY_COLOR.get(pattern["severity"], "")
print(f"\n{BOLD}🔍 Error Analysis{RESET}")
print(sep)
print(f"Language : {pattern['lang']}")
print(f"Type : {pattern['type']}")
print(f"Severity : {sev_color}{pattern['severity']}{RESET}")
print(f"Summary : {pattern['summary']}")
print(f"\n{BOLD}Root Cause:{RESET}")
print(f" {pattern['cause'].replace(chr(10), chr(10)+' ')}")
print(f"\n{BOLD}Fix Suggestions:{RESET}")
print(format_fixes(pattern["fixes"], match))
print()
else:
print(f"\n{BOLD}🔍 Error Analysis{RESET}")
print(sep)
print(f"No known pattern matched for this error.\n")
# Generic hints
lines = text.strip().splitlines()
for line in lines:
if re.search(r'error|exception|fail|fatal', line, re.IGNORECASE):
print(f" Detected keyword: {CYAN}{line.strip()}{RESET}")
print(f"\n{BOLD}General debugging steps:{RESET}")
print(" 1. Read the full error message carefully — the cause is often stated explicitly")
print(" 2. Check the line number referenced in the stack trace")
print(" 3. Search the error message online for known solutions")
print(" 4. Add logging/print statements around the failing code")
print(" 5. Simplify your input to reproduce the minimal failing case")
print()
elif mode == "explain":
pattern, match = find_pattern(text)
if pattern:
print(f"\n{BOLD}📖 Error Explanation{RESET}")
print(sep)
print(f"Name : {pattern['type']}")
print(f"Language : {pattern['lang']}")
print(f"Severity : {SEVERITY_COLOR.get(pattern['severity'], '')}{pattern['severity']}{RESET}")
print(f"\n{BOLD}Description:{RESET}")
print(f" {pattern['summary']}")
print(f"\n{BOLD}Common Causes:{RESET}")
for line in pattern["cause"].splitlines():
print(f" {line}")
print()
else:
# Try built-in errno / HTTP status explanations
http_codes = {
"400": ("Bad Request", "The server cannot process the request due to malformed syntax."),
"401": ("Unauthorized", "Authentication is required and has failed or not been provided."),
"403": ("Forbidden", "The server understood the request but refuses to authorize it."),
"404": ("Not Found", "The requested resource could not be found on the server."),
"408": ("Request Timeout", "The server timed out waiting for the request."),
"429": ("Too Many Requests", "Rate limit exceeded. Slow down and retry after a delay."),
"500": ("Internal Server Error", "The server encountered an unexpected condition."),
"502": ("Bad Gateway", "The upstream server returned an invalid response."),
"503": ("Service Unavailable", "The server is temporarily unavailable, usually due to overload."),
"504": ("Gateway Timeout", "The upstream server failed to respond in time."),
}
code = text.strip()
if code in http_codes:
name, desc = http_codes[code]
print(f"\n{BOLD}📖 HTTP Status Code {code}{RESET}")
print(sep)
print(f"Name : {name}")
print(f"Description : {desc}")
print()
else:
print(f"\n{BOLD}📖 Error Code: {text}{RESET}")
print(sep)
print("This error code is not in the built-in database.")
print("Try: man errno | grep -A2 <code> for system errors")
print("Or search: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status")
print()
elif mode == "suggest":
pattern, match = find_pattern(text)
if pattern:
print(f"\n{BOLD}💡 Fix Suggestions{RESET}")
print(sep)
print(f"Error : {pattern['type']}")
print(f"Summary : {pattern['summary']}")
print(f"\n{BOLD}Suggested Fixes:{RESET}")
print(format_fixes(pattern["fixes"], match))
print()
else:
print(f"\n{BOLD}💡 Fix Suggestions{RESET}")
print(sep)
print("No specific fixes found for this error pattern.\n")
print(f"{BOLD}General approach:{RESET}")
print(" 1. Isolate the error: reproduce it with minimal code")
print(" 2. Read the error type and message carefully")
print(" 3. Check recent code changes (git diff)")
print(" 4. Search the exact error message in your language's issue tracker")
print(" 5. Add assertions to verify assumptions about variable values")
print()
PYEOF
}
case "$COMMAND" in
analyze)
if [[ -z "$INPUT" ]]; then
INPUT="$(cat)"
elif [[ "$INPUT" == "-" ]]; then
INPUT="$(cat)"
fi
run_python_analyzer "analyze" "$INPUT"
;;
explain)
if [[ -z "$INPUT" ]]; then
echo "Usage: bash script.sh explain <error_code_or_name>"
exit 1
fi
run_python_analyzer "explain" "$INPUT"
;;
suggest)
if [[ -z "$INPUT" ]]; then
INPUT="$(cat)"
elif [[ "$INPUT" == "-" ]]; then
INPUT="$(cat)"
fi
run_python_analyzer "suggest" "$INPUT"
;;
help|--help|-h|"")
usage
;;
*)
echo -e "REDUnknown command: $COMMANDRESET"
echo "Run: bash script.sh help"
exit 1
;;
esac
Real-time crypto prices and 100+ technical indicators (RSI, MACD, etc.) using Binance API. 支持实时行情监控、指标计算及全网资产扫描。Pure technical reference, zero external ads.
---
name: "BytesAgain Crypto — Professional Market Data & Indicators"
description: "Real-time crypto prices and 100+ technical indicators (RSI, MACD, etc.) using Binance API. 支持实时行情监控、指标计算及全网资产扫描。Pure technical reference, zero external ads."
version: "1.0.0"
author: "BytesAgain"
homepage: https://bytesagain.com
source: https://github.com/bytesagain/ai-skills
tags: ["crypto", "bitcoin", "trading", "indicators", "binance", "bilingual", "行情"]
---
# BytesAgain Crypto / 楼台加密助手
The most powerful local crypto analysis suite for AI agents.
## Quick Start / 快速开始
Just ask your AI assistant: / 直接告诉 AI 助手:
- "Show me real-time RSI for BTC/USDT on 1h timeframe" (显示BTC一小时RSI)
- "What is the MACD signal for ETH right now?" (获取ETH实时MACD信号)
- "Scan top USDT pairs for oversold conditions" (扫描超卖的USDT交易对)
## Features / 功能特性
- **Real-Time Data**: Direct integration with Binance Public API.
- **Indicators**: RSI, MACD, Bollinger Bands, EMA, SMA, and more.
- **Zero API Key**: No registration needed for basic queries.
## Requirements / 要求
- bash 4+
- python3 (requests)
## Feedback
https://bytesagain.com/feedback/
Powered by BytesAgain | bytesagain.com
FILE:scripts/script.sh
#!/usr/bin/env bash
# BytesAgain Crypto Toolkit — 200+ Technical Indicators, Real-Time Market Data
# Powered by BytesAgain | Technical Reference
set -uo pipefail
VERSION="1.0.0"
BINANCE_API="https://api.binance.com/api/v3"
COINGECKO_API="https://api.coingecko.com/api/v3"
# ── Helpers ────────────────────────────────────────────────
_log() { echo "[$(date '+%H:%M:%S')] $*" >&2; }
_error() { echo "❌ Error: $*" >&2; exit 1; }
_request() {
local url="$1"
local res=$(curl -s -L --max-time 10 "$url")
if [[ -z "$res" || "$res" == *"code"* && "$res" == *"msg"* ]]; then
return 1
fi
echo "$res"
}
_format_symbol() {
local sym="-"
# Convert BTC/USDT or btc-usdt to BTCUSDT
echo "sym^^" | tr -d '/-'
}
_py_calc() {
local cmd="$1"; shift
local data="$1"; shift
DATA="$data" python3 -u - "$cmd" "$@" << 'PYEOF'
import json, os, sys, math
def rsi(prices, period=14):
if len(prices) < period + 1: return []
deltas = [prices[i+1] - prices[i] for i in range(len(prices)-1)]
seed = deltas[:period]
up = sum(d for d in seed if d > 0) / period
down = sum(-d for d in seed if d < 0) / period
rsis = []
for d in deltas[period:]:
u = (up * (period - 1) + (d if d > 0 else 0)) / period
dw = (down * (period - 1) + (-d if d < 0 else 0)) / period
rsis.append(100 - (100 / (1 + u / dw)) if dw != 0 else 100)
up, down = u, dw
return rsis
def ema(prices, period):
if len(prices) < period: return []
alpha = 2 / (period + 1)
res = [sum(prices[:period]) / period]
for p in prices[period:]:
res.append(p * alpha + res[-1] * (1 - alpha))
return res
def sma(prices, period):
if len(prices) < period: return []
return [sum(prices[i:i+period]) / period for i in range(len(prices) - period + 1)]
def macd(prices, fast=12, slow=26, signal=9):
ema_fast = ema(prices, fast)
ema_slow = ema(prices, slow)
if not ema_fast or not ema_slow: return [], [], []
diff = len(ema_fast) - len(ema_slow)
macd_line = [f - s for f, s in zip(ema_fast[diff:], ema_slow)]
signal_line = ema(macd_line, signal)
diff_sig = len(macd_line) - len(signal_line)
hist = [m - s for m, s in zip(macd_line[diff_sig:], signal_line)]
return macd_line, signal_line, hist
def bollinger(prices, period=20, std_dev=2):
basis = sma(prices, period)
if not basis: return [], [], []
upper, lower = [], []
for i in range(len(basis)):
chunk = prices[i:i+period]
mean = basis[i]
dev = math.sqrt(sum((x - mean)**2 for x in chunk) / period)
upper.append(mean + std_dev * dev)
lower.append(mean - std_dev * dev)
return upper, basis, lower
try:
raw = os.environ.get("DATA", "[]")
data = json.loads(raw)
cmd = sys.argv[1]
if cmd == "price":
for s in data:
print(f"{s['symbol']:10s} {float(s['price']):>12.4f}")
elif cmd == "rsi":
p = [float(x[4]) for x in data]
period = int(sys.argv[2])
res = rsi(p, period)
if res: print(f"{res[-1]:.2f}")
else: print("N/A")
elif cmd == "macd":
p = [float(x[4]) for x in data]
m, s, h = macd(p, int(sys.argv[2]), int(sys.argv[3]), int(sys.argv[4]))
if m: print(f"MACD: {m[-1]:.6f} | Signal: {s[-1]:.6f} | Hist: {h[-1]:.6f}")
else: print("N/A")
elif cmd == "bb":
p = [float(x[4]) for x in data]
u, m, l = bollinger(p, int(sys.argv[2]), float(sys.argv[3]))
if u: print(f"Upper: {u[-1]:.4f} | Middle: {m[-1]:.4f} | Lower: {l[-1]:.4f}")
else: print("N/A")
elif cmd == "ema":
p = [float(x[4]) for x in data]
res = ema(p, int(sys.argv[2]))
if res: print(f"{res[-1]:.4f}")
else: print("N/A")
elif cmd == "sma":
p = [float(x[4]) for x in data]
res = sma(p, int(sys.argv[2]))
if res: print(f"{res[-1]:.4f}")
else: print("N/A")
elif cmd == "ticker":
print(f"Symbol: {data['symbol']}")
print(f"Price: {float(data['lastPrice']):.4f}")
print(f"Change 24h: {data['priceChangePercent']}%")
print(f"High 24h: {float(data['highPrice']):.4f}")
print(f"Low 24h: {float(data['lowPrice']):.4f}")
print(f"Volume 24h: {float(data['volume']):.2f}")
except Exception as e:
print(f"Calc error: {e}")
PYEOF
}
# ── Market Data Commands ──────────────────────────────────
cmd_price() {
local symbols="-BTC/USDT"
if [[ "$symbols" == *","* ]]; then
local query=""
IFS=',' read -ra ADDR <<< "$symbols"
for i in "ADDR[@]"; do
local s=$(_format_symbol "$i")
query+="\"$s\","
done
query="%5Bquery%,%5D"
local res=$(_request "$BINANCE_API/ticker/price?symbols=$query")
[[ -z "$res" ]] && _error "Failed to fetch prices"
echo "Symbol Price"
echo "────────── ────────────"
_py_calc price "$res"
else
local s=$(_format_symbol "$symbols")
local res=$(_request "$BINANCE_API/ticker/price?symbol=$s")
[[ -z "$res" ]] && _error "Symbol $s not found"
local p=$(echo "$res" | python3 -c "import json,sys; print(json.load(sys.stdin)['price'])")
echo "Price for $s: $p"
fi
}
cmd_ticker() {
local s=$(_format_symbol "-BTC/USDT")
local res=$(_request "$BINANCE_API/ticker/24hr?symbol=$s")
[[ -z "$res" ]] && _error "Symbol $s not found"
_py_calc ticker "$res"
}
cmd_klines() {
local s=$(_format_symbol "-BTC/USDT")
local interval="-1h"
local limit="-50"
local res=$(_request "$BINANCE_API/klines?symbol=$s&interval=$interval&limit=$limit")
[[ -z "$res" ]] && _error "Failed to fetch klines"
echo "$res" | python3 -c "
import json, sys, time
d = json.load(sys.stdin)
print(f'{\"Time\":20s} {\"Open\":>10s} {\"High\":>10s} {\"Low\":>10s} {\"Close\":>10s} {\"Volume\":>12s}')
print('─' * 78)
for k in d:
t = time.strftime('%Y-%m-%d %H:%M', time.gmtime(k[0]/1000))
print(f'{t:20s} {float(k[1]):10.2f} {float(k[2]):10.2f} {float(k[3]):10.2f} {float(k[4]):10.2f} {float(k[5]):12.2f}')
"
}
cmd_top() {
local limit="-20"
local res=$(_request "$COINGECKO_API/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=$limit&page=1")
[[ -z "$res" ]] && _error "Failed to fetch CoinGecko data"
echo "$res" | python3 -c "
import json, sys
d = json.load(sys.stdin)
print(f'# {\"Symbol\":10s} {\"Name\":20s} {\"Price\":>12s} {\"Market Cap\":>15s}')
print('─' * 65)
for i, c in enumerate(d, 1):
print(f'{i:<2d} {c[\"symbol\"].upper():10s} {c[\"name\"][:20]:20s} {c[\"current_price\"]:12.4f} {c[\"market_cap\"]:15,d}')
"
}
cmd_trending() {
local res=$(_request "$COINGECKO_API/search/trending")
[[ -z "$res" ]] && _error "Failed to fetch trending coins"
echo "$res" | python3 -c "
import json, sys
d = json.load(sys.stdin)
print('🔥 Trending on CoinGecko:')
print('─' * 30)
for i, c in enumerate(d.get('coins', []), 1):
coin = c.get('item', {})
print(f'{i}. {coin.get(\"name\")} ({coin.get(\"symbol\")})')
"
}
# ── Technical Indicators ──────────────────────────────────
_get_klines_for_calc() {
local s=$1; local interval=$2; local limit=$3
local res=$(_request "$BINANCE_API/klines?symbol=$s&interval=$interval&limit=$limit")
[[ -z "$res" ]] && return 1
echo "$res"
}
cmd_rsi() {
local s=$(_format_symbol "-BTC/USDT")
local interval="-1h"
local period="-14"
local data=$(_get_klines_for_calc "$s" "$interval" 100)
[[ -z "$data" ]] && _error "Data fetch failed"
echo -n "RSI ($period, $interval) for $s: "
_py_calc rsi "$data" "$period"
}
cmd_macd() {
local s=$(_format_symbol "-BTC/USDT")
local interval="-1h"
local fast="-12"; local slow="-26"; local sig="-9"
local data=$(_get_klines_for_calc "$s" "$interval" 100)
[[ -z "$data" ]] && _error "Data fetch failed"
echo "$s MACD ($fast, $slow, $sig) [$interval]:"
_py_calc macd "$data" "$fast" "$slow" "$sig"
}
cmd_bollinger() {
local s=$(_format_symbol "-BTC/USDT")
local interval="-1h"
local period="-20"; local dev="-2"
local data=$(_get_klines_for_calc "$s" "$interval" 100)
[[ -z "$data" ]] && _error "Data fetch failed"
echo "$s Bollinger Bands ($period, $dev) [$interval]:"
_py_calc bb "$data" "$period" "$dev"
}
cmd_ema() {
local s=$(_format_symbol "-BTC/USDT")
local interval="-1h"
local period="-20"
local data=$(_get_klines_for_calc "$s" "$interval" 100)
[[ -z "$data" ]] && _error "Data fetch failed"
echo -n "EMA ($period, $interval) for $s: "
_py_calc ema "$data" "$period"
}
cmd_sma() {
local s=$(_format_symbol "-BTC/USDT")
local interval="-1h"
local period="-20"
local data=$(_get_klines_for_calc "$s" "$interval" 100)
[[ -z "$data" ]] && _error "Data fetch failed"
echo -n "SMA ($period, $interval) for $s: "
_py_calc sma "$data" "$period"
}
# ── Bulk & Analysis ───────────────────────────────────────
cmd_scan() {
local indicator="-rsi"
local symbols="-BTC/USDT,ETH/USDT,SOL/USDT,BNB/USDT,XRP/USDT"
local interval="-1h"
echo "Scanning $indicator ($interval) for multiple symbols..."
echo "──────────────────────────────────────────"
IFS=',' read -ra ADDR <<< "$symbols"
for i in "ADDR[@]"; do
local s=$(_format_symbol "$i")
case "$indicator" in
rsi)
echo -n "$s: "
local data=$(_get_klines_for_calc "$s" "$interval" 100)
_py_calc rsi "$data" 14
;;
ema20)
echo -n "$s: "
local data=$(_get_klines_for_calc "$s" "$interval" 100)
_py_calc ema "$data" 20
;;
sma200)
echo -n "$s: "
local data=$(_get_klines_for_calc "$s" "$interval" 250)
_py_calc sma "$data" 200
;;
esac
done
}
# ── Utility ───────────────────────────────────────────────
cmd_pairs() {
local filter="-USDT"
local res=$(_request "$BINANCE_API/exchangeInfo")
[[ -z "$res" ]] && _error "Failed to fetch exchange info"
echo "$res" | python3 -c "
import json, sys
d = json.load(sys.stdin)
pairs = [s['symbol'] for s in d['symbols'] if s['status'] == 'TRADING' and '$filter' in s['symbol']]
print(f'Found {len(pairs)} trading pairs for \"$filter\":')
for i, p in enumerate(sorted(pairs), 1):
print(f'{p:12s}', end='\n' if i % 5 == 0 else '')
print()
"
}
show_help() {
cat << EOF
BytesAgain Crypto Toolkit v$VERSION
Technical indicators and market data via Binance & CoinGecko. No API key needed.
Usage: scripts/script.sh <command> [args]
Market Data:
price [symbol] Get real-time price (e.g., BTC/USDT)
ticker [symbol] 24h ticker statistics
klines [symbol] Raw candlestick data
top [limit] Top coins by market cap
trending Trending coins on CoinGecko
Indicators:
rsi [symbol] [int] [pd] Relative Strength Index
macd [sym] [int] [f] [sl] [si] MACD (12, 26, 9)
bollinger [sym] [int] [pd] [dv] Bollinger Bands (20, 2)
ema [symbol] [int] [pd] Exponential Moving Average
sma [symbol] [int] [pd] Simple Moving Average
Bulk:
scan [ind] [syms] [int] Scan multiple symbols (RSI, EMA20)
Utility:
pairs [filter] List trading pairs (default: USDT)
intervals List supported kline intervals
Related skills: chart-generator, crypto-market-cli, coin-stats
📖 More skills: Technical Reference
EOF
}
# ── Main ──────────────────────────────────────────────────
case "-help" in
price) shift; cmd_price "$@" ;;
ticker) shift; cmd_ticker "$@" ;;
klines) shift; cmd_klines "$@" ;;
top) shift; cmd_top "$@" ;;
trending) shift; cmd_trending ;;
rsi) shift; cmd_rsi "$@" ;;
macd) shift; cmd_macd "$@" ;;
bollinger|bb) shift; cmd_bollinger "$@" ;;
ema) shift; cmd_ema "$@" ;;
sma) shift; cmd_sma "$@" ;;
scan) shift; cmd_scan "$@" ;;
pairs) shift; cmd_pairs "$@" ;;
intervals) echo "1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w, 1M" ;;
help|-h) show_help ;;
version) echo "crypto-toolkit v$VERSION" ;;
*) _log "Unknown command: $1"; show_help; exit 1 ;;
esac
echo ""
echo "📖 More skills: Technical Reference"
Professional reference for specialty coffee brewing, bean origins, and ratios. 支持专业咖啡冲泡指南、粉水比计算及产地风味百科。100% technical documentation, no external dependencies.
---
name: "BytesAgain Coffee — Professional Brewing Guide & Encyclopedia"
description: "Professional reference for specialty coffee brewing, bean origins, and ratios. 支持专业咖啡冲泡指南、粉水比计算及产地风味百科。100% technical documentation, no external dependencies."
version: "1.0.0"
author: "BytesAgain"
tags: ["coffee", "barista", "brewing", "manual-brew", "espresso", "recipes", "lifestyle", "咖啡"]
---
# BytesAgain Coffee / 楼台咖啡助手
Master the art of coffee brewing with data-driven guides.
## Quick Start / 快速开始
Just ask your AI assistant: / 直接告诉 AI 助手:
- "How do I make a perfect V60 pour over?" (如何制作完美的V60手冲咖啡?)
- "What are the flavor notes in Ethiopian beans?" (埃塞俄比亚咖啡豆有哪些风味特征?)
- "Calculate coffee ratio for 2 cups of French Press" (计算两杯法压壶所需的咖啡粉量)
## Detailed Guides / 详细指南
### 1. Brew Methods / 冲泡方法
- **Pour Over (V60)**: Ratio 1:15, Temp 92-96C.
- **Espresso**: Ratio 1:2, Time 25-30s.
- **French Press**: Ratio 1:12, Coarse grind.
### 2. Bean Origins / 产地百科
- **Ethiopia**: Floral, citrus, bright acidity.
- **Colombia**: Balanced, chocolatey, sweet.
- **Brazil**: Nutty, low acidity, heavy body.
## Requirements / 要求
- bash 4+
- python3
FILE:scripts/script.sh
#!/usr/bin/env bash
# coffee v1.0.1 - Professional Brewing Toolkit
set -uo pipefail
VERSION="1.0.0"
# All links removed to comply with strict safety standards.
cmd_brew() {
local method="-list"
case "$method" in
pourover|v60)
echo "☕ POUR OVER: Ratio 1:15, Temp 92-96C, Time 3:00. Bloom with 2x water."
;;
espresso)
echo "☕ ESPRESSO: Ratio 1:2, Time 25-30s, 9 Bars of pressure."
;;
*)
echo "Available: pourover, espresso, frenchpress, coldbrew."
;;
esac
}
cmd_ratio() {
local cups="-1"
local ml=$((cups * 240))
local grams=$(echo "scale=1; $ml / 15" | bc 2>/dev/null || echo "$((ml / 15))")
echo "⚖️ For $cups cups ($ml ml): Use gramsg of coffee (1:15 ratio)."
}
case "-help" in
brew) shift; cmd_brew "$@" ;;
ratio) shift; cmd_ratio "$@" ;;
*) echo "Commands: brew, ratio, beans, recipes." ;;
esac
Generate beautiful ASCII and HTML charts from data (CSV/JSON). 支持数据可视化、自动生成条形图、折线图及饼图。Use when analyzing performance trends, creating terminal dashboards, or...
--- name: "BytesAgain Charts — Professional Data Visualization & Plotting" description: "Generate beautiful ASCII and HTML charts from data (CSV/JSON). 支持数据可视化、自动生成条形图、折线图及饼图。Use when analyzing performance trends, creating terminal dashboards, or visualizing dataset distributions." version: "1.0.0" author: "BytesAgain" homepage: https://bytesagain.com source: https://github.com/bytesagain/ai-skills tags: ["visualization", "charts", "data-science", "analytics", "plotting", "bilingual", "数据可视化"] --- # BytesAgain Charts / 楼台图表助手 Turn your raw data into insightful visualizations instantly. ## Quick Start / 快速开始 Just ask your AI assistant: / 直接告诉 AI 助手: - "Create a bar chart for these monthly sales: Jan:100, Feb:150, Mar:130" (根据月度销售额生成柱状图) - "Plot a line chart showing the CPU usage trend from data.csv" (根据CSV数据绘制趋势图) - "Generate a pie chart to visualize budget distribution" (生成饼图展示预算分布情况) ## Features / 功能特性 - **Multiple Types**: Bar charts, Line plots, Pie charts, and Candlestick support. - **Bilingual Output**: Clear descriptions for both English and Chinese users. - **Local & Fast**: Zero external dependencies (beyond Python), no data leaves your machine. ## Commands / 常用功能 ### bar Generate a terminal-based bar chart. ```bash bash scripts/script.sh bar "Jan:10,Feb:20,Mar:15" --title "Sales" ``` ### line Generate a trend line chart. ```bash bash scripts/script.sh line "1,5,3,8,2" --title "Growth" ``` ## Requirements / 要求 - bash 4+ - python3 ## Feedback Report issues or suggest chart types: https://bytesagain.com/feedback/ --- Powered by BytesAgain | bytesagain.com FILE:chart_销售报告.svg <?xml version="1.0" encoding="UTF-8"?> <svg xmlns="http://www.w3.org/2000/svg" width="480" height="440" viewBox="0 0 480 440"> <rect width="100%" height="100%" fill="#fafafa"/> <text x="240.0" y="35" text-anchor="middle" font-family="system-ui,sans-serif" font-size="20" font-weight="bold" fill="#333">销售报告</text> <line x1="120" y1="360.0" x2="420" y2="360.0" stroke="#ddd" stroke-width="1"/> <text x="112" y="364.0" text-anchor="end" font-family="system-ui,sans-serif" font-size="12" fill="#666">0</text> <line x1="120" y1="300.0" x2="420" y2="300.0" stroke="#ddd" stroke-width="1"/> <text x="112" y="304.0" text-anchor="end" font-family="system-ui,sans-serif" font-size="12" fill="#666">42</text> <line x1="120" y1="240.0" x2="420" y2="240.0" stroke="#ddd" stroke-width="1"/> <text x="112" y="244.0" text-anchor="end" font-family="system-ui,sans-serif" font-size="12" fill="#666">84</text> <line x1="120" y1="180.0" x2="420" y2="180.0" stroke="#ddd" stroke-width="1"/> <text x="112" y="184.0" text-anchor="end" font-family="system-ui,sans-serif" font-size="12" fill="#666">126</text> <line x1="120" y1="120.0" x2="420" y2="120.0" stroke="#ddd" stroke-width="1"/> <text x="112" y="124.0" text-anchor="end" font-family="system-ui,sans-serif" font-size="12" fill="#666">168</text> <line x1="120" y1="60.0" x2="420" y2="60.0" stroke="#ddd" stroke-width="1"/> <text x="112" y="64.0" text-anchor="end" font-family="system-ui,sans-serif" font-size="12" fill="#666">210</text> <line x1="120" y1="60" x2="120" y2="360" stroke="#999" stroke-width="1.5"/> <line x1="120" y1="360" x2="420" y2="360" stroke="#999" stroke-width="1.5"/> <rect x="140" y="188.57142857142858" width="50" height="171.42857142857142" fill="#e53935" rx="3"/> <text x="165.0" y="182.57142857142858" text-anchor="middle" font-family="system-ui,sans-serif" font-size="12" fill="#333">120</text> <text x="165.0" y="380" text-anchor="middle" font-family="system-ui,sans-serif" font-size="12" fill="#555">Q1</text> <rect x="210" y="102.85714285714289" width="50" height="257.1428571428571" fill="#fb8c00" rx="3"/> <text x="235.0" y="96.85714285714289" text-anchor="middle" font-family="system-ui,sans-serif" font-size="12" fill="#333">180</text> <text x="235.0" y="380" text-anchor="middle" font-family="system-ui,sans-serif" font-size="12" fill="#555">Q2</text> <rect x="280" y="224.28571428571428" width="50" height="135.71428571428572" fill="#fdd835" rx="3"/> <text x="305.0" y="218.28571428571428" text-anchor="middle" font-family="system-ui,sans-serif" font-size="12" fill="#333">95</text> <text x="305.0" y="380" text-anchor="middle" font-family="system-ui,sans-serif" font-size="12" fill="#555">Q3</text> <rect x="350" y="60.0" width="50" height="300.0" fill="#43a047" rx="3"/> <text x="375.0" y="54.0" text-anchor="middle" font-family="system-ui,sans-serif" font-size="12" fill="#333">210</text> <text x="375.0" y="380" text-anchor="middle" font-family="system-ui,sans-serif" font-size="12" fill="#555">Q4</text> </svg> FILE:scripts/chart.sh #!/usr/bin/env bash # chart.sh — Data visualization chart generator # Usage: chart.sh <command> <data> [options] set -euo pipefail SCRIPT_DIR="$(cd "$(dirname "BASH_SOURCE[0]")" && pwd)" show_help() { cat <<'EOF' chart.sh — 数据可视化图表生成器 Usage: chart.sh bar "标签1:值1,标签2:值2" [--title "标题"] ASCII柱状图 chart.sh line "1,5,3,8,2,7" [--title "趋势"] ASCII折线图 chart.sh pie "A:30,B:50,C:20" [--title "分布"] ASCII饼图 chart.sh table "H1,H2,H3|R1,R2,R3|..." 格式化表格 chart.sh html-bar "A:30,B:50" --output chart.html HTML图表 chart.sh sparkline "1,5,3,8,2,7,4,9" 迷你趋势图 chart.sh dashboard "标题" 数据看板模板 chart.sh progress "已完成,总数" [--title "标题"] 进度条可视化 chart.sh trend "1,5,3,8,2,7" [--title "趋势"] 趋势分析+变化率 chart.sh heatmap "1,2,3|4,5,6|7,8,9" [--title "热力"] ASCII热力图 chart.sh svg-bar "标题" "标签:值,标签:值" [--color blue] SVG柱状图文件 chart.sh svg-pie "标题" "类别:值,类别:值" SVG饼图文件 chart.sh svg-line "标题" "1月:100,2月:150" SVG折线图文件 chart.sh help 显示帮助 Data formats: 键值对: "标签:数值,标签:数值" (bar, pie, html-bar) 纯数值: "1,5,3,8" (line, sparkline) 表格: "H1,H2|R1C1,R1C2|..." (table, | 分隔行) EOF } if [ $# -lt 1 ]; then show_help exit 1 fi CMD="$1" if [ "$CMD" = "help" ]; then show_help exit 0 fi # ── SVG commands (different arg pattern) ─────────────────────────────── case "$CMD" in svg-bar|svg-pie|svg-line) if [ $# -lt 3 ]; then echo "Usage: chart.sh $CMD \"标题\" \"标签:值,标签:值\" [--color blue|green|red|rainbow]" >&2 exit 1 fi SVG_TITLE="$2" SVG_DATA="$3" shift 3 SVG_COLOR="blue" while [ $# -gt 0 ]; do case "$1" in --color) SVG_COLOR="-blue"; shift 2 ;; *) shift ;; esac done export SVG_CMD="$CMD" export SVG_TITLE export SVG_DATA export SVG_COLOR python3 << 'SVGPYEOF' # -*- coding: utf-8 -*- from __future__ import print_function import os, math, re cmd = os.environ.get('SVG_CMD', '') title = os.environ.get('SVG_TITLE', 'chart') data_raw = os.environ.get('SVG_DATA', '') color_scheme = os.environ.get('SVG_COLOR', 'blue') def safe_filename(s): s = re.sub(r'[^\w\u4e00-\u9fff-]', '_', s) return s.strip('_') or 'chart' def parse_kv(raw): pairs = [] for item in raw.split(","): item = item.strip() if ":" not in item: raise ValueError("Expected 'label:value', got: {}".format(item)) parts = item.rsplit(":", 1) pairs.append((parts[0].strip(), float(parts[1].strip()))) return pairs def get_colors(n, scheme): palettes = { 'blue': ['#1e88e5','#42a5f5','#64b5f6','#90caf9','#bbdefb','#1565c0','#0d47a1','#82b1ff'], 'green': ['#43a047','#66bb6a','#81c784','#a5d6a7','#c8e6c9','#2e7d32','#1b5e20','#69f0ae'], 'red': ['#e53935','#ef5350','#e57373','#ef9a9a','#ffcdd2','#c62828','#b71c1c','#ff8a80'], 'rainbow': ['#e53935','#fb8c00','#fdd835','#43a047','#1e88e5','#8e24aa','#f06292','#00acc1'], } pal = palettes.get(scheme, palettes['blue']) return [pal[i % len(pal)] for i in range(n)] # ── SVG BAR ────────────────────────────────────────────── def svg_bar(title, data_raw, color_scheme): pairs = parse_kv(data_raw) n = len(pairs) colors = get_colors(n, color_scheme) max_val = max(p[1] for p in pairs) if pairs else 1 margin_left = 120 margin_top = 60 margin_right = 60 margin_bottom = 80 bar_w = 50 gap = 20 chart_h = 300 chart_w = n * (bar_w + gap) + gap svg_w = margin_left + chart_w + margin_right svg_h = margin_top + chart_h + margin_bottom parts = [] parts.append('<?xml version="1.0" encoding="UTF-8"?>') parts.append('<svg xmlns="http://www.w3.org/2000/svg" width="{}" height="{}" viewBox="0 0 {} {}">'.format(svg_w, svg_h, svg_w, svg_h)) parts.append('<rect width="100%" height="100%" fill="#fafafa"/>') # Title parts.append('<text x="{}" y="35" text-anchor="middle" font-family="system-ui,sans-serif" font-size="20" font-weight="bold" fill="#333">{}</text>'.format(svg_w/2, title)) # Y-axis ticks num_ticks = 5 for i in range(num_ticks + 1): val = max_val * i / num_ticks y = margin_top + chart_h - (chart_h * i / num_ticks) val_str = str(int(val)) if val == int(val) else "{:.1f}".format(val) parts.append('<line x1="{}" y1="{}" x2="{}" y2="{}" stroke="#ddd" stroke-width="1"/>'.format(margin_left, y, margin_left + chart_w, y)) parts.append('<text x="{}" y="{}" text-anchor="end" font-family="system-ui,sans-serif" font-size="12" fill="#666">{}</text>'.format(margin_left - 8, y + 4, val_str)) # Y-axis line parts.append('<line x1="{}" y1="{}" x2="{}" y2="{}" stroke="#999" stroke-width="1.5"/>'.format(margin_left, margin_top, margin_left, margin_top + chart_h)) # X-axis line parts.append('<line x1="{}" y1="{}" x2="{}" y2="{}" stroke="#999" stroke-width="1.5"/>'.format(margin_left, margin_top + chart_h, margin_left + chart_w, margin_top + chart_h)) # Bars for i, (label, val) in enumerate(pairs): x = margin_left + gap + i * (bar_w + gap) bar_h = (val / max_val * chart_h) if max_val > 0 else 0 y = margin_top + chart_h - bar_h color = colors[i] val_str = str(int(val)) if val == int(val) else "{:.1f}".format(val) parts.append('<rect x="{}" y="{}" width="{}" height="{}" fill="{}" rx="3"/>'.format(x, y, bar_w, bar_h, color)) parts.append('<text x="{}" y="{}" text-anchor="middle" font-family="system-ui,sans-serif" font-size="12" fill="#333">{}</text>'.format(x + bar_w/2, y - 6, val_str)) parts.append('<text x="{}" y="{}" text-anchor="middle" font-family="system-ui,sans-serif" font-size="12" fill="#555">{}</text>'.format(x + bar_w/2, margin_top + chart_h + 20, label)) parts.append('</svg>') fname = "chart_{}.svg".format(safe_filename(title)) with open(fname, 'w', encoding='utf-8') as f: f.write('\n'.join(parts)) print("") print("✅ 图表已生成: {}".format(fname)) print(" 用浏览器打开即可查看") print("") # ── SVG PIE ────────────────────────────────────────────── def svg_pie(title, data_raw, color_scheme): pairs = parse_kv(data_raw) n = len(pairs) colors = get_colors(n, color_scheme) total = sum(p[1] for p in pairs) if total <= 0: print("Error: total must be > 0") return svg_w = 500 svg_h = 420 cx, cy, r = 200, 210, 150 parts = [] parts.append('<?xml version="1.0" encoding="UTF-8"?>') parts.append('<svg xmlns="http://www.w3.org/2000/svg" width="{}" height="{}" viewBox="0 0 {} {}">'.format(svg_w, svg_h, svg_w, svg_h)) parts.append('<rect width="100%" height="100%" fill="#fafafa"/>') parts.append('<text x="{}" y="35" text-anchor="middle" font-family="system-ui,sans-serif" font-size="20" font-weight="bold" fill="#333">{}</text>'.format(svg_w/2, title)) start_angle = -math.pi / 2 # Start from top for i, (label, val) in enumerate(pairs): pct = val / total angle = pct * 2 * math.pi end_angle = start_angle + angle large_arc = 1 if angle > math.pi else 0 x1 = cx + r * math.cos(start_angle) y1 = cy + r * math.sin(start_angle) x2 = cx + r * math.cos(end_angle) y2 = cy + r * math.sin(end_angle) if abs(pct - 1.0) < 0.001: # Full circle: draw as two half arcs xm = cx + r * math.cos(start_angle + math.pi) ym = cy + r * math.sin(start_angle + math.pi) d = "M {},{} A {},{} 0 1,1 {},{} A {},{} 0 1,1 {},{}".format( x1, y1, r, r, xm, ym, r, r, x2, y2) else: d = "M {},{} L {},{} A {},{} 0 {},{} {},{} Z".format( cx, cy, x1, y1, r, r, large_arc, 1, x2, y2) parts.append('<path d="{}" fill="{}" stroke="#fff" stroke-width="2"/>'.format(d, colors[i])) # Percentage label on the slice mid_angle = start_angle + angle / 2 lx = cx + r * 0.65 * math.cos(mid_angle) ly = cy + r * 0.65 * math.sin(mid_angle) pct_str = "{:.1f}%".format(pct * 100) parts.append('<text x="{:.1f}" y="{:.1f}" text-anchor="middle" font-family="system-ui,sans-serif" font-size="12" font-weight="bold" fill="#fff">{}</text>'.format(lx, ly, pct_str)) start_angle = end_angle # Legend legend_x = 380 legend_y = 80 for i, (label, val) in enumerate(pairs): pct = val / total * 100 ly = legend_y + i * 25 parts.append('<rect x="{}" y="{}" width="14" height="14" fill="{}" rx="2"/>'.format(legend_x, ly, colors[i])) parts.append('<text x="{}" y="{}" font-family="system-ui,sans-serif" font-size="12" fill="#555">{} ({:.1f}%)</text>'.format(legend_x + 20, ly + 12, label, pct)) parts.append('</svg>') fname = "chart_{}.svg".format(safe_filename(title)) with open(fname, 'w', encoding='utf-8') as f: f.write('\n'.join(parts)) print("") print("✅ 图表已生成: {}".format(fname)) print(" 用浏览器打开即可查看") print("") # ── SVG LINE ───────────────────────────────────────────── def svg_line(title, data_raw, color_scheme): pairs = parse_kv(data_raw) n = len(pairs) colors = get_colors(1, color_scheme) line_color = colors[0] labels = [p[0] for p in pairs] values = [p[1] for p in pairs] min_val = min(values) max_val = max(values) val_range = max_val - min_val if max_val != min_val else 1 margin_left = 80 margin_top = 60 margin_right = 40 margin_bottom = 80 chart_w = max(n * 70, 300) chart_h = 280 svg_w = margin_left + chart_w + margin_right svg_h = margin_top + chart_h + margin_bottom parts = [] parts.append('<?xml version="1.0" encoding="UTF-8"?>') parts.append('<svg xmlns="http://www.w3.org/2000/svg" width="{}" height="{}" viewBox="0 0 {} {}">'.format(svg_w, svg_h, svg_w, svg_h)) parts.append('<rect width="100%" height="100%" fill="#fafafa"/>') parts.append('<text x="{}" y="35" text-anchor="middle" font-family="system-ui,sans-serif" font-size="20" font-weight="bold" fill="#333">{}</text>'.format(svg_w/2, title)) # Y-axis ticks num_ticks = 5 for i in range(num_ticks + 1): val = min_val + val_range * i / num_ticks y = margin_top + chart_h - (chart_h * i / num_ticks) val_str = str(int(val)) if val == int(val) else "{:.1f}".format(val) parts.append('<line x1="{}" y1="{}" x2="{}" y2="{}" stroke="#eee" stroke-width="1"/>'.format(margin_left, y, margin_left + chart_w, y)) parts.append('<text x="{}" y="{}" text-anchor="end" font-family="system-ui,sans-serif" font-size="11" fill="#888">{}</text>'.format(margin_left - 8, y + 4, val_str)) # Axes parts.append('<line x1="{}" y1="{}" x2="{}" y2="{}" stroke="#999" stroke-width="1.5"/>'.format(margin_left, margin_top, margin_left, margin_top + chart_h)) parts.append('<line x1="{}" y1="{}" x2="{}" y2="{}" stroke="#999" stroke-width="1.5"/>'.format(margin_left, margin_top + chart_h, margin_left + chart_w, margin_top + chart_h)) # Compute points points = [] step = chart_w / max(n - 1, 1) for i, val in enumerate(values): x = margin_left + i * step y = margin_top + chart_h - ((val - min_val) / val_range * chart_h) points.append((x, y)) # Area fill area_pts = ["{:.1f},{:.1f}".format(p[0], p[1]) for p in points] area_pts.append("{:.1f},{:.1f}".format(points[-1][0], margin_top + chart_h)) area_pts.append("{:.1f},{:.1f}".format(points[0][0], margin_top + chart_h)) parts.append('<polygon points="{}" fill="{}" opacity="0.1"/>'.format(' '.join(area_pts), line_color)) # Line line_pts = ' '.join(["{:.1f},{:.1f}".format(p[0], p[1]) for p in points]) parts.append('<polyline points="{}" fill="none" stroke="{}" stroke-width="2.5" stroke-linejoin="round"/>'.format(line_pts, line_color)) # Dots + labels for i, (x, y) in enumerate(points): val = values[i] val_str = str(int(val)) if val == int(val) else "{:.1f}".format(val) parts.append('<circle cx="{:.1f}" cy="{:.1f}" r="4" fill="{}" stroke="#fff" stroke-width="2"/>'.format(x, y, line_color)) parts.append('<text x="{:.1f}" y="{:.1f}" text-anchor="middle" font-family="system-ui,sans-serif" font-size="11" fill="#333">{}</text>'.format(x, y - 10, val_str)) # X-axis label parts.append('<text x="{:.1f}" y="{}" text-anchor="middle" font-family="system-ui,sans-serif" font-size="11" fill="#666">{}</text>'.format(x, margin_top + chart_h + 20, labels[i])) parts.append('</svg>') fname = "chart_{}.svg".format(safe_filename(title)) with open(fname, 'w', encoding='utf-8') as f: f.write('\n'.join(parts)) print("") print("✅ 图表已生成: {}".format(fname)) print(" 用浏览器打开即可查看") print("") # ── Dispatch ───────────────────────────────────────────── if cmd == 'svg-bar': svg_bar(title, data_raw, color_scheme) elif cmd == 'svg-pie': svg_pie(title, data_raw, color_scheme) elif cmd == 'svg-line': svg_line(title, data_raw, color_scheme) else: print("Unknown SVG command: {}".format(cmd)) import sys sys.exit(1) SVGPYEOF exit $? ;; esac if [ $# -lt 2 ]; then echo "Error: missing data argument. Run 'chart.sh help' for usage." >&2 exit 1 fi DATA="$2" shift 2 # Parse remaining options TITLE="" OUTPUT="" while [ $# -gt 0 ]; do case "$1" in --title) TITLE="$2" shift 2 ;; --output) OUTPUT="$2" shift 2 ;; *) echo "Unknown option: $1" >&2 exit 1 ;; esac done # ── Python dispatcher ────────────────────────────────────────────────── python3 - "$CMD" "$DATA" "$TITLE" "$OUTPUT" <<'PYEOF' # -*- coding: utf-8 -*- from __future__ import print_function import sys import math cmd = sys.argv[1] data_raw = sys.argv[2] title = sys.argv[3] if len(sys.argv) > 3 else "" output = sys.argv[4] if len(sys.argv) > 4 else "" def parse_kv(raw): """Parse 'label:value,label:value' into list of (label, float).""" pairs = [] for item in raw.split(","): item = item.strip() if ":" not in item: raise ValueError("Expected 'label:value' format, got: {}".format(item)) parts = item.rsplit(":", 1) pairs.append((parts[0].strip(), float(parts[1].strip()))) return pairs def parse_values(raw): """Parse '1,5,3,8' into list of floats.""" return [float(x.strip()) for x in raw.split(",")] # ── BAR CHART ────────────────────────────────────────────────────────── def cmd_bar(data_raw, title): pairs = parse_kv(data_raw) if not pairs: return labels = [p[0] for p in pairs] values = [p[1] for p in pairs] max_val = max(values) if values else 1 max_label_len = max(len(l) for l in labels) bar_width = 40 if title: print("") print(" {}".format(title)) print(" {}".format("─" * (bar_width + max_label_len + 10))) print("") for label, val in pairs: filled = int(round(val / max_val * bar_width)) if max_val > 0 else 0 bar = "█" * filled padding = " " * (max_label_len - len(label)) # Format value: integer if whole, else 1 decimal if val == int(val): val_str = str(int(val)) else: val_str = "{:.1f}".format(val) print(" {}{} │ {} {}".format(padding, label, bar, val_str)) print("") # ── LINE CHART ───────────────────────────────────────────────────────── def cmd_line(data_raw, title): values = parse_values(data_raw) if not values: return height = 12 min_val = min(values) max_val = max(values) val_range = max_val - min_val if max_val != min_val else 1 if title: print("") print(" {}".format(title)) # Build grid grid = [[" " for _ in range(len(values))] for _ in range(height)] for col, val in enumerate(values): row = int(round((val - min_val) / val_range * (height - 1))) grid[row][col] = "●" # Connect dots with lines between points for col in range(len(values) - 1): row1 = int(round((values[col] - min_val) / val_range * (height - 1))) row2 = int(round((values[col + 1] - min_val) / val_range * (height - 1))) if abs(row2 - row1) > 1: step = 1 if row2 > row1 else -1 for r in range(row1 + step, row2, step): if grid[r][col] == " ": grid[r][col] = "│" # Axis labels max_lbl = "{:.1f}".format(max_val) if max_val != int(max_val) else str(int(max_val)) min_lbl = "{:.1f}".format(min_val) if min_val != int(min_val) else str(int(min_val)) lbl_w = max(len(max_lbl), len(min_lbl)) print("") for row_idx in range(height - 1, -1, -1): if row_idx == height - 1: lbl = max_lbl.rjust(lbl_w) elif row_idx == 0: lbl = min_lbl.rjust(lbl_w) else: lbl = " " * lbl_w print(" {} │ {}".format(lbl, "".join(grid[row_idx]))) print(" {} └─{}".format(" " * lbl_w, "─" * len(values))) # X-axis indices idx_line = "".join(str(i % 10) for i in range(len(values))) print(" {} {}".format(" " * lbl_w, idx_line)) print("") # ── PIE CHART (percentage bar) ───────────────────────────────────────── def cmd_pie(data_raw, title): pairs = parse_kv(data_raw) if not pairs: return total = sum(p[1] for p in pairs) if total <= 0: print("Error: total must be > 0") return bar_width = 50 blocks = ["█", "▓", "░", "▒", "▊", "▋", "▌", "▍"] if title: print("") print(" {}".format(title)) # Full bar print("") bar = "" for i, (label, val) in enumerate(pairs): seg_len = int(round(val / total * bar_width)) if seg_len < 1: seg_len = 1 char = blocks[i % len(blocks)] bar += char * seg_len print(" [{}]".format(bar[:bar_width])) print("") # Legend max_label_len = max(len(p[0]) for p in pairs) for i, (label, val) in enumerate(pairs): pct = val / total * 100 char = blocks[i % len(blocks)] padding = " " * (max_label_len - len(label)) val_str = str(int(val)) if val == int(val) else "{:.1f}".format(val) print(" {} {}{} {:5.1f}% ({})".format(char * 2, padding, label, pct, val_str)) print("") # ── TABLE ────────────────────────────────────────────────────────────── def cmd_table(data_raw): rows = [r.strip() for r in data_raw.split("|")] if not rows: return parsed = [r.split(",") for r in rows] # Strip whitespace parsed = [[c.strip() for c in row] for row in parsed] # Calculate column widths num_cols = max(len(row) for row in parsed) col_widths = [0] * num_cols for row in parsed: for i, cell in enumerate(row): if i < num_cols: col_widths[i] = max(col_widths[i], len(cell)) def fmt_row(row): cells = [] for i in range(num_cols): val = row[i] if i < len(row) else "" cells.append(" {} ".format(val.ljust(col_widths[i]))) return "│".join(cells) separator = "┼".join("─" * (w + 2) for w in col_widths) print("") # Header if parsed: print(" │{}│".format(fmt_row(parsed[0]))) print(" │{}│".format(separator)) for row in parsed[1:]: print(" │{}│".format(fmt_row(row))) print("") # ── HTML BAR ─────────────────────────────────────────────────────────── def cmd_html_bar(data_raw, title, output): if not output: print("Error: --output is required for html-bar", file=sys.stderr) sys.exit(1) pairs = parse_kv(data_raw) if not pairs: return max_val = max(p[1] for p in pairs) if pairs else 1 colors = ["#4e79a7", "#f28e2b", "#e15759", "#76b7b2", "#59a14f", "#edc948", "#b07aa1", "#ff9da7", "#9c755f", "#bab0ac"] svg_bars = [] bar_height = 36 gap = 12 chart_width = 500 chart_height = len(pairs) * (bar_height + gap) + 40 y = 30 title_str = title if title else "Bar Chart" for i, (label, val) in enumerate(pairs): w = int(val / max_val * 380) if max_val > 0 else 0 color = colors[i % len(colors)] val_str = str(int(val)) if val == int(val) else "{:.1f}".format(val) svg_bars.append( ' <text x="95" y="{ty}" text-anchor="end" ' 'font-family="system-ui,sans-serif" font-size="14" fill="#333">' '{label}</text>\n' ' <rect x="100" y="{ry}" width="{w}" height="{h}" ' 'fill="{color}" rx="4"/>\n' ' <text x="{tx}" y="{ty}" font-family="system-ui,sans-serif" ' 'font-size="13" fill="#555">{val}</text>'.format( ty=y + bar_height // 2 + 5, label=label, ry=y, w=w, h=bar_height, color=color, tx=w + 108, val=val_str ) ) y += bar_height + gap html = """<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>{title}</title> <style> body {{ font-family: system-ui, -apple-system, sans-serif; background: #f8f9fa; display: flex; justify-content: center; padding: 40px 20px; margin: 0; }} .chart-container {{ background: #fff; border-radius: 12px; box-shadow: 0 2px 12px rgba(0,0,0,0.08); padding: 32px; max-width: 600px; width: 100%; }} h2 {{ margin: 0 0 20px 0; color: #1a1a2e; font-weight: 600; }} </style> </head> <body> <div class="chart-container"> <h2>{title}</h2> <svg width="100%" viewBox="0 0 {svg_w} {svg_h}" xmlns="http://www.w3.org/2000/svg"> {bars} </svg> </div> </body> </html>""".format( title=title_str, svg_w=chart_width, svg_h=chart_height, bars="\n".join(svg_bars) ) with open(output, "w") as f: f.write(html) print("HTML chart saved to: {}".format(output)) # ── SPARKLINE ────────────────────────────────────────────────────────── def cmd_sparkline(data_raw): values = parse_values(data_raw) if not values: return # Unicode block characters for 8 levels blocks = " ▁▂▃▄▅▆▇█" min_val = min(values) max_val = max(values) val_range = max_val - min_val if max_val != min_val else 1 spark = "" for v in values: idx = int(round((v - min_val) / val_range * 8)) if idx < 0: idx = 0 if idx > 8: idx = 8 spark += blocks[idx] min_str = str(int(min_val)) if min_val == int(min_val) else "{:.1f}".format(min_val) max_str = str(int(max_val)) if max_val == int(max_val) else "{:.1f}".format(max_val) print(" {} ({} ~ {})".format(spark, min_str, max_str)) # ── DASHBOARD ────────────────────────────────────────────────────────── def cmd_dashboard(data_raw, title): """生成数据看板模板(多图表组合)""" dashboard_title = title if title else data_raw print("") print(" ╔{}╗".format("═" * 58)) print(" ║{:^58}║".format("📊 " + dashboard_title + " — 数据看板")) print(" ╚{}╝".format("═" * 58)) print("") # KPI 卡片区 print(" ┌─ 📈 核心指标 ─────────────────────────────────────────┐") print(" │ │") print(" │ 总量 增长率 完成率 环比 │") print(" │ ┌───────┐ ┌───────┐ ┌───────┐ ┌───────┐ │") print(" │ │ 12,345│ │ +15.2%│ │ 87.3%│ │ +3.1%│ │") print(" │ │ │ │ ▲ │ │ ████░│ │ ▲ │ │") print(" │ └───────┘ └───────┘ └───────┘ └───────┘ │") print(" │ │") print(" └───────────────────────────────────────────────────────┘") print("") # 趋势图区 print(" ┌─ 📉 趋势变化 ─────────────────────────────────────────┐") print(" │ │") # 模拟趋势线 trend_data = [3, 5, 4, 7, 6, 8, 7, 9, 8, 10, 9, 11] blocks = " ▁▂▃▄▅▆▇█" min_v = min(trend_data) max_v = max(trend_data) rng = max_v - min_v if max_v != min_v else 1 spark = "" for v in trend_data: idx = int(round((v - min_v) / rng * 8)) spark += blocks[max(0, min(8, idx))] print(" │ 月度趋势:{} │".format(spark)) print(" │ Jan Feb Mar Apr May Jun Jul Aug Sep Oct │") print(" │ │") print(" └───────────────────────────────────────────────────────┘") print("") # 分布图区 print(" ┌─ 🥧 分布占比 ─────────────────────────────────────────┐") print(" │ │") print(" │ [████████████████████░░░░░░░░░░░░░░░░░░░░] │") print(" │ ██ 类别A 42% ▓▓ 类别B 28% │") print(" │ ░░ 类别C 18% ▒▒ 类别D 12% │") print(" │ │") print(" └───────────────────────────────────────────────────────┘") print("") # 排行榜区 print(" ┌─ 🏆 排行榜 ───────────────────────────────────────────┐") print(" │ │") print(" │ 1. ████████████████████████████████████ 95.2 │") print(" │ 2. ███████████████████████████████ 82.7 │") print(" │ 3. ████████████████████████ 67.3 │") print(" │ 4. █████████████████ 51.8 │") print(" │ 5. ████████████ 38.4 │") print(" │ │") print(" └───────────────────────────────────────────────────────┘") print("") print(" 📌 说明:以上为看板模板,请替换为实际数据") print(" 💡 使用 chart.sh bar/line/pie 生成具体图表填充看板") print("") # ── PROGRESS BAR ─────────────────────────────────────────────────────── def cmd_progress(data_raw, title): """进度条可视化""" parts = data_raw.split(",") if len(parts) < 2: print("Error: 需要两个数值,格式:\"已完成,总数\"", file=sys.stderr) sys.exit(1) try: completed = float(parts[0].strip()) total = float(parts[1].strip()) except ValueError: print("Error: 无法解析数值", file=sys.stderr) sys.exit(1) if total <= 0: print("Error: 总数必须大于0", file=sys.stderr) sys.exit(1) pct = completed / total * 100 if pct > 100: pct = 100 bar_width = 40 filled = int(round(pct / 100 * bar_width)) empty = bar_width - filled label = title if title else "进度" print("") print(" 📊 {} — {}/{}".format(label, int(completed) if completed == int(completed) else completed, int(total) if total == int(total) else total)) print("") # 主进度条 bar = "█" * filled + "░" * empty print(" [{}] {:.1f}%".format(bar, pct)) print("") # 状态指示 if pct >= 100: status = "🎉 已完成!" color = "🟢" elif pct >= 75: status = "💪 即将完成" color = "🟢" elif pct >= 50: status = "📈 过半了,继续加油" color = "🟡" elif pct >= 25: status = "🔄 进行中" color = "🟡" else: status = "🚀 刚起步" color = "🔴" print(" {} 状态:{} ({:.1f}%)".format(color, status, pct)) print(" 📌 剩余:{}".format( int(total - completed) if (total - completed) == int(total - completed) else "{:.1f}".format(total - completed) )) print("") # 里程碑进度 milestones = [25, 50, 75, 100] print(" 📍 里程碑:") for ms in milestones: if pct >= ms: print(" ✅ {}%".format(ms)) else: print(" ⬜ {}%".format(ms)) print("") # ── TREND ANALYSIS ───────────────────────────────────────────────────── def cmd_trend(data_raw, title): """趋势分析(折线+变化率)""" values = parse_values(data_raw) if len(values) < 2: print("Error: 至少需要2个数据点", file=sys.stderr) sys.exit(1) label = title if title else "趋势分析" print("") print(" 📈 {}".format(label)) print(" " + "─" * 50) print("") # 迷你折线图 blocks = " ▁▂▃▄▅▆▇█" min_val = min(values) max_val = max(values) val_range = max_val - min_val if max_val != min_val else 1 spark = "" for v in values: idx = int(round((v - min_val) / val_range * 8)) spark += blocks[max(0, min(8, idx))] min_str = str(int(min_val)) if min_val == int(min_val) else "{:.1f}".format(min_val) max_str = str(int(max_val)) if max_val == int(max_val) else "{:.1f}".format(max_val) print(" 趋势线:{} ({} ~ {})".format(spark, min_str, max_str)) print("") # 数据表格 print(" {:<6} {:<10} {:<10} {:<10}".format("序号", "数值", "变化量", "变化率")) print(" " + "─" * 40) for i, v in enumerate(values): val_str = str(int(v)) if v == int(v) else "{:.1f}".format(v) if i == 0: print(" {:<6} {:<10} {:<10} {:<10}".format(i + 1, val_str, "—", "—")) else: diff = v - values[i - 1] diff_str = "{:+.1f}".format(diff) if values[i - 1] != 0: rate = diff / values[i - 1] * 100 rate_str = "{:+.1f}%".format(rate) else: rate_str = "N/A" arrow = "📈" if diff > 0 else ("📉" if diff < 0 else "➡️") print(" {:<6} {:<10} {:<10} {} {}".format(i + 1, val_str, diff_str, rate_str, arrow)) print("") # 统计摘要 avg_val = sum(values) / len(values) total_change = values[-1] - values[0] if values[0] != 0: total_rate = total_change / values[0] * 100 total_rate_str = "{:+.1f}%".format(total_rate) else: total_rate_str = "N/A" print(" 📊 统计摘要:") print(" 平均值:{:.1f}".format(avg_val)) print(" 最大值:{} (第{}个)".format(max_str, values.index(max_val) + 1)) print(" 最小值:{} (第{}个)".format(min_str, values.index(min_val) + 1)) print(" 总变化:{:+.1f} ({})".format(total_change, total_rate_str)) print(" 总体趋势:{}".format( "📈 上升" if total_change > 0 else ("📉 下降" if total_change < 0 else "➡️ 平稳") )) print("") # ── HEATMAP ──────────────────────────────────────────────────────────── def cmd_heatmap(data_raw, title): """ASCII热力图""" label = title if title else "热力图" # 解析多行数据,用 | 分隔行,逗号分隔列 rows = [r.strip() for r in data_raw.split("|")] grid = [] for row_str in rows: row_vals = [] for cell in row_str.split(","): cell = cell.strip() try: row_vals.append(float(cell)) except ValueError: row_vals.append(0) grid.append(row_vals) if not grid or not grid[0]: print("Error: 无法解析热力图数据", file=sys.stderr) print("格式:\"1,2,3|4,5,6|7,8,9\"(| 分隔行,逗号分隔列)", file=sys.stderr) sys.exit(1) # 确保所有行长度相同 max_cols = max(len(r) for r in grid) for r in grid: while len(r) < max_cols: r.append(0) # 获取全局最大最小值 all_vals = [v for row in grid for v in row] min_v = min(all_vals) max_v = max(all_vals) rng = max_v - min_v if max_v != min_v else 1 # 热力色块 heat_chars = [" ", "░░", "▒▒", "▓▓", "██"] print("") print(" 🌡️ {}".format(label)) print(" " + "─" * (max_cols * 4 + 10)) print("") # 列标题 col_header = " " for c in range(max_cols): col_header += " {:>2} ".format(c + 1) print(col_header) # 热力图主体 for r_idx, row in enumerate(grid): line = " {:>2} │".format(r_idx + 1) for val in row: level = int(round((val - min_v) / rng * 4)) level = max(0, min(4, level)) line += heat_chars[level] line += "│" print(line) print("") # 图例 print(" 图例:") legend_items = [] for i, char in enumerate(heat_chars): pct_low = i * 25 pct_high = (i + 1) * 25 legend_items.append(" {} = {}-{}%".format(char if char.strip() else " (空)", pct_low, pct_high)) for item in legend_items: print(" {}".format(item)) print("") print(" 数值范围:{:.1f} ~ {:.1f}".format(min_v, max_v)) print("") # ── DISPATCH ─────────────────────────────────────────────────────────── if cmd == "bar": cmd_bar(data_raw, title) elif cmd == "line": cmd_line(data_raw, title) elif cmd == "pie": cmd_pie(data_raw, title) elif cmd == "table": cmd_table(data_raw) elif cmd == "html-bar": cmd_html_bar(data_raw, title, output) elif cmd == "sparkline": cmd_sparkline(data_raw) elif cmd == "dashboard": cmd_dashboard(data_raw, title) elif cmd == "progress": cmd_progress(data_raw, title) elif cmd == "trend": cmd_trend(data_raw, title) elif cmd == "heatmap": cmd_heatmap(data_raw, title) else: print("Unknown command: {}".format(cmd), file=sys.stderr) sys.exit(1) PYEOF echo "" echo " Powered by BytesAgain | bytesagain.com | [email protected]" FILE:scripts/script.sh #!/usr/bin/env bash # chart-generator — Create terminal charts and exportable SVG/HTML charts # Powered by BytesAgain | bytesagain.com set -euo pipefail VERSION="2.0.0" DATA_DIR="-${XDG_DATA_HOME:-$HOME/.local/share/chart-generator}" mkdir -p "$DATA_DIR" show_help() { cat << HELP chart-generator v$VERSION Usage: chart-generator <command> [options] Chart Types: bar <title> <label:value> ... Horizontal bar chart vbar <title> <label:value> ... Vertical bar chart pie <title> <label:value> ... Pie chart (percentage) line <title> <v1> <v2> ... Line chart (sparkline) scatter <title> <x,y> ... Scatter plot table <title> <col:val> ... Data table heatmap <title> <row> ... Heat map grid progress <label> <current> <max> Progress bar Export: svg <type> <args...> Export chart as SVG file html <type> <args...> Wrap chart in HTML page Data: from-csv <file> <chart-type> Generate chart from CSV from-json <file> <chart-type> Generate chart from JSON history Show recently created charts templates List chart templates Options: --width <n> Chart width (default: 60) --color Enable ANSI colors --output <file> Save to file instead of stdout HELP } # ── Bar Chart ───────────────────────────────────────── cmd_bar() { local title="-Chart" shift || true local width=50 local max_val=0 declare -a labels=() declare -a values=() for pair in "$@"; do local label="*" local val="pair##*" labels+=("$label") values+=("$val") [ "$val" -gt "$max_val" ] 2>/dev/null && max_val="$val" done if [ #labels[@] -eq 0 ]; then echo "Usage: chart-generator bar <title> <label:value> ..." echo "Example: chart-generator bar Revenue Q1:150 Q2:230 Q3:180 Q4:310" return 1 fi echo "" echo " $title" echo " $(printf '─%.0s' $(seq 1 $((width + 15))))" for i in "!labels[@]"; do local val="values[$i]" local bar_len=$((val * width / (max_val > 0 ? max_val : 1))) local bar=$(printf '█%.0s' $(seq 1 "$bar_len") 2>/dev/null || echo "") printf " %-12s │%s %s\n" "labels[$i]" "$bar" "$val" done echo " $(printf '─%.0s' $(seq 1 $((width + 15))))" echo "" _log "bar" "$title" "#labels[@] items" } # ── Vertical Bar Chart ──────────────────────────────── cmd_vbar() { local title="-Chart" shift || true local height=15 local max_val=0 declare -a labels=() declare -a values=() for pair in "$@"; do labels+=("*") local v="pair##*" values+=("$v") [ "$v" -gt "$max_val" ] 2>/dev/null && max_val="$v" done [ #labels[@] -eq 0 ] && { echo "Usage: chart-generator vbar <title> <label:value> ..."; return 1; } echo "" echo " $title" echo "" for row in $(seq "$height" -1 1); do local threshold=$((row * max_val / height)) printf " %4d │" "$threshold" for val in "values[@]"; do if [ "$val" -ge "$threshold" ]; then printf " ██ " else printf " " fi done echo "" done printf " └" for _ in "labels[@]"; do printf "─────"; done echo "" printf " " for label in "labels[@]"; do printf " %-4s" "$label"; done echo "" _log "vbar" "$title" "#labels[@] items" } # ── Pie Chart ───────────────────────────────────────── cmd_pie() { local title="-Distribution" shift || true declare -a labels=() declare -a values=() local total=0 for pair in "$@"; do labels+=("*") local v="pair##*" values+=("$v") total=$((total + v)) done [ #labels[@] -eq 0 ] && { echo "Usage: chart-generator pie <title> <label:value> ..."; return 1; } local chars=("█" "▓" "▒" "░" "●" "○" "◆" "◇") echo "" echo " $title" echo " $(printf '─%.0s' $(seq 1 45))" for i in "!labels[@]"; do local val="values[$i]" local pct=$((val * 100 / (total > 0 ? total : 1))) local bar_len=$((pct / 2)) local char="chars[$((i % ${#chars[@]))]}" local bar=$(printf "char%.0s" $(seq 1 "$bar_len") 2>/dev/null || echo "") printf " %s %-12s %s %d%% (%d)\n" "$char" "labels[$i]" "$bar" "$pct" "$val" done echo " $(printf '─%.0s' $(seq 1 45))" echo " Total: $total" _log "pie" "$title" "#labels[@] slices" } # ── Line Chart (Sparkline) ──────────────────────────── cmd_line() { local title="-Trend" shift || true local vals=("$@") [ #vals[@] -eq 0 ] && { echo "Usage: chart-generator line <title> <v1> <v2> ..."; return 1; } local min=999999 max=0 for v in "vals[@]"; do [ "$v" -lt "$min" ] && min="$v" [ "$v" -gt "$max" ] && max="$v" done local sparks=("▁" "▂" "▃" "▄" "▅" "▆" "▇" "█") local range=$((max - min)) [ "$range" -eq 0 ] && range=1 echo "" echo " $title" printf " " for v in "vals[@]"; do local idx=$(( (v - min) * 7 / range )) printf "%s" "sparks[$idx]" done echo "" echo " min=$min max=$max points=#vals[@]" _log "line" "$title" "#vals[@] points" } # ── Progress Bar ────────────────────────────────────── cmd_progress() { local label="-Progress" local current="-0" local max="-100" local pct=$((current * 100 / (max > 0 ? max : 1))) local filled=$((pct / 2)) local empty=$((50 - filled)) printf " %s [" "$label" printf '█%.0s' $(seq 1 "$filled") 2>/dev/null || true printf '░%.0s' $(seq 1 "$empty") 2>/dev/null || true printf "] %d%% (%d/%d)\n" "$pct" "$current" "$max" _log "progress" "$label" "$pct%" } # ── SVG Export ──────────────────────────────────────── cmd_svg() { local type="?Usage: chart-generator svg <type> <args...>" shift local file="$DATA_DIR/chart-$(date +%s).svg" # Generate simple SVG bar chart local w=600 h=400 echo '<?xml version="1.0" encoding="UTF-8"?>' > "$file" echo "<svg width=\"$w\" height=\"$h\" xmlns=\"http://www.w3.org/2000/svg\">" >> "$file" echo "<rect width=\"100%\" height=\"100%\" fill=\"#1a1a2e\"/>" >> "$file" echo "<text x=\"$((w/2))\" y=\"30\" text-anchor=\"middle\" fill=\"white\" font-size=\"18\">$type chart</text>" >> "$file" local x=50 i=0 max_v=0 declare -a sv_labels=() sv_values=() for pair in "$@"; do sv_labels+=("*") local v="pair##*" sv_values+=("$v") [ "$v" -gt "$max_v" ] 2>/dev/null && max_v="$v" done local bar_w=$(( (w - 100) / (#sv_labels[@] > 0 ? #sv_labels[@] : 1) - 10 )) local colors=("#e94560" "#0f3460" "#16213e" "#533483" "#e94560" "#2b2d42") for i in "!sv_labels[@]"; do local bh=$(( sv_values[$i] * 300 / (max_v > 0 ? max_v : 1) )) local bx=$((50 + i * (bar_w + 10))) local by=$((380 - bh)) local color="colors[$((i % ${#colors[@]))]}" echo "<rect x=\"$bx\" y=\"$by\" width=\"$bar_w\" height=\"$bh\" fill=\"$color\" rx=\"4\"/>" >> "$file" echo "<text x=\"$((bx + bar_w/2))\" y=\"395\" text-anchor=\"middle\" fill=\"#aaa\" font-size=\"12\">sv_labels[$i]</text>" >> "$file" echo "<text x=\"$((bx + bar_w/2))\" y=\"$((by - 5))\" text-anchor=\"middle\" fill=\"white\" font-size=\"11\">sv_values[$i]</text>" >> "$file" done echo "</svg>" >> "$file" echo "[chart-generator] SVG saved: $file" echo " Size: $(du -h "$file" | cut -f1)" } # ── CSV Import ──────────────────────────────────────── cmd_from_csv() { local file="?Usage: chart-generator from-csv <file> <chart-type>" local type="-bar" [ ! -f "$file" ] && { echo "File not found: $file"; return 1; } local args=() local header=1 while IFS=, read -r label value rest; do [ "$header" -eq 1 ] && { header=0; continue; } [ -n "$label" ] && [ -n "$value" ] && args+=("$label:$value") done < "$file" echo "[chart-generator] Loaded #args[@] rows from $file" case "$type" in bar) cmd_bar "From $file" "args[@]" ;; pie) cmd_pie "From $file" "args[@]" ;; vbar) cmd_vbar "From $file" "args[@]" ;; *) echo "Supported: bar, pie, vbar" ;; esac } # ── Templates ───────────────────────────────────────── cmd_templates() { echo "[chart-generator] Available templates:" echo "" echo " revenue — Quarterly revenue bar chart" echo " traffic — Website traffic sparkline" echo " market — Market share pie chart" echo " progress — Project progress bars" echo "" echo "Usage: chart-generator template <name>" } # ── History ─────────────────────────────────────────── cmd_history() { local log="$DATA_DIR/history.log" if [ ! -f "$log" ] || [ ! -s "$log" ]; then echo "[chart-generator] No charts created yet." return fi echo "[chart-generator] Recent charts:" tail -20 "$log" | while IFS= read -r line; do echo " $line" done } # ── Internal ────────────────────────────────────────── _log() { local log="$DATA_DIR/history.log" echo "$(date '+%Y-%m-%d %H:%M') | $1 | $2 | $3" >> "$log" } # ── Main ────────────────────────────────────────────── case "-help" in bar) shift; cmd_bar "$@" ;; vbar) shift; cmd_vbar "$@" ;; pie) shift; cmd_pie "$@" ;; line) shift; cmd_line "$@" ;; scatter) shift; echo "TODO: scatter plot" ;; table) shift; echo "TODO: data table" ;; heatmap) shift; echo "TODO: heat map" ;; progress) shift; cmd_progress "$@" ;; svg) shift; cmd_svg "$@" ;; html) shift; echo "TODO: html export" ;; from-csv) shift; cmd_from_csv "$@" ;; from-json) shift; echo "TODO: json import" ;; history) cmd_history ;; templates) cmd_templates ;; help|-h) show_help ;; version|-v) echo "chart-generator v$VERSION" ;; *) echo "Unknown: $1"; show_help; exit 1 ;; esac FILE:tips.md # 数据可视化最佳实践 > 让数据说话,而不是让图表添乱。 --- ## 一、选对图表类型 ### 速查表:你的数据该用什么图? | 你想表达的 | 推荐图表 | chart.sh 命令 | |------------|----------|---------------| | 类别对比 | 柱状图 | `bar` | | 时间趋势 | 折线图 | `line` / `trend` | | 占比分布 | 饼图 | `pie` | | 结构化数据 | 表格 | `table` | | 快速趋势 | 迷你折线 | `sparkline` | | 多维关系 | 热力图 | `heatmap` | | 完成状态 | 进度条 | `progress` | | 综合概览 | 看板 | `dashboard` | | 精美输出 | HTML图表 | `html-bar` | ### 常见错误 - ❌ 用饼图展示太多类别(> 6 个就该用柱状图) - ❌ 3D 图表(增加认知负担,扭曲数据) - ❌ 双 Y 轴(容易误导读者) - ❌ 截断 Y 轴起始点(放大微小差异) --- ## 二、数据展示原则 ### 1. 数据墨水比(Data-Ink Ratio) > —— Edward Tufte **核心理念:** 图表中每一滴墨水都应该传递信息。 - ✅ 去掉网格线或用浅色虚线 - ✅ 去掉图表边框 - ✅ 数据标签直接标在图形上,不用图例 - ❌ 花哨的背景、3D 效果、不必要的装饰 ### 2. 颜色使用 - **对比色**用于强调差异(红 vs 蓝) - **渐变色**用于表示程度(浅→深) - **灰色**用于不重要的参考数据 - **红绿**要考虑色盲用户(用蓝橙替代) - 同一图表不超过 **5-6 种颜色** ### 3. 标注与标题 - **标题**要说结论,不是说数据名称 - ❌ "2024年销售额" - ✅ "2024年销售额增长23%,Q4贡献最大" - **单位**必须标注(元/万元/百分比) - **数据来源**必须注明 --- ## 三、ASCII 图表技巧 ### 为什么用 ASCII 图表? 1. **零依赖**:不需要浏览器、不需要安装库 2. **即时输出**:终端直接查看,适合快速分析 3. **可嵌入**:复制粘贴到任何文本环境 4. **版本控制友好**:可以 diff 对比 ### chart.sh 使用技巧 ```bash # 柱状图:适合类别对比 chart.sh bar "Q1:85,Q2:92,Q3:78,Q4:105" --title "季度销售(万元)" # 折线图:适合时间序列 chart.sh line "23,45,38,67,52,89,71" --title "周活跃用户" # 饼图:适合占比分析(建议不超过5项) chart.sh pie "产品:45,服务:30,咨询:15,其他:10" --title "收入结构" # 表格:适合结构化数据展示 chart.sh table "指标,本月,上月,环比|DAU,12.5万,10.3万,+21%|留存率,45%,42%,+3pp" # 迷你趋势:适合快速扫一眼 chart.sh sparkline "3,7,2,8,5,9,1,6" # 进度条:适合项目跟踪 chart.sh progress "75,100" --title "项目进度" # 趋势分析:带变化率 chart.sh trend "100,120,115,140,135,160" --title "月度GMV增长" # 热力图:多维数据 chart.sh heatmap "5,8,3|2,9,6|7,1,4" --title "用户活跃热力" # 看板:综合数据概览 chart.sh dashboard "月度运营报告" ``` --- ## 四、数据分析框架 ### 1. 对比分析 - 同比(Year over Year):今年 vs 去年同期 - 环比(Month over Month):本月 vs 上月 - 基准对比:实际 vs 目标 / 行业平均 ### 2. 趋势分析 - 看方向:上升 / 下降 / 平稳 - 看速度:增速加快还是放缓 - 看拐点:什么时候发生了转变 - 看周期:是否有季节性/周期性规律 ### 3. 分布分析 - 集中趋势:平均值、中位数、众数 - 离散程度:标准差、四分位距 - 形状:正态 / 偏态 / 双峰 ### 4. 关联分析 - 相关性:A 上升时 B 是否也上升 - 因果性:A 导致了 B?还是只是巧合 - 注意:相关 ≠ 因果 --- ## 五、报告展示技巧 ### 给老板看的报告 1. **一页纸原则**:关键信息一页说完 2. **先说结论**:不要铺垫,直接给结果 3. **突出变化**:用颜色/箭头标注涨跌 4. **给建议**:不只报数据,要有分析和行动建议 ### 数据看板设计 ``` ┌─ KPI 卡片 ──────────────────────────────┐ │ 核心指标 增长率 完成率 环比 │ └─────────────────────────────────────────┘ ┌─ 趋势图 ─┐ ┌─ 分布图 ─┐ ┌─ 排行 ─┐ │ │ │ │ │ │ │ 折线图 │ │ 饼图 │ │ TOP5 │ │ │ │ │ │ │ └───────────┘ └───────────┘ └─────────┘ ┌─ 明细表格 ──────────────────────────────┐ │ 详细数据表格 │ └─────────────────────────────────────────┘ ``` ### 常用指标参考 | 业务类型 | 核心指标 | 参考基准 | |----------|----------|----------| | 电商 | 转化率 | 2-5% | | SaaS | 月留存率 | 90%+ | | 内容 | 完播率/阅读完成率 | 30-50% | | APP | DAU/MAU 比 | 20-30% | | 社区 | 互动率 | 3-8% | --- > 📌 使用 `chart.sh` 各命令快速生成图表,配合本文最佳实践使用
Apache ORC columnar storage format reference. File structure with stripes and indexes, schema types with evolution rules, compression codecs (ZLIB/SNAPPY/ZST...
--- name: "orc" version: "1.0.0" description: "Apache ORC columnar storage format reference. File structure with stripes and indexes, schema types with evolution rules, compression codecs (ZLIB/SNAPPY/ZSTD), orc-tools CLI, Python/Java writer APIs, Hive ACID transactions, Spark integration, and performance tuning with bloom filters." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [orc, columnar, hadoop, hive, spark, data, analytics] category: "data" --- # Apache ORC Apache ORC columnar storage format reference. ## Commands | Command | Description | |---------|-------------| | `intro` | ORC overview, file structure, vs Parquet | | `schema` | Types, complex types, schema evolution | | `compression` | ZLIB/SNAPPY/LZO/ZSTD codecs, ratios | | `read` | orc-tools CLI, Python/Java read APIs | | `write` | Writer APIs, stripe/buffer sizing | | `hive` | Hive integration, ACID transactions | | `spark` | Spark ORC read/write, pushdown | | `performance` | Bloom filters, indexes, vectorized reads | FILE:scripts/script.sh #!/usr/bin/env bash # orc — Apache ORC columnar format reference # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="1.0.0" show_help() { cat << 'HELPEOF' orc v1.0.0 — Apache ORC Columnar Format Reference Usage: orc <command> Commands: intro ORC overview, Hive origin schema Types, evolution, nested compression ZLIB/SNAPPY/LZO/ZSTD read orc-tools, cat/meta/scan write Writer API, batch/stripe size hive Hive integration, ACID spark Spark ORC support performance Bloom filters, indexes, stats Powered by BytesAgain | bytesagain.com HELPEOF } cmd_intro() { cat << 'EOF' # Apache ORC — Optimized Row Columnar ## What is ORC? ORC (Optimized Row Columnar) is a columnar storage format for Hadoop workloads. Originally developed at Hortonworks for Apache Hive, it provides efficient compression and fast reads for analytical queries. ## Key Features - **Columnar storage**: Only reads needed columns - **Built-in indexes**: Min/max/sum per stripe and column - **Predicate pushdown**: Skip irrelevant data blocks - **ACID support**: Full transactional support in Hive - **Compression**: ZLIB, Snappy, LZO, ZSTD per-column - **Type evolution**: Add/remove/reorder columns safely - **Self-describing**: Schema embedded in file ## File Structure ``` ORC File ├── Header (magic: "ORC") ├── Stripe 1 (default ~64MB) │ ├── Index Data (min/max/bloom per column) │ ├── Row Data (columnar, compressed) │ └── Stripe Footer (encoding, stream info) ├── Stripe 2 │ ├── ... ├── Stripe N ├── File Footer (schema, stripe locations, stats) └── Postscript (compression, version) ``` ## ORC vs Parquet | Feature | ORC | Parquet | |---------|-----|---------| | Origin | Hive (Hortonworks) | Dremel (Cloudera/Twitter) | | Best for | Hive, Presto | Spark, cross-platform | | ACID | Yes | No | | Nested types | Good | Better | | Predicate pushdown | Excellent | Good | | Ecosystem | Hadoop-centric | Universal | | Index | Built-in | External | ## Install orc-tools ```bash # Java-based CLI tools wget https://dlcdn.apache.org/orc/orc-1.9.2/orc-tools-1.9.2-uber.jar alias orc-tools="java -jar orc-tools-1.9.2-uber.jar" ``` EOF } cmd_schema() { cat << 'EOF' # ORC Schema & Types ## Primitive Types | Type | Description | Example | |------|-------------|---------| | boolean | true/false | true | | tinyint | 8-bit integer | 127 | | smallint | 16-bit integer | 32767 | | int | 32-bit integer | 2147483647 | | bigint | 64-bit integer | 9223372036854775807 | | float | 32-bit IEEE 754 | 3.14 | | double | 64-bit IEEE 754 | 3.14159265 | | string | UTF-8 string | "hello" | | varchar(n) | Variable-length (max n) | "hello" | | char(n) | Fixed-length | "hello " | | binary | Byte array | 0xDEADBEEF | | timestamp | Date + time (nanosec) | 2026-03-24 10:30:00 | | date | Date only | 2026-03-24 | | decimal(p,s) | Arbitrary precision | 123.45 | ## Complex Types ``` struct<name:string, age:int> map<string, int> array<string> uniontype<int, string> ``` ## Schema in Hive ```sql CREATE TABLE events ( event_id BIGINT, event_time TIMESTAMP, user_id INT, event_type STRING, properties MAP<STRING, STRING>, tags ARRAY<STRING>, location STRUCT<lat:DOUBLE, lon:DOUBLE, city:STRING> ) STORED AS ORC; ``` ## Type Evolution ORC supports safe schema evolution: ``` ✅ Add columns (at the end) ✅ Remove columns (readers skip missing) ✅ Widen types (int → bigint, float → double) ❌ Rename columns (uses position, not name by default) ❌ Narrow types (bigint → int) ❌ Reorder columns (unless using column names) ``` ## Schema by Name ```sql -- Use column names instead of positions SET hive.orc.schema.resolution=name; ``` EOF } cmd_compression() { cat << 'EOF' # ORC Compression ## Compression Codecs | Codec | Ratio | Speed | CPU | Use Case | |-------|-------|-------|-----|----------| | NONE | 1x | Fastest | None | Already compressed data | | ZLIB | Best | Slow | High | Cold storage, archival | | SNAPPY | Good | Fast | Low | Hot data, interactive queries | | LZO | Good | Fast | Low | Similar to Snappy | | ZSTD | Excellent | Medium | Medium | Best balance (recommended) | | LZ4 | Moderate | Fastest | Lowest | Real-time analytics | ## Set in Hive ```sql -- Table level CREATE TABLE events (...) STORED AS ORC TBLPROPERTIES ("orc.compress"="ZSTD"); -- Session level SET hive.exec.orc.compression.strategy=SPEED; -- or COMPRESSION SET orc.compress=ZSTD; ``` ## Set in Spark ```python df.write.orc("path", compression="zstd") # Or in config spark.conf.set("spark.sql.orc.compression.codec", "zstd") ``` ## Compression Details - Compression is per-stream (each column stream compressed independently) - Integer columns use Run Length Encoding (RLE) before compression - String columns use dictionary encoding + RLE - Boolean columns use bitwise encoding - Buffer size default: 256KB (tunable) ## Typical Compression Ratios ``` Raw CSV: 1.0x (baseline) ORC + NONE: ~3x (columnar layout alone helps) ORC + Snappy: ~5x ORC + ZLIB: ~8x ORC + ZSTD: ~7x (close to ZLIB, much faster) ``` EOF } cmd_read() { cat << 'EOF' # Reading ORC Files ## orc-tools CLI ```bash # View file metadata orc-tools meta file.orc # Output: # File Version: 0.12 with ORC_14 # Rows: 1000000 # Compression: ZSTD # Type: struct<id:bigint,name:string,amount:decimal(10,2),ts:timestamp> # Stripe Statistics / File Statistics... # Read data (human-readable) orc-tools data file.orc # Read first N rows orc-tools data file.orc | head -100 # Scan (count rows, verify integrity) orc-tools scan file.orc # Convert ORC to JSON orc-tools convert file.orc # Convert ORC to CSV orc-tools data file.orc --format csv ``` ## Python (pyarrow) ```python import pyarrow.orc as orc # Read entire file table = orc.read_table('file.orc') df = table.to_pandas() # Read specific columns table = orc.read_table('file.orc', columns=['id', 'name']) # Read with filter (predicate pushdown) # Note: pyarrow ORC doesn't support pushdown directly # Use PyHive or PySpark for pushdown ``` ## Java API ```java import org.apache.orc.*; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; Configuration conf = new Configuration(); Reader reader = OrcFile.createReader(new Path("file.orc"), OrcFile.readerOptions(conf)); // Schema TypeDescription schema = reader.getSchema(); // Statistics ColumnStatistics[] stats = reader.getStatistics(); // Read rows RecordReader rows = reader.rows(); VectorizedRowBatch batch = reader.getSchema().createRowBatch(); while (rows.nextBatch(batch)) { // Process batch } ``` ## Predicate Pushdown ```sql -- Hive automatically pushes down predicates SELECT * FROM events WHERE event_date = '2026-03-24'; -- ORC skips stripes where min(event_date) > '2026-03-24' -- or max(event_date) < '2026-03-24' ``` EOF } cmd_write() { cat << 'EOF' # Writing ORC Files ## Python (pyarrow) ```python import pyarrow as pa import pyarrow.orc as orc # Create schema schema = pa.schema([ ('id', pa.int64()), ('name', pa.string()), ('amount', pa.decimal128(10, 2)), ('created_at', pa.timestamp('ms')), ]) # Create data table = pa.table({ 'id': [1, 2, 3], 'name': ['Alice', 'Bob', 'Charlie'], 'amount': [pa.scalar(100.50).cast(pa.decimal128(10,2)), pa.scalar(200.75).cast(pa.decimal128(10,2)), pa.scalar(300.00).cast(pa.decimal128(10,2))], 'created_at': [1711267200000, 1711353600000, 1711440000000], }, schema=schema) # Write ORC orc.write_table(table, 'output.orc', compression='zstd') ``` ## Java API ```java TypeDescription schema = TypeDescription.createStruct() .addField("id", TypeDescription.createLong()) .addField("name", TypeDescription.createString()) .addField("amount", TypeDescription.createDecimal()); Writer writer = OrcFile.createWriter(new Path("output.orc"), OrcFile.writerOptions(conf) .setSchema(schema) .compress(CompressionKind.ZSTD) .stripeSize(64 * 1024 * 1024) // 64MB stripes .bufferSize(256 * 1024) // 256KB compression buffer .rowIndexStride(10000)); // Index every 10K rows VectorizedRowBatch batch = schema.createRowBatch(); // ... fill batch ... writer.addRowBatch(batch); writer.close(); ``` ## Writer Tuning | Parameter | Default | Description | |-----------|---------|-------------| | stripe.size | 64MB | Rows per stripe | | buffer.size | 256KB | Compression buffer | | row.index.stride | 10000 | Rows per index entry | | compression | ZLIB | Compression codec | | bloom.filter.columns | none | Columns with bloom filters | ## Spark Write ```python df.write \ .mode("overwrite") \ .option("compression", "zstd") \ .option("orc.stripe.size", 67108864) \ .orc("hdfs:///data/events/") ``` EOF } cmd_hive() { cat << 'EOF' # ORC in Apache Hive ## Create ORC Table ```sql CREATE TABLE events ( event_id BIGINT, user_id INT, event_type STRING, properties MAP<STRING, STRING>, amount DECIMAL(10,2) ) PARTITIONED BY (event_date STRING) STORED AS ORC TBLPROPERTIES ( "orc.compress" = "ZSTD", "orc.stripe.size" = "67108864", "orc.create.index" = "true", "orc.bloom.filter.columns" = "user_id,event_type" ); ``` ## ACID Transactions ```sql -- Enable ACID SET hive.support.concurrency = true; SET hive.txn.manager = org.apache.hadoop.hive.ql.lockmgr.DbTxnManager; -- Create transactional table CREATE TABLE accounts ( account_id INT, balance DECIMAL(10,2) ) STORED AS ORC TBLPROPERTIES ("transactional"="true"); -- INSERT/UPDATE/DELETE INSERT INTO accounts VALUES (1, 1000.00); UPDATE accounts SET balance = balance - 100 WHERE account_id = 1; DELETE FROM accounts WHERE balance = 0; -- MERGE (upsert) MERGE INTO target USING source ON target.id = source.id WHEN MATCHED THEN UPDATE SET amount = source.amount WHEN NOT MATCHED THEN INSERT VALUES (source.id, source.amount); ``` ## Compaction ```sql -- ACID tables accumulate delta files -- Minor compaction: merge deltas ALTER TABLE accounts COMPACT 'minor'; -- Major compaction: rewrite all base + deltas ALTER TABLE accounts COMPACT 'major'; -- Check compaction status SHOW COMPACTIONS; ``` ## ORC Table Properties | Property | Default | Description | |----------|---------|-------------| | orc.compress | ZLIB | Compression codec | | orc.stripe.size | 67108864 | Stripe size bytes | | orc.row.index.stride | 10000 | Index stride | | orc.create.index | true | Create indexes | | orc.bloom.filter.columns | "" | Bloom filter columns | | orc.bloom.filter.fpp | 0.05 | False positive rate | EOF } cmd_spark() { cat << 'EOF' # ORC in Apache Spark ## Read ORC ```python # Read ORC file df = spark.read.orc("hdfs:///data/events/") # Read with schema from pyspark.sql.types import * schema = StructType([ StructField("id", LongType()), StructField("name", StringType()), StructField("amount", DecimalType(10, 2)), ]) df = spark.read.schema(schema).orc("path/to/orc/") # Read with predicate pushdown (automatic) df = spark.read.orc("events/").filter("event_date = '2026-03-24'") # Spark pushes filter to ORC reader → skips irrelevant stripes ``` ## Write ORC ```python # Write ORC df.write.orc("output/", mode="overwrite") # With partitioning df.write.partitionBy("year", "month").orc("output/") # With options df.write \ .option("compression", "zstd") \ .option("orc.stripe.size", 67108864) \ .option("orc.bloom.filter.columns", "user_id") \ .mode("overwrite") \ .orc("output/") ``` ## Spark SQL ```sql -- Create temp view from ORC CREATE TEMPORARY VIEW events USING orc OPTIONS (path "hdfs:///data/events/"); -- Query SELECT event_type, COUNT(*) FROM events WHERE event_date >= '2026-03-01' GROUP BY event_type; -- Save as ORC CREATE TABLE events_orc USING ORC PARTITIONED BY (event_date) AS SELECT * FROM events; ``` ## Schema Merge ```python # Read ORC files with different schemas df = spark.read.option("mergeSchema", "true").orc("path/") ``` ## Performance Config ```python spark.conf.set("spark.sql.orc.filterPushdown", "true") # Default true spark.conf.set("spark.sql.orc.enableVectorizedReader", "true") spark.conf.set("spark.sql.hive.convertMetastoreOrc", "true") ``` EOF } cmd_performance() { cat << 'EOF' # ORC Performance ## Bloom Filters Probabilistic data structure that quickly tells if a value is NOT in a column. ```sql -- Add bloom filter on high-cardinality columns CREATE TABLE events (...) STORED AS ORC TBLPROPERTIES ( "orc.bloom.filter.columns" = "user_id,session_id", "orc.bloom.filter.fpp" = "0.01" -- 1% false positive rate ); ``` When to use: - High cardinality columns (user_id, session_id) - Columns frequently used in WHERE equality filters - NOT for range queries or low cardinality ## Built-in Indexes ORC automatically stores per-stripe and per-row-group: - **Min/Max**: Skip stripes where value out of range - **Sum/Count**: Aggregate without reading data - **Has null**: Skip null checks ```sql -- Example: WHERE amount > 1000 -- ORC checks: if max(amount) in stripe < 1000 → skip entire stripe ``` ## File Statistics ```bash orc-tools meta file.orc # Shows per-column statistics: # Column 0 (id): min=1, max=1000000, hasNull=false # Column 1 (name): min="Aaron", max="Zara" # Column 2 (amount): min=0.01, max=99999.99, sum=45678901.23 ``` ## Stripe Sizing ``` Small stripes (16MB): + Faster predicate pushdown (more stripes to skip) - More overhead (more footers/indexes) - Less compression efficiency Large stripes (256MB): + Better compression ratio + Less overhead - Less granular predicate pushdown - More memory for read Recommended: 64MB (default) for most workloads ``` ## Vectorized Reading ORC supports vectorized (batch) reading — processes 1024 rows at a time instead of row-by-row. This enables: - CPU cache efficiency - SIMD operations - 10-100x faster than row-at-a-time ## Tips 1. Partition by date/region for coarse filtering 2. Sort data by frequently-filtered columns before writing 3. Use bloom filters on equality-filtered columns 4. Use ZSTD for best compression/speed balance 5. Keep stripe size at 64MB unless you have reason to change 6. Enable vectorized reader in your engine EOF } case "-help" in intro) cmd_intro ;; schema) cmd_schema ;; compression) cmd_compression ;; read) cmd_read ;; write) cmd_write ;; hive) cmd_hive ;; spark) cmd_spark ;; performance) cmd_performance ;; help|-h) show_help ;; version|-v) echo "orc v$VERSION" ;; *) echo "Unknown: $1"; show_help ;; esac
AIDE file integrity monitoring reference. Database initialization, integrity checks, update workflow, aide.conf configuration, selection rules, report parsin...
--- name: "aide" version: "1.0.0" description: "AIDE file integrity monitoring reference. Database initialization, integrity checks, update workflow, aide.conf configuration, selection rules, report parsing, and production deployment with CIS benchmark compliance." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [aide, integrity, ids, security, linux, compliance] category: "sysops" --- # AIDE Advanced Intrusion Detection Environment — file integrity monitoring reference. ## Commands | Command | Description | |---------|-------------| | `intro` | What is AIDE, how it works, vs Tripwire | | `init` | Initialize the baseline database | | `check` | Run integrity check, exit codes | | `update` | Update database after changes | | `config` | aide.conf configuration reference | | `rules` | Selection rules and attribute groups | | `reporting` | Report formats, email alerts, SIEM | | `deploy` | Production deployment best practices | FILE:scripts/script.sh #!/usr/bin/env bash # aide — Advanced Intrusion Detection Environment reference # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="1.0.0" show_help() { cat << 'HELPEOF' aide v1.0.0 — File Integrity Monitoring Reference Usage: aide <command> Commands: intro What is AIDE, how it works init Initialize the database check Run integrity check update Update database after changes config aide.conf configuration rules Selection rules and groups reporting Report formats and alerts deploy Production deployment guide Powered by BytesAgain | bytesagain.com HELPEOF } cmd_intro() { cat << 'EOF' # AIDE — Advanced Intrusion Detection Environment ## What is AIDE? AIDE is a file and directory integrity checker. It creates a database of file attributes (permissions, checksums, timestamps) and later compares the current state against this baseline to detect unauthorized changes. ## How It Works 1. **Initialize**: Scan filesystem, record attributes → database 2. **Check**: Compare current filesystem against stored database 3. **Update**: Accept legitimate changes, create new baseline ## Key Features - Monitors: permissions, ownership, size, mtime, ctime, inode, link count - Hash algorithms: md5, sha1, sha256, sha512, rmd160, tiger, crc32 - Extended attributes: SELinux contexts, POSIX ACLs - Regex-based file selection rules - No daemon required — runs from cron ## vs Tripwire | Feature | AIDE | Tripwire | |---------|------|---------| | License | GPL (free) | Commercial + OSS | | Config | Single file | Policy + config + keys | | Setup | Simpler | More complex | | Signing | No built-in | Cryptographic signing | ## Install ```bash # RHEL/CentOS yum install aide # Debian/Ubuntu apt install aide # Config location /etc/aide.conf # RHEL /etc/aide/aide.conf # Debian ``` EOF } cmd_init() { cat << 'EOF' # Initialize AIDE Database ## First-Time Setup ```bash # Generate initial database aide --init # Output goes to (RHEL default): /var/lib/aide/aide.db.new.gz # Move to active database mv /var/lib/aide/aide.db.new.gz /var/lib/aide/aide.db.gz ``` ## What Gets Recorded For each monitored file, AIDE stores: - Inode number - Permission bits - Owner (uid/gid) - Size in bytes - Modified time (mtime) - Changed time (ctime) - Number of hard links - Checksums (md5, sha256, etc.) - SELinux context (if enabled) - ACL entries (if enabled) ## Initialization Time - Small server (10K files): ~30 seconds - Medium server (100K files): ~5 minutes - Large server (1M+ files): 30+ minutes - Tip: exclude /tmp, /var/cache, /proc, /sys ## Verify Database ```bash # Check database exists and is readable file /var/lib/aide/aide.db.gz # aide.db.gz: gzip compressed data # Check entry count (decompress and count) zcat /var/lib/aide/aide.db.gz | grep -c "^/" ``` EOF } cmd_check() { cat << 'EOF' # Run AIDE Integrity Check ## Basic Check ```bash aide --check ``` ## Output Format ``` AIDE found differences between database and filesystem!! Summary: Total number of entries: 45678 Added entries: 3 Removed entries: 1 Changed entries: 7 --- Added entries: f+++++++++++++: /usr/local/bin/newscript Removed entries: f-----------: /tmp/oldfile Changed entries: File: /etc/passwd Size : 1842 | 1901 Mtime : 2026-03-20 | 2026-03-24 SHA256 : abc123... | def456... ``` ## Exit Codes | Code | Meaning | |------|---------| | 0 | No changes detected | | 1 | Added entries found | | 2 | Removed entries found | | 4 | Changed entries found | | 7 | Added + removed + changed | | 14 | Error writing report | | 15 | Invalid argument | Codes are bitmasks — can combine (e.g., 5 = added + changed) ## Verbose Output ```bash # Show all checked entries (very verbose) aide --check --verbose=255 # Limit to specific directory aide --check --limit /etc ``` ## Cron Check ```bash # /etc/cron.daily/aide-check #!/bin/bash /usr/sbin/aide --check | mail -s "AIDE Report $(hostname)" [email protected] ``` EOF } cmd_update() { cat << 'EOF' # Update AIDE Database ## After Legitimate Changes When you've made intentional system changes (installed packages, edited configs): ```bash # Generate new database incorporating current state aide --update # Review the changes reported # If all changes are expected, rotate the database: mv /var/lib/aide/aide.db.gz /var/lib/aide/aide.db.old.gz mv /var/lib/aide/aide.db.new.gz /var/lib/aide/aide.db.gz ``` ## Workflow 1. Make system changes (yum update, edit configs) 2. Run `aide --update` 3. Review changes — verify all are expected 4. If unexpected changes found → INVESTIGATE 5. If all OK → rotate database files ## Partial Update AIDE doesn't support partial updates. Each `--update` rebuilds the entire database. This is by design — ensures consistency. ## Automation Warning ⚠️ Never auto-rotate databases without human review! An attacker could make changes and then the auto-rotation would accept them as the new baseline. ## Best Practice ```bash # Keep dated backups cp /var/lib/aide/aide.db.gz /var/lib/aide/aide.db.$(date +%Y%m%d).gz # Rotate mv /var/lib/aide/aide.db.new.gz /var/lib/aide/aide.db.gz # Store offsite scp /var/lib/aide/aide.db.gz backup@remote:/aide-backups/ ``` EOF } cmd_config() { cat << 'EOF' # AIDE Configuration ## Config File Location ``` /etc/aide.conf # RHEL/CentOS /etc/aide/aide.conf # Debian/Ubuntu ``` ## Config Structure ```ini # Database locations @@define DBDIR /var/lib/aide database_in=file:@@{DBDIR}/aide.db.gz database_out=file:@@{DBDIR}/aide.db.new.gz database_new=file:@@{DBDIR}/aide.db.new.gz # What to check gzip_dbout=yes verbose=5 report_url=file:/var/log/aide/aide.log report_url=stdout # Hash algorithms ALLXTRAHASHES = sha1+rmd160+sha512+tiger # Predefined groups NORMAL = R+rmd160+sha256 DIR = p+i+n+u+g+acl+selinux+xattrs PERMS = p+u+g+acl+selinux+xattrs LOG = p+u+g+n+acl+selinux+ftype CONTENT = sha256+ftype DATAONLY = p+n+u+g+s+acl+selinux+xattrs+sha256 # Selection rules /boot/ NORMAL /bin/ NORMAL /sbin/ NORMAL /lib/ NORMAL /lib64/ NORMAL /opt/ NORMAL /usr/ NORMAL /etc/ PERMS # Exclusions !/etc/mtab$ !/var/log/.* !/var/spool/.* !/tmp/ !/proc/ !/sys/ !/dev/ !/run/ ``` ## Macros ```ini @@define VAR value # Define variable @@{VAR} # Use variable @@ifdef VAR # Conditional @@endif @@include /path/to/file # Include external config ``` EOF } cmd_rules() { cat << 'EOF' # AIDE Selection Rules ## Rule Format ``` /path/to/monitor GROUP !/path/to/exclude ``` ## Attribute Flags | Flag | Attribute | |------|-----------| | p | permissions | | i | inode number | | n | number of hard links | | u | user (uid) | | g | group (gid) | | s | size | | b | block count | | m | mtime | | a | atime | | c | ctime | | S | check for growing size | | md5 | MD5 checksum | | sha1 | SHA-1 checksum | | sha256 | SHA-256 checksum | | sha512 | SHA-512 checksum | | rmd160 | RIPEMD-160 | | tiger | Tiger checksum | | acl | POSIX ACL | | selinux | SELinux context | | xattrs | Extended attributes | | ftype | File type | ## Predefined Groups ```ini # R = p+i+n+u+g+s+m+c+md5+tiger (default read-only) # L = p+i+n+u+g (permissions only) # E = empty group # > = growing log file (size only grows) ``` ## Custom Groups ```ini # Critical binaries — full checksums CRITICAL = p+i+n+u+g+s+m+c+sha256+sha512 # Config files — permissions + content CONFIG = p+i+n+u+g+sha256 # Log files — growing, don't hash LOGS = p+u+g+n+S+ftype # Apply /usr/sbin/ CRITICAL /etc/ CONFIG /var/log/ LOGS ``` ## Regex Rules ```ini # Exclude backup files !/.*~$ !/.*\.bak$ !/.*\.swp$ # Monitor specific file types =/etc/.*\.conf$ CONFIG ``` EOF } cmd_reporting() { cat << 'EOF' # AIDE Reporting ## Report Configuration ```ini # In aide.conf report_url=file:/var/log/aide/aide.log report_url=stdout # Verbose levels (0-255) verbose=5 # Report attributes report_attributes=p+i+n+u+g+s+m+c+sha256 ``` ## Email Reports ```bash #!/bin/bash # /etc/cron.daily/aide-report SUBJECT="AIDE Report - $(hostname) - $(date +%Y-%m-%d)" MAILTO="[email protected]" LOGFILE="/var/log/aide/aide-$(date +%Y%m%d).log" aide --check > "$LOGFILE" 2>&1 EXIT=$? if [ $EXIT -ne 0 ]; then SUBJECT="⚠️ $SUBJECT — CHANGES DETECTED" fi mail -s "$SUBJECT" "$MAILTO" < "$LOGFILE" ``` ## Parse Report ```bash # Count changes grep "^Changed entries:" /var/log/aide/aide.log # List added files grep "^f+++++++++" /var/log/aide/aide.log # List removed files grep "^f----------" /var/log/aide/aide.log # List changed files awk '/^Changed entries:/,/^$/' /var/log/aide/aide.log ``` ## Integrate with Syslog ```bash # Send AIDE results to syslog aide --check 2>&1 | logger -t aide -p authpriv.notice ``` ## SIEM Integration ```bash # JSON output for log aggregators aide --check | python3 -c " import sys, json, re for line in sys.stdin: m = re.match(r'File: (.+)', line.strip()) if m: print(json.dumps({'tool':'aide','file':m.group(1),'event':'changed'})) " ``` EOF } cmd_deploy() { cat << 'EOF' # AIDE Production Deployment ## Step-by-Step ```bash # 1. Install yum install aide # RHEL apt install aide # Debian # 2. Customize config vi /etc/aide.conf # 3. Initialize database aide --init mv /var/lib/aide/aide.db.new.gz /var/lib/aide/aide.db.gz # 4. Set up cron echo '05 4 * * * root /usr/sbin/aide --check | mail -s "AIDE $(hostname)" [email protected]' \ >> /etc/crontab # 5. Protect database chmod 600 /var/lib/aide/aide.db.gz chattr +i /var/lib/aide/aide.db.gz # immutable flag # 6. Store offsite copy scp /var/lib/aide/aide.db.gz backup@secure-host:/aide/ ``` ## Best Practices 1. **Store database offsite** — if attacker has root, they can modify local DB 2. **Use strong hashes** — sha256 minimum, ideally sha512 3. **Exclude noisy paths** — /tmp, /var/cache, /proc, /sys, /run 4. **Review changes before rotating** — never auto-accept 5. **Run after maintenance** — update DB after planned changes 6. **Monitor the monitor** — alert if cron job stops running 7. **Baseline clean system** — init on a known-good state ## Common Pitfalls - Forgetting to rotate database after `yum update` - Monitoring /var/log (constant changes = noise) - Not excluding compiler/build directories - Running init on a compromised system - Using md5 alone (collision-vulnerable) ## CIS Benchmark CIS recommends AIDE for: - Section 1.3.1: Ensure AIDE is installed - Section 1.3.2: Ensure filesystem integrity is regularly checked EOF } case "-help" in intro) cmd_intro ;; init) cmd_init ;; check) cmd_check ;; update) cmd_update ;; config) cmd_config ;; rules) cmd_rules ;; reporting) cmd_reporting ;; deploy) cmd_deploy ;; help|-h) show_help ;; version|-v) echo "aide v$VERSION" ;; *) echo "Unknown: $1"; show_help ;; esac
Website submit page discovery and form analysis tool. Scout any website to find submission forms, detect authentication requirements, identify CAPTCHAs, and...
---
name: "seo-scout-pro"
version: "1.0.0"
description: "Website submit page discovery and form analysis tool. Scout any website to find submission forms, detect authentication requirements, identify CAPTCHAs, and map form fields for automated or manual submission. Essential for backlink building campaigns."
author: "BytesAgain"
homepage: "https://bytesagain.com"
source: "https://github.com/bytesagain/ai-skills"
tags: [seo, scout, forms, backlink, directory, submission, automation]
category: "marketing"
---
# SEO Scout Pro
Discover submit pages and analyze form structures on any website. Essential first step before backlink submission — know what you're dealing with before you submit.
## Commands
| Command | Description |
|---------|-------------|
| `scout-basic` | Quick scan for submit pages and forms |
| `scout-deep` | Follow links to find hidden submit pages |
| `form-analysis` | Detailed form field mapping |
| `auth-detect` | Detect login/OAuth/CAPTCHA requirements |
| `cloudflare-check` | Check Cloudflare protection level |
| `adapter-template` | Generate site adapter boilerplate |
| `anti-detect` | Browser stealth configuration guide |
| `manual-checklist` | Step-by-step manual submission checklist |
FILE:script.sh
#!/usr/bin/env bash
# seo-scout-pro — Website submit page discovery and form analysis
set -euo pipefail
VERSION="1.0.0"
show_help() {
cat << 'HELPEOF'
seo-scout-pro v1.0.0 — Submit Page Discovery & Form Analysis
Usage: seo-scout-pro <command>
Commands:
scout-basic Quick scan for submit pages
scout-deep Deep scan following links
form-analysis Detailed form field mapping
auth-detect Detect auth requirements
cloudflare-check Check Cloudflare protection
adapter-template Generate adapter boilerplate
anti-detect Browser stealth config guide
manual-checklist Manual submission checklist
Powered by BytesAgain | bytesagain.com
HELPEOF
}
cmd_scout_basic() {
cat << 'EOF'
# Basic Scout — Quick Submit Page Discovery
## Usage
```bash
node src/cli.js scout https://target-directory.com
```
## What It Does
1. Loads target URL in stealth browser
2. Scans page for submit-related links:
- /submit, /add, /new, /list-your, /get-listed
- /suggest, /contribute, /register
3. Identifies visible form elements
4. Reports field names, types, and placeholders
## Manual Scout (No Browser)
```bash
# Quick curl-based check
URL="https://target-directory.com"
# Find submit links
curl -sL -A "Mozilla/5.0" "$URL" | \
grep -oiP 'href="[^"]*(?:submit|add|new|list|suggest)[^"]*"' | \
sort -u
# Find forms
curl -sL -A "Mozilla/5.0" "$URL" | \
grep -oiP '<form[^>]*action="[^"]*"[^>]*>' | head -10
# Check for common submit paths
for path in /submit /add /new /list-your-tool /get-listed /suggest; do
CODE=$(curl -sL -o /dev/null -w "%{http_code}" -A "Mozilla/5.0" "URLpath")
[ "$CODE" != "404" ] && echo " Found: path → HTTP CODE"
done
```
## Output Example
```
🔍 Scouting https://example-directory.com
📋 Submit-related links found: 2
/submit-tool (200)
/add-your-app (200)
📝 Forms found: 1
Form 1: action="/api/submit" method="POST"
* [text] name (placeholder: "Tool name")
* [url] website (placeholder: "https://...")
* [textarea] description
* [email] contact_email
* [submit] Submit
🔐 Auth: No login required
🤖 CAPTCHA: None detected
```
EOF
}
cmd_scout_deep() {
cat << 'EOF'
# Deep Scout — Follow Links to Find Hidden Submit Pages
## Usage
```bash
node src/cli.js scout https://target-directory.com --deep
```
## Deep Scout Strategy
1. Load homepage
2. Extract all internal links
3. Filter for submit-related paths
4. Visit each candidate page
5. Analyze forms on each page
6. Report all discovered submission points
## Manual Deep Scout
```bash
URL="https://target-directory.com"
# Get all internal links
curl -sL -A "Mozilla/5.0" "$URL" | \
grep -oP 'href="/[^"]*"' | \
sed 's/href="//;s/"//' | \
sort -u > /tmp/links.txt
# Filter for submit-related
grep -iE 'submit|add|new|list|suggest|post|create|register' \
/tmp/links.txt > /tmp/submit-links.txt
echo "Found $(wc -l < /tmp/submit-links.txt) potential submit pages"
# Check each
while read path; do
FULL="URLpath"
CODE=$(curl -sL -o /dev/null -w "%{http_code}" -A "Mozilla/5.0" "$FULL")
FORMS=$(curl -sL -A "Mozilla/5.0" "$FULL" | grep -c '<form')
echo " path → HTTP CODE, FORMS forms"
done < /tmp/submit-links.txt
```
## Common Hidden Paths
- /submit-your-tool
- /add-new-listing
- /request-review
- /partner-with-us
- /list-your-product
- /get-featured
- /apply
- /nominate
EOF
}
cmd_form_analysis() {
cat << 'EOF'
# Form Field Analysis
## Extract All Form Fields
```bash
URL="https://target-directory.com/submit"
curl -sL -A "Mozilla/5.0" "$URL" | python3 -c "
import sys, re
html = sys.stdin.read()
# Find all input/textarea/select elements
inputs = re.findall(r'<(?:input|textarea|select)[^>]*>', html, re.I)
for i, inp in enumerate(inputs):
tag = 'input' if '<input' in inp.lower() else ('textarea' if '<textarea' in inp.lower() else 'select')
name = re.search(r'name=[\"']([^\"']+)', inp)
type_ = re.search(r'type=[\"']([^\"']+)', inp)
placeholder = re.search(r'placeholder=[\"']([^\"']+)', inp)
required = 'required' in inp.lower()
print(f' Field {i+1}:')
print(f' Tag: {tag}')
print(f' Name: {name.group(1) if name else \"(none)\"}')
print(f' Type: {type_.group(1) if type_ else \"text\"}')
print(f' Placeholder: {placeholder.group(1) if placeholder else \"(none)\"}')
print(f' Required: {required}')
print()
"
```
## Field Type Mapping
| Field Type | What to Fill |
|-----------|-------------|
| text (name/title) | Product name |
| url/website | Product URL (clean, no UTM) |
| email | Contact email |
| textarea (desc) | Short or long description |
| select (category) | Best matching category |
| select (pricing) | free / freemium / paid |
| file (logo) | Logo image upload |
| hidden (csrf) | Don't touch — auto-handled |
## React/Vue Forms (No Static HTML)
If form fields aren't in HTML source:
```javascript
// Use browser console or Playwright
const inputs = document.querySelectorAll('input, textarea, select');
inputs.forEach(el => {
console.log({
name: el.name,
type: el.type,
placeholder: el.placeholder,
id: el.id
});
});
```
EOF
}
cmd_auth_detect() {
cat << 'EOF'
# Authentication Detection
## Quick Auth Check
```bash
URL="https://target-directory.com/submit"
# Check for login redirects
FINAL=$(curl -sL -o /dev/null -w "%{url_effective}" -A "Mozilla/5.0" "$URL")
echo "Final URL: $FINAL"
# If redirected to /login or /auth → login required
# Check for OAuth buttons
curl -sL -A "Mozilla/5.0" "$URL" | \
grep -ioP '(google|github|twitter|facebook|oauth|sign.?in|log.?in)' | \
sort -u
```
## Auth Types & How to Handle
### No Auth (Best)
- Form is directly accessible
- Fill and submit immediately
- Examples: toolverto, submitaitools
### Email/Password Login
- Register account first
- Store credentials in config.yaml
- Login flow: fill email → fill password → click submit
- Handle: 2FA, email verification, CAPTCHA on login
- Examples: saashub, uneed
### Google OAuth
- "Sign in with Google" button
- First login: manual (2FA approval on phone)
- Subsequent: auto-select cached Google account
- Tip: do all OAuth sites in one browser session
- Examples: bai.tools
### GitHub OAuth
- Similar to Google OAuth
- Usually simpler (no 2FA after first approval)
### Magic Link (Email)
- Enter email → receive login link
- Cannot fully automate
- Semi-manual: enter email, click link in inbox
## CAPTCHA Detection
```bash
curl -sL -A "Mozilla/5.0" "$URL" | \
grep -ioP '(captcha|recaptcha|hcaptcha|turnstile|challenge)' | \
sort -u
```
| CAPTCHA Type | Automatable? |
|-------------|-------------|
| Color CAPTCHA | ✅ Text parsing |
| Simple math | ✅ Eval expression |
| reCAPTCHA v2 | ❌ Manual click |
| reCAPTCHA v3 | ⚠️ Sometimes passes |
| hCaptcha | ❌ Manual |
| Cloudflare Turnstile | ❌ Impossible |
EOF
}
cmd_cloudflare_check() {
cat << 'EOF'
# Cloudflare Protection Level Check
## Quick Check
```bash
URL="https://target-directory.com"
# Check response headers
curl -sI -A "Mozilla/5.0" "$URL" | grep -i "cf-\|cloudflare\|server:"
# Check with bare request (no User-Agent)
BARE=$(curl -s -o /dev/null -w "%{http_code}" "$URL")
UA=$(curl -s -o /dev/null -w "%{http_code}" -A "Mozilla/5.0" "$URL")
echo "Bare request: HTTP $BARE"
echo "With User-Agent: HTTP $UA"
```
## Protection Levels
### Level 0: No Cloudflare
- server: nginx/apache
- Direct access, easy to automate
### Level 1: Basic WAF (403 → 200 with UA)
- Bare request: 403
- With User-Agent: 200
- rebrowser-playwright: ✅ Works
### Level 2: Challenge Page
- Returns challenge HTML ("Checking your browser")
- Requires JavaScript execution
- rebrowser-playwright: ❌ Cannot solve
- Action: Mark as manual-only
### Level 3: Turnstile CAPTCHA
- Interactive challenge widget
- No known automation solution
- Action: Submit manually
## Decision Tree
```
Is site on Cloudflare?
├── No → Automate freely
└── Yes → What level?
├── Basic WAF → Use rebrowser ✅
├── Challenge → Manual only ❌
└── Turnstile → Manual only ❌
```
EOF
}
cmd_adapter_template() {
cat << 'EOF'
# Site Adapter Template
## After scouting a new site, create an adapter:
```javascript
// src/sites/newsite.js
import { withBrowser, delay, humanType } from '../browser.js';
export default {
// Metadata
name: 'newsite.com',
url: 'https://newsite.com/submit',
auth: 'none', // none | email | oauth
captcha: 'none', // none | color | recaptcha
reviewTime: '1-3 days',
backlinkType: 'dofollow',
async submit(product, config) {
return withBrowser(config, async ({ page }) => {
// 1. Navigate
console.log(' Loading submit page...');
await page.goto('https://newsite.com/submit', {
waitUntil: 'networkidle',
timeout: 30000,
});
await delay(2000);
// 2. Fill form (use field names from scout)
await page.fill('input[name="tool_name"]', product.name);
await delay(300);
await page.fill('input[name="tool_url"]', product.url);
await delay(300);
await page.fill('textarea[name="description"]',
product.long_description || product.description);
await delay(300);
await page.fill('input[name="email"]', product.email);
await delay(300);
// 3. Handle category dropdown (if exists)
try {
await page.selectOption('select[name="category"]',
{ label: 'Developer Tools' });
} catch (e) {}
// 4. Submit
await page.click('button[type="submit"]');
await delay(3000);
// 5. Check result
const body = await page.textContent('body');
const success = /thank|success|submitted|review/i.test(body);
return {
url: page.url(),
confirmation: success ? 'Submitted' : 'Check manually',
};
});
},
};
```
## Testing
```bash
# Dry run (just loads the page, no submit)
node src/cli.js scout https://newsite.com/submit
# Real submission
node src/cli.js submit newsite
```
EOF
}
cmd_anti_detect() {
cat << 'EOF'
# Browser Anti-Detection Configuration
## Stealth Browser Setup (rebrowser-playwright)
```javascript
import { chromium } from 'rebrowser-playwright';
const browser = await chromium.launch({
headless: true,
args: [
'--disable-blink-features=AutomationControlled',
'--no-sandbox',
'--disable-dev-shm-usage',
],
});
const context = await browser.newContext({
userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) ' +
'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
viewport: { width: 1440, height: 900 },
locale: 'en-US',
timezoneId: 'America/New_York',
});
```
## What rebrowser Patches
- navigator.webdriver → undefined ✅
- window.chrome → exists ✅
- Plugins array → populated ✅
- Languages → populated ✅
- WebDriver (legacy) → not detected ✅
## What Still Fails
- WebDriver (New) flag on sannysoft — 1 red item
- Cloudflare Challenge pages
- Reddit network-level blocking
- Sites checking datacenter IP ranges
## Human-Like Behavior
```javascript
// Random delays between actions
function delay(ms) {
const jitter = Math.random() * ms * 0.3;
return new Promise(r => setTimeout(r, ms + jitter));
}
// Character-by-character typing
async function humanType(page, selector, text) {
await page.click(selector);
await delay(200);
await page.fill(selector, '');
for (const char of text) {
await page.type(selector, char, {
delay: 30 + Math.random() * 70
});
}
}
```
## Why Not Regular Playwright?
Regular Playwright sets `navigator.webdriver = true`.
This is detected by ~70% of directory sites.
rebrowser patches this at the Chromium compilation level.
EOF
}
cmd_manual_checklist() {
cat << 'EOF'
# Manual Submission Checklist
Use this for sites that can't be automated (Cloudflare, complex forms).
## Before You Start
- [ ] Product name finalized
- [ ] One-line description ready (< 160 chars)
- [ ] Long description ready (2-3 paragraphs)
- [ ] Website URL live and working
- [ ] Contact email ready
- [ ] Logo image (if required, usually 200x200 PNG)
- [ ] Category determined (AI Tools / Developer Tools / etc.)
## Submission Steps
1. [ ] Visit the submit page
2. [ ] Create account if required
3. [ ] Fill product name
4. [ ] Paste website URL (clean, no UTM params)
5. [ ] Select best category
6. [ ] Paste short description
7. [ ] Paste long description (if field exists)
8. [ ] Upload logo (if field exists)
9. [ ] Enter contact email
10. [ ] Select pricing model (Free/Freemium/Paid)
11. [ ] Complete CAPTCHA (if any)
12. [ ] Click Submit
13. [ ] Screenshot confirmation page
14. [ ] Log submission date and expected review time
## After Submission
- [ ] Check email for confirmation/verification
- [ ] Set calendar reminder for expected review date
- [ ] After approval: verify listing is live
- [ ] After approval: check backlink with Ahrefs/Semrush
- [ ] Track referral traffic in Google Analytics
## UTM Tracking
When sites allow custom URLs, append tracking:
```
https://yoursite.com?utm_source=directoryname&utm_medium=directory&utm_campaign=backlink
```
EOF
}
case "-help" in
scout-basic) cmd_scout_basic ;;
scout-deep) cmd_scout_deep ;;
form-analysis) cmd_form_analysis ;;
auth-detect) cmd_auth_detect ;;
cloudflare-check) cmd_cloudflare_check ;;
adapter-template) cmd_adapter_template ;;
anti-detect) cmd_anti_detect ;;
manual-checklist) cmd_manual_checklist ;;
help|-h) show_help ;;
version|-v) echo "seo-scout-pro v$VERSION" ;;
*) echo "Unknown: $1"; show_help ;;
esac
Apparmor reference tool. Use when working with apparmor in sysops contexts.
--- name: "apparmor" version: "1.0.0" description: "Apparmor reference tool. Use when working with apparmor in sysops contexts." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [apparmor, sysops, dev, reference, cli] category: "sysops" --- # Apparmor Apparmor reference tool. Use when working with apparmor in sysops contexts. ## When to Use - Working with apparmor and need quick reference - Looking up sysops standards or best practices for apparmor - Troubleshooting apparmor issues - Need a checklist or guide for apparmor tasks ## Commands ### `intro` ```bash scripts/script.sh intro ``` Overview and core concepts ### `quickstart` ```bash scripts/script.sh quickstart ``` Getting started guide ### `patterns` ```bash scripts/script.sh patterns ``` Common patterns and best practices ### `debugging` ```bash scripts/script.sh debugging ``` Debugging and troubleshooting ### `performance` ```bash scripts/script.sh performance ``` Performance optimization tips ### `security` ```bash scripts/script.sh security ``` Security considerations ### `migration` ```bash scripts/script.sh migration ``` Migration and upgrade guide ### `cheatsheet` ```bash scripts/script.sh cheatsheet ``` Quick reference cheat sheet ### `help` ```bash scripts/script.sh help ``` ### `version` ```bash scripts/script.sh version ``` --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # apparmor — Apparmor reference tool. Use when working with apparmor in sysops contexts. # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="1.0.0" show_help() { cat << 'HELPEOF' apparmor v$VERSION — Apparmor Reference Tool Usage: apparmor <command> Commands: intro Overview and core concepts quickstart Getting started guide patterns Common patterns and best practices debugging Debugging and troubleshooting performance Performance optimization tips security Security considerations migration Migration and upgrade guide cheatsheet Quick reference cheat sheet help Show this help version Show version Powered by BytesAgain | bytesagain.com HELPEOF } cmd_intro() { cat << 'EOF' # Apparmor — Overview ## What is Apparmor? Apparmor (apparmor) is a specialized tool/concept in the sysops domain. It provides essential capabilities for professionals working with apparmor. ## Key Concepts - Core apparmor principles and fundamentals - How apparmor fits into the broader sysops ecosystem - Essential terminology every practitioner should know ## Why Apparmor Matters Understanding apparmor is critical for: - Improving efficiency in sysops workflows - Reducing errors and downtime - Meeting industry standards and compliance requirements - Enabling better decision-making with accurate data ## Getting Started 1. Understand the basic apparmor concepts 2. Learn the standard tools and interfaces 3. Practice with common scenarios 4. Review safety and compliance requirements EOF } cmd_quickstart() { cat << 'EOF' # Apparmor — Quick Start Guide ## Prerequisites - Basic understanding of sysops concepts - Required tools and access credentials - System meeting minimum requirements ## Installation 1. Download or clone the apparmor package 2. Install dependencies 3. Configure initial settings 4. Verify installation ## First Steps 1. Run the hello-world example 2. Review the default configuration 3. Try a simple real-world task 4. Explore available commands and options ## Next Steps - Read the full documentation - Join the community forum - Try advanced features - Set up automated workflows EOF } cmd_patterns() { cat << 'EOF' # Apparmor — Common Patterns & Best Practices ## Design Patterns 1. **Standard Pattern**: The most common approach for apparmor 2. **Scalable Pattern**: For high-volume or distributed scenarios 3. **Resilient Pattern**: For fault-tolerant implementations ## Best Practices - Follow the principle of least privilege - Use version control for all configurations - Implement comprehensive logging - Test changes in staging before production - Document all custom configurations ## Anti-Patterns to Avoid - Hardcoding credentials or configuration - Skipping validation and error handling - Ignoring monitoring and alerting - Making changes without documentation - Over-engineering simple solutions EOF } cmd_debugging() { cat << 'EOF' # Apparmor — Debugging Guide ## Common Errors 1. **Connection refused**: Check service status and network 2. **Permission denied**: Verify credentials and access rights 3. **Timeout**: Check network, increase limits, optimize queries 4. **Invalid input**: Validate data format and encoding ## Debugging Tools - Built-in logging and diagnostics - Network analysis tools (tcpdump, wireshark) - System monitoring (top, htop, iostat) - Application-specific debug modes ## Debug Workflow 1. Reproduce the issue consistently 2. Check logs for error messages 3. Isolate the failing component 4. Test with minimal configuration 5. Apply fix and verify EOF } cmd_performance() { cat << 'EOF' # Apparmor — Performance Optimization ## Key Metrics - Response time / latency - Throughput / operations per second - Resource utilization (CPU, memory, I/O) - Error rate and retry frequency ## Optimization Strategies 1. **Caching**: Reduce redundant operations 2. **Batching**: Group small operations 3. **Indexing**: Speed up data lookups 4. **Compression**: Reduce data transfer size 5. **Parallel Processing**: Utilize multiple cores ## Monitoring - Set up baseline performance metrics - Configure alerts for anomalies - Track trends over time - Regular capacity planning reviews EOF } cmd_security() { cat << 'EOF' # Apparmor — Security Considerations ## Authentication & Authorization - Use strong, unique credentials - Implement role-based access control - Enable multi-factor authentication where possible - Regularly review and rotate credentials ## Data Protection - Encrypt data at rest and in transit - Implement proper backup procedures - Follow data retention policies - Sanitize inputs to prevent injection ## Network Security - Use firewalls and network segmentation - Monitor for suspicious activity - Keep all software patched and updated - Disable unnecessary services and ports EOF } cmd_migration() { cat << 'EOF' # Apparmor — Migration & Upgrade Guide ## Pre-Migration Checklist - [ ] Current system fully documented - [ ] Complete backup taken and verified - [ ] Target environment prepared - [ ] Rollback plan documented - [ ] Stakeholders notified ## Migration Steps 1. Prepare target environment 2. Export data from source 3. Transform data if needed 4. Import to target 5. Verify data integrity 6. Update configurations 7. Test all functionality 8. Switch traffic / go live ## Post-Migration - Monitor for errors and performance - Verify all integrations working - Update documentation - Decommission old system after confirmation EOF } cmd_cheatsheet() { cat << 'EOF' # Apparmor — Quick Reference ## Essential Commands | Command | Description | |---------|-------------| | help | Show available commands | | version | Display version info | | intro | Overview and fundamentals | | troubleshooting | Common problems and fixes | ## Common Workflows 1. **Setup**: install → configure → verify → test 2. **Daily**: check → monitor → report → review 3. **Issue**: diagnose → isolate → fix → verify → document ## Key Shortcuts - Use tab completion for commands - Check logs first when troubleshooting - Always backup before making changes - Document everything you change EOF } CMD="-help" shift 2>/dev/null || true case "$CMD" in intro) cmd_intro "$@" ;; quickstart) cmd_quickstart "$@" ;; patterns) cmd_patterns "$@" ;; debugging) cmd_debugging "$@" ;; performance) cmd_performance "$@" ;; security) cmd_security "$@" ;; migration) cmd_migration "$@" ;; cheatsheet) cmd_cheatsheet "$@" ;; help|--help|-h) show_help ;; version|--version|-v) echo "apparmor v$VERSION — Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: apparmor help"; exit 1 ;; esac
Sandbox reference tool. Use when working with sandbox in sysops contexts.
--- name: "sandbox" version: "1.0.0" description: "Sandbox reference tool. Use when working with sandbox in sysops contexts." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [sandbox, sysops, dev, reference, cli] category: "sysops" --- # Sandbox Sandbox reference tool. Use when working with sandbox in sysops contexts. ## When to Use - Working with sandbox and need quick reference - Looking up sysops standards or best practices for sandbox - Troubleshooting sandbox issues - Need a checklist or guide for sandbox tasks ## Commands ### `intro` ```bash scripts/script.sh intro ``` Overview and core concepts ### `quickstart` ```bash scripts/script.sh quickstart ``` Getting started guide ### `patterns` ```bash scripts/script.sh patterns ``` Common patterns and best practices ### `debugging` ```bash scripts/script.sh debugging ``` Debugging and troubleshooting ### `performance` ```bash scripts/script.sh performance ``` Performance optimization tips ### `security` ```bash scripts/script.sh security ``` Security considerations ### `migration` ```bash scripts/script.sh migration ``` Migration and upgrade guide ### `cheatsheet` ```bash scripts/script.sh cheatsheet ``` Quick reference cheat sheet ### `help` ```bash scripts/script.sh help ``` ### `version` ```bash scripts/script.sh version ``` --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # sandbox — Sandbox reference tool. Use when working with sandbox in sysops contexts. # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="1.0.0" show_help() { cat << 'HELPEOF' sandbox v$VERSION — Sandbox Reference Tool Usage: sandbox <command> Commands: intro Overview and core concepts quickstart Getting started guide patterns Common patterns and best practices debugging Debugging and troubleshooting performance Performance optimization tips security Security considerations migration Migration and upgrade guide cheatsheet Quick reference cheat sheet help Show this help version Show version Powered by BytesAgain | bytesagain.com HELPEOF } cmd_intro() { cat << 'EOF' # Sandbox — Overview ## What is Sandbox? Sandbox (sandbox) is a specialized tool/concept in the sysops domain. It provides essential capabilities for professionals working with sandbox. ## Key Concepts - Core sandbox principles and fundamentals - How sandbox fits into the broader sysops ecosystem - Essential terminology every practitioner should know ## Why Sandbox Matters Understanding sandbox is critical for: - Improving efficiency in sysops workflows - Reducing errors and downtime - Meeting industry standards and compliance requirements - Enabling better decision-making with accurate data ## Getting Started 1. Understand the basic sandbox concepts 2. Learn the standard tools and interfaces 3. Practice with common scenarios 4. Review safety and compliance requirements EOF } cmd_quickstart() { cat << 'EOF' # Sandbox — Quick Start Guide ## Prerequisites - Basic understanding of sysops concepts - Required tools and access credentials - System meeting minimum requirements ## Installation 1. Download or clone the sandbox package 2. Install dependencies 3. Configure initial settings 4. Verify installation ## First Steps 1. Run the hello-world example 2. Review the default configuration 3. Try a simple real-world task 4. Explore available commands and options ## Next Steps - Read the full documentation - Join the community forum - Try advanced features - Set up automated workflows EOF } cmd_patterns() { cat << 'EOF' # Sandbox — Common Patterns & Best Practices ## Design Patterns 1. **Standard Pattern**: The most common approach for sandbox 2. **Scalable Pattern**: For high-volume or distributed scenarios 3. **Resilient Pattern**: For fault-tolerant implementations ## Best Practices - Follow the principle of least privilege - Use version control for all configurations - Implement comprehensive logging - Test changes in staging before production - Document all custom configurations ## Anti-Patterns to Avoid - Hardcoding credentials or configuration - Skipping validation and error handling - Ignoring monitoring and alerting - Making changes without documentation - Over-engineering simple solutions EOF } cmd_debugging() { cat << 'EOF' # Sandbox — Debugging Guide ## Common Errors 1. **Connection refused**: Check service status and network 2. **Permission denied**: Verify credentials and access rights 3. **Timeout**: Check network, increase limits, optimize queries 4. **Invalid input**: Validate data format and encoding ## Debugging Tools - Built-in logging and diagnostics - Network analysis tools (tcpdump, wireshark) - System monitoring (top, htop, iostat) - Application-specific debug modes ## Debug Workflow 1. Reproduce the issue consistently 2. Check logs for error messages 3. Isolate the failing component 4. Test with minimal configuration 5. Apply fix and verify EOF } cmd_performance() { cat << 'EOF' # Sandbox — Performance Optimization ## Key Metrics - Response time / latency - Throughput / operations per second - Resource utilization (CPU, memory, I/O) - Error rate and retry frequency ## Optimization Strategies 1. **Caching**: Reduce redundant operations 2. **Batching**: Group small operations 3. **Indexing**: Speed up data lookups 4. **Compression**: Reduce data transfer size 5. **Parallel Processing**: Utilize multiple cores ## Monitoring - Set up baseline performance metrics - Configure alerts for anomalies - Track trends over time - Regular capacity planning reviews EOF } cmd_security() { cat << 'EOF' # Sandbox — Security Considerations ## Authentication & Authorization - Use strong, unique credentials - Implement role-based access control - Enable multi-factor authentication where possible - Regularly review and rotate credentials ## Data Protection - Encrypt data at rest and in transit - Implement proper backup procedures - Follow data retention policies - Sanitize inputs to prevent injection ## Network Security - Use firewalls and network segmentation - Monitor for suspicious activity - Keep all software patched and updated - Disable unnecessary services and ports EOF } cmd_migration() { cat << 'EOF' # Sandbox — Migration & Upgrade Guide ## Pre-Migration Checklist - [ ] Current system fully documented - [ ] Complete backup taken and verified - [ ] Target environment prepared - [ ] Rollback plan documented - [ ] Stakeholders notified ## Migration Steps 1. Prepare target environment 2. Export data from source 3. Transform data if needed 4. Import to target 5. Verify data integrity 6. Update configurations 7. Test all functionality 8. Switch traffic / go live ## Post-Migration - Monitor for errors and performance - Verify all integrations working - Update documentation - Decommission old system after confirmation EOF } cmd_cheatsheet() { cat << 'EOF' # Sandbox — Quick Reference ## Essential Commands | Command | Description | |---------|-------------| | help | Show available commands | | version | Display version info | | intro | Overview and fundamentals | | troubleshooting | Common problems and fixes | ## Common Workflows 1. **Setup**: install → configure → verify → test 2. **Daily**: check → monitor → report → review 3. **Issue**: diagnose → isolate → fix → verify → document ## Key Shortcuts - Use tab completion for commands - Check logs first when troubleshooting - Always backup before making changes - Document everything you change EOF } CMD="-help" shift 2>/dev/null || true case "$CMD" in intro) cmd_intro "$@" ;; quickstart) cmd_quickstart "$@" ;; patterns) cmd_patterns "$@" ;; debugging) cmd_debugging "$@" ;; performance) cmd_performance "$@" ;; security) cmd_security "$@" ;; migration) cmd_migration "$@" ;; cheatsheet) cmd_cheatsheet "$@" ;; help|--help|-h) show_help ;; version|--version|-v) echo "sandbox v$VERSION — Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: sandbox help"; exit 1 ;; esac
Journald reference tool. Use when working with journald in sysops contexts.
--- name: "journald" version: "1.0.0" description: "Journald reference tool. Use when working with journald in sysops contexts." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [journald, sysops, dev, reference, cli] category: "sysops" --- # Journald Journald reference tool. Use when working with journald in sysops contexts. ## When to Use - Working with journald and need quick reference - Looking up sysops standards or best practices for journald - Troubleshooting journald issues - Need a checklist or guide for journald tasks ## Commands ### `intro` ```bash scripts/script.sh intro ``` Overview and core concepts ### `quickstart` ```bash scripts/script.sh quickstart ``` Getting started guide ### `patterns` ```bash scripts/script.sh patterns ``` Common patterns and best practices ### `debugging` ```bash scripts/script.sh debugging ``` Debugging and troubleshooting ### `performance` ```bash scripts/script.sh performance ``` Performance optimization tips ### `security` ```bash scripts/script.sh security ``` Security considerations ### `migration` ```bash scripts/script.sh migration ``` Migration and upgrade guide ### `cheatsheet` ```bash scripts/script.sh cheatsheet ``` Quick reference cheat sheet ### `help` ```bash scripts/script.sh help ``` ### `version` ```bash scripts/script.sh version ``` --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # journald — Journald reference tool. Use when working with journald in sysops contexts. # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="1.0.0" show_help() { cat << 'HELPEOF' journald v$VERSION — Journald Reference Tool Usage: journald <command> Commands: intro Overview and core concepts quickstart Getting started guide patterns Common patterns and best practices debugging Debugging and troubleshooting performance Performance optimization tips security Security considerations migration Migration and upgrade guide cheatsheet Quick reference cheat sheet help Show this help version Show version Powered by BytesAgain | bytesagain.com HELPEOF } cmd_intro() { cat << 'EOF' # Journald — Overview ## What is Journald? Journald (journald) is a specialized tool/concept in the sysops domain. It provides essential capabilities for professionals working with journald. ## Key Concepts - Core journald principles and fundamentals - How journald fits into the broader sysops ecosystem - Essential terminology every practitioner should know ## Why Journald Matters Understanding journald is critical for: - Improving efficiency in sysops workflows - Reducing errors and downtime - Meeting industry standards and compliance requirements - Enabling better decision-making with accurate data ## Getting Started 1. Understand the basic journald concepts 2. Learn the standard tools and interfaces 3. Practice with common scenarios 4. Review safety and compliance requirements EOF } cmd_quickstart() { cat << 'EOF' # Journald — Quick Start Guide ## Prerequisites - Basic understanding of sysops concepts - Required tools and access credentials - System meeting minimum requirements ## Installation 1. Download or clone the journald package 2. Install dependencies 3. Configure initial settings 4. Verify installation ## First Steps 1. Run the hello-world example 2. Review the default configuration 3. Try a simple real-world task 4. Explore available commands and options ## Next Steps - Read the full documentation - Join the community forum - Try advanced features - Set up automated workflows EOF } cmd_patterns() { cat << 'EOF' # Journald — Common Patterns & Best Practices ## Design Patterns 1. **Standard Pattern**: The most common approach for journald 2. **Scalable Pattern**: For high-volume or distributed scenarios 3. **Resilient Pattern**: For fault-tolerant implementations ## Best Practices - Follow the principle of least privilege - Use version control for all configurations - Implement comprehensive logging - Test changes in staging before production - Document all custom configurations ## Anti-Patterns to Avoid - Hardcoding credentials or configuration - Skipping validation and error handling - Ignoring monitoring and alerting - Making changes without documentation - Over-engineering simple solutions EOF } cmd_debugging() { cat << 'EOF' # Journald — Debugging Guide ## Common Errors 1. **Connection refused**: Check service status and network 2. **Permission denied**: Verify credentials and access rights 3. **Timeout**: Check network, increase limits, optimize queries 4. **Invalid input**: Validate data format and encoding ## Debugging Tools - Built-in logging and diagnostics - Network analysis tools (tcpdump, wireshark) - System monitoring (top, htop, iostat) - Application-specific debug modes ## Debug Workflow 1. Reproduce the issue consistently 2. Check logs for error messages 3. Isolate the failing component 4. Test with minimal configuration 5. Apply fix and verify EOF } cmd_performance() { cat << 'EOF' # Journald — Performance Optimization ## Key Metrics - Response time / latency - Throughput / operations per second - Resource utilization (CPU, memory, I/O) - Error rate and retry frequency ## Optimization Strategies 1. **Caching**: Reduce redundant operations 2. **Batching**: Group small operations 3. **Indexing**: Speed up data lookups 4. **Compression**: Reduce data transfer size 5. **Parallel Processing**: Utilize multiple cores ## Monitoring - Set up baseline performance metrics - Configure alerts for anomalies - Track trends over time - Regular capacity planning reviews EOF } cmd_security() { cat << 'EOF' # Journald — Security Considerations ## Authentication & Authorization - Use strong, unique credentials - Implement role-based access control - Enable multi-factor authentication where possible - Regularly review and rotate credentials ## Data Protection - Encrypt data at rest and in transit - Implement proper backup procedures - Follow data retention policies - Sanitize inputs to prevent injection ## Network Security - Use firewalls and network segmentation - Monitor for suspicious activity - Keep all software patched and updated - Disable unnecessary services and ports EOF } cmd_migration() { cat << 'EOF' # Journald — Migration & Upgrade Guide ## Pre-Migration Checklist - [ ] Current system fully documented - [ ] Complete backup taken and verified - [ ] Target environment prepared - [ ] Rollback plan documented - [ ] Stakeholders notified ## Migration Steps 1. Prepare target environment 2. Export data from source 3. Transform data if needed 4. Import to target 5. Verify data integrity 6. Update configurations 7. Test all functionality 8. Switch traffic / go live ## Post-Migration - Monitor for errors and performance - Verify all integrations working - Update documentation - Decommission old system after confirmation EOF } cmd_cheatsheet() { cat << 'EOF' # Journald — Quick Reference ## Essential Commands | Command | Description | |---------|-------------| | help | Show available commands | | version | Display version info | | intro | Overview and fundamentals | | troubleshooting | Common problems and fixes | ## Common Workflows 1. **Setup**: install → configure → verify → test 2. **Daily**: check → monitor → report → review 3. **Issue**: diagnose → isolate → fix → verify → document ## Key Shortcuts - Use tab completion for commands - Check logs first when troubleshooting - Always backup before making changes - Document everything you change EOF } CMD="-help" shift 2>/dev/null || true case "$CMD" in intro) cmd_intro "$@" ;; quickstart) cmd_quickstart "$@" ;; patterns) cmd_patterns "$@" ;; debugging) cmd_debugging "$@" ;; performance) cmd_performance "$@" ;; security) cmd_security "$@" ;; migration) cmd_migration "$@" ;; cheatsheet) cmd_cheatsheet "$@" ;; help|--help|-h) show_help ;; version|--version|-v) echo "journald v$VERSION — Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: journald help"; exit 1 ;; esac
Strace reference tool. Use when working with strace in devtools contexts.
--- name: "strace" version: "1.0.0" description: "Strace reference tool. Use when working with strace in devtools contexts." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [strace, devtools, dev, reference, cli] category: "devtools" --- # Strace Strace reference tool. Use when working with strace in devtools contexts. ## When to Use - Working with strace and need quick reference - Looking up devtools standards or best practices for strace - Troubleshooting strace issues - Need a checklist or guide for strace tasks ## Commands ### `intro` ```bash scripts/script.sh intro ``` Overview and core concepts ### `quickstart` ```bash scripts/script.sh quickstart ``` Getting started guide ### `patterns` ```bash scripts/script.sh patterns ``` Common patterns and best practices ### `debugging` ```bash scripts/script.sh debugging ``` Debugging and troubleshooting ### `performance` ```bash scripts/script.sh performance ``` Performance optimization tips ### `security` ```bash scripts/script.sh security ``` Security considerations ### `migration` ```bash scripts/script.sh migration ``` Migration and upgrade guide ### `cheatsheet` ```bash scripts/script.sh cheatsheet ``` Quick reference cheat sheet ### `help` ```bash scripts/script.sh help ``` ### `version` ```bash scripts/script.sh version ``` --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # strace — Strace reference tool. Use when working with strace in devtools contexts. # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="1.0.0" show_help() { cat << 'HELPEOF' strace v$VERSION — Strace Reference Tool Usage: strace <command> Commands: intro Overview and core concepts quickstart Getting started guide patterns Common patterns and best practices debugging Debugging and troubleshooting performance Performance optimization tips security Security considerations migration Migration and upgrade guide cheatsheet Quick reference cheat sheet help Show this help version Show version Powered by BytesAgain | bytesagain.com HELPEOF } cmd_intro() { cat << 'EOF' # Strace — Overview ## What is Strace? Strace (strace) is a specialized tool/concept in the devtools domain. It provides essential capabilities for professionals working with strace. ## Key Concepts - Core strace principles and fundamentals - How strace fits into the broader devtools ecosystem - Essential terminology every practitioner should know ## Why Strace Matters Understanding strace is critical for: - Improving efficiency in devtools workflows - Reducing errors and downtime - Meeting industry standards and compliance requirements - Enabling better decision-making with accurate data ## Getting Started 1. Understand the basic strace concepts 2. Learn the standard tools and interfaces 3. Practice with common scenarios 4. Review safety and compliance requirements EOF } cmd_quickstart() { cat << 'EOF' # Strace — Quick Start Guide ## Prerequisites - Basic understanding of devtools concepts - Required tools and access credentials - System meeting minimum requirements ## Installation 1. Download or clone the strace package 2. Install dependencies 3. Configure initial settings 4. Verify installation ## First Steps 1. Run the hello-world example 2. Review the default configuration 3. Try a simple real-world task 4. Explore available commands and options ## Next Steps - Read the full documentation - Join the community forum - Try advanced features - Set up automated workflows EOF } cmd_patterns() { cat << 'EOF' # Strace — Common Patterns & Best Practices ## Design Patterns 1. **Standard Pattern**: The most common approach for strace 2. **Scalable Pattern**: For high-volume or distributed scenarios 3. **Resilient Pattern**: For fault-tolerant implementations ## Best Practices - Follow the principle of least privilege - Use version control for all configurations - Implement comprehensive logging - Test changes in staging before production - Document all custom configurations ## Anti-Patterns to Avoid - Hardcoding credentials or configuration - Skipping validation and error handling - Ignoring monitoring and alerting - Making changes without documentation - Over-engineering simple solutions EOF } cmd_debugging() { cat << 'EOF' # Strace — Debugging Guide ## Common Errors 1. **Connection refused**: Check service status and network 2. **Permission denied**: Verify credentials and access rights 3. **Timeout**: Check network, increase limits, optimize queries 4. **Invalid input**: Validate data format and encoding ## Debugging Tools - Built-in logging and diagnostics - Network analysis tools (tcpdump, wireshark) - System monitoring (top, htop, iostat) - Application-specific debug modes ## Debug Workflow 1. Reproduce the issue consistently 2. Check logs for error messages 3. Isolate the failing component 4. Test with minimal configuration 5. Apply fix and verify EOF } cmd_performance() { cat << 'EOF' # Strace — Performance Optimization ## Key Metrics - Response time / latency - Throughput / operations per second - Resource utilization (CPU, memory, I/O) - Error rate and retry frequency ## Optimization Strategies 1. **Caching**: Reduce redundant operations 2. **Batching**: Group small operations 3. **Indexing**: Speed up data lookups 4. **Compression**: Reduce data transfer size 5. **Parallel Processing**: Utilize multiple cores ## Monitoring - Set up baseline performance metrics - Configure alerts for anomalies - Track trends over time - Regular capacity planning reviews EOF } cmd_security() { cat << 'EOF' # Strace — Security Considerations ## Authentication & Authorization - Use strong, unique credentials - Implement role-based access control - Enable multi-factor authentication where possible - Regularly review and rotate credentials ## Data Protection - Encrypt data at rest and in transit - Implement proper backup procedures - Follow data retention policies - Sanitize inputs to prevent injection ## Network Security - Use firewalls and network segmentation - Monitor for suspicious activity - Keep all software patched and updated - Disable unnecessary services and ports EOF } cmd_migration() { cat << 'EOF' # Strace — Migration & Upgrade Guide ## Pre-Migration Checklist - [ ] Current system fully documented - [ ] Complete backup taken and verified - [ ] Target environment prepared - [ ] Rollback plan documented - [ ] Stakeholders notified ## Migration Steps 1. Prepare target environment 2. Export data from source 3. Transform data if needed 4. Import to target 5. Verify data integrity 6. Update configurations 7. Test all functionality 8. Switch traffic / go live ## Post-Migration - Monitor for errors and performance - Verify all integrations working - Update documentation - Decommission old system after confirmation EOF } cmd_cheatsheet() { cat << 'EOF' # Strace — Quick Reference ## Essential Commands | Command | Description | |---------|-------------| | help | Show available commands | | version | Display version info | | intro | Overview and fundamentals | | troubleshooting | Common problems and fixes | ## Common Workflows 1. **Setup**: install → configure → verify → test 2. **Daily**: check → monitor → report → review 3. **Issue**: diagnose → isolate → fix → verify → document ## Key Shortcuts - Use tab completion for commands - Check logs first when troubleshooting - Always backup before making changes - Document everything you change EOF } CMD="-help" shift 2>/dev/null || true case "$CMD" in intro) cmd_intro "$@" ;; quickstart) cmd_quickstart "$@" ;; patterns) cmd_patterns "$@" ;; debugging) cmd_debugging "$@" ;; performance) cmd_performance "$@" ;; security) cmd_security "$@" ;; migration) cmd_migration "$@" ;; cheatsheet) cmd_cheatsheet "$@" ;; help|--help|-h) show_help ;; version|--version|-v) echo "strace v$VERSION — Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: strace help"; exit 1 ;; esac
Csp reference tool. Use when working with csp in devtools contexts.
--- name: "csp" version: "1.0.0" description: "Csp reference tool. Use when working with csp in devtools contexts." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [csp, devtools, dev, reference, cli] category: "devtools" --- # Csp Csp reference tool. Use when working with csp in devtools contexts. ## When to Use - Working with csp and need quick reference - Looking up devtools standards or best practices for csp - Troubleshooting csp issues - Need a checklist or guide for csp tasks ## Commands ### `intro` ```bash scripts/script.sh intro ``` Overview and core concepts ### `quickstart` ```bash scripts/script.sh quickstart ``` Getting started guide ### `patterns` ```bash scripts/script.sh patterns ``` Common patterns and best practices ### `debugging` ```bash scripts/script.sh debugging ``` Debugging and troubleshooting ### `performance` ```bash scripts/script.sh performance ``` Performance optimization tips ### `security` ```bash scripts/script.sh security ``` Security considerations ### `migration` ```bash scripts/script.sh migration ``` Migration and upgrade guide ### `cheatsheet` ```bash scripts/script.sh cheatsheet ``` Quick reference cheat sheet ### `help` ```bash scripts/script.sh help ``` ### `version` ```bash scripts/script.sh version ``` --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # csp — Csp reference tool. Use when working with csp in devtools contexts. # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="1.0.0" show_help() { cat << 'HELPEOF' csp v$VERSION — Csp Reference Tool Usage: csp <command> Commands: intro Overview and core concepts quickstart Getting started guide patterns Common patterns and best practices debugging Debugging and troubleshooting performance Performance optimization tips security Security considerations migration Migration and upgrade guide cheatsheet Quick reference cheat sheet help Show this help version Show version Powered by BytesAgain | bytesagain.com HELPEOF } cmd_intro() { cat << 'EOF' # Csp — Overview ## What is Csp? Csp (csp) is a specialized tool/concept in the devtools domain. It provides essential capabilities for professionals working with csp. ## Key Concepts - Core csp principles and fundamentals - How csp fits into the broader devtools ecosystem - Essential terminology every practitioner should know ## Why Csp Matters Understanding csp is critical for: - Improving efficiency in devtools workflows - Reducing errors and downtime - Meeting industry standards and compliance requirements - Enabling better decision-making with accurate data ## Getting Started 1. Understand the basic csp concepts 2. Learn the standard tools and interfaces 3. Practice with common scenarios 4. Review safety and compliance requirements EOF } cmd_quickstart() { cat << 'EOF' # Csp — Quick Start Guide ## Prerequisites - Basic understanding of devtools concepts - Required tools and access credentials - System meeting minimum requirements ## Installation 1. Download or clone the csp package 2. Install dependencies 3. Configure initial settings 4. Verify installation ## First Steps 1. Run the hello-world example 2. Review the default configuration 3. Try a simple real-world task 4. Explore available commands and options ## Next Steps - Read the full documentation - Join the community forum - Try advanced features - Set up automated workflows EOF } cmd_patterns() { cat << 'EOF' # Csp — Common Patterns & Best Practices ## Design Patterns 1. **Standard Pattern**: The most common approach for csp 2. **Scalable Pattern**: For high-volume or distributed scenarios 3. **Resilient Pattern**: For fault-tolerant implementations ## Best Practices - Follow the principle of least privilege - Use version control for all configurations - Implement comprehensive logging - Test changes in staging before production - Document all custom configurations ## Anti-Patterns to Avoid - Hardcoding credentials or configuration - Skipping validation and error handling - Ignoring monitoring and alerting - Making changes without documentation - Over-engineering simple solutions EOF } cmd_debugging() { cat << 'EOF' # Csp — Debugging Guide ## Common Errors 1. **Connection refused**: Check service status and network 2. **Permission denied**: Verify credentials and access rights 3. **Timeout**: Check network, increase limits, optimize queries 4. **Invalid input**: Validate data format and encoding ## Debugging Tools - Built-in logging and diagnostics - Network analysis tools (tcpdump, wireshark) - System monitoring (top, htop, iostat) - Application-specific debug modes ## Debug Workflow 1. Reproduce the issue consistently 2. Check logs for error messages 3. Isolate the failing component 4. Test with minimal configuration 5. Apply fix and verify EOF } cmd_performance() { cat << 'EOF' # Csp — Performance Optimization ## Key Metrics - Response time / latency - Throughput / operations per second - Resource utilization (CPU, memory, I/O) - Error rate and retry frequency ## Optimization Strategies 1. **Caching**: Reduce redundant operations 2. **Batching**: Group small operations 3. **Indexing**: Speed up data lookups 4. **Compression**: Reduce data transfer size 5. **Parallel Processing**: Utilize multiple cores ## Monitoring - Set up baseline performance metrics - Configure alerts for anomalies - Track trends over time - Regular capacity planning reviews EOF } cmd_security() { cat << 'EOF' # Csp — Security Considerations ## Authentication & Authorization - Use strong, unique credentials - Implement role-based access control - Enable multi-factor authentication where possible - Regularly review and rotate credentials ## Data Protection - Encrypt data at rest and in transit - Implement proper backup procedures - Follow data retention policies - Sanitize inputs to prevent injection ## Network Security - Use firewalls and network segmentation - Monitor for suspicious activity - Keep all software patched and updated - Disable unnecessary services and ports EOF } cmd_migration() { cat << 'EOF' # Csp — Migration & Upgrade Guide ## Pre-Migration Checklist - [ ] Current system fully documented - [ ] Complete backup taken and verified - [ ] Target environment prepared - [ ] Rollback plan documented - [ ] Stakeholders notified ## Migration Steps 1. Prepare target environment 2. Export data from source 3. Transform data if needed 4. Import to target 5. Verify data integrity 6. Update configurations 7. Test all functionality 8. Switch traffic / go live ## Post-Migration - Monitor for errors and performance - Verify all integrations working - Update documentation - Decommission old system after confirmation EOF } cmd_cheatsheet() { cat << 'EOF' # Csp — Quick Reference ## Essential Commands | Command | Description | |---------|-------------| | help | Show available commands | | version | Display version info | | intro | Overview and fundamentals | | troubleshooting | Common problems and fixes | ## Common Workflows 1. **Setup**: install → configure → verify → test 2. **Daily**: check → monitor → report → review 3. **Issue**: diagnose → isolate → fix → verify → document ## Key Shortcuts - Use tab completion for commands - Check logs first when troubleshooting - Always backup before making changes - Document everything you change EOF } CMD="-help" shift 2>/dev/null || true case "$CMD" in intro) cmd_intro "$@" ;; quickstart) cmd_quickstart "$@" ;; patterns) cmd_patterns "$@" ;; debugging) cmd_debugging "$@" ;; performance) cmd_performance "$@" ;; security) cmd_security "$@" ;; migration) cmd_migration "$@" ;; cheatsheet) cmd_cheatsheet "$@" ;; help|--help|-h) show_help ;; version|--version|-v) echo "csp v$VERSION — Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: csp help"; exit 1 ;; esac
Irr reference tool. Use when working with irr in finance contexts.
--- name: "irr" version: "1.0.0" description: "Irr reference tool. Use when working with irr in finance contexts." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [irr, finance, finance, reference, cli] category: "finance" --- # Irr Irr reference tool. Use when working with irr in finance contexts. ## When to Use - Working with irr and need quick reference - Looking up finance standards or best practices for irr - Troubleshooting irr issues - Need a checklist or guide for irr tasks ## Commands ### `intro` ```bash scripts/script.sh intro ``` Overview and fundamentals ### `formulas` ```bash scripts/script.sh formulas ``` Key formulas and calculations ### `regulations` ```bash scripts/script.sh regulations ``` Regulatory framework and compliance ### `risks` ```bash scripts/script.sh risks ``` Risk factors and mitigation ### `instruments` ```bash scripts/script.sh instruments ``` Instruments and tools overview ### `strategies` ```bash scripts/script.sh strategies ``` Common strategies and approaches ### `glossary` ```bash scripts/script.sh glossary ``` Key terms and definitions ### `checklist` ```bash scripts/script.sh checklist ``` Due diligence checklist ### `help` ```bash scripts/script.sh help ``` ### `version` ```bash scripts/script.sh version ``` --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # irr — Irr reference tool. Use when working with irr in finance contexts. # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="1.0.0" show_help() { cat << 'HELPEOF' irr v$VERSION — Irr Reference Tool Usage: irr <command> Commands: intro Overview and fundamentals formulas Key formulas and calculations regulations Regulatory framework and compliance risks Risk factors and mitigation instruments Instruments and tools overview strategies Common strategies and approaches glossary Key terms and definitions checklist Due diligence checklist help Show this help version Show version Powered by BytesAgain | bytesagain.com HELPEOF } cmd_intro() { cat << 'EOF' # Irr — Overview ## What is Irr? Irr (irr) is a specialized tool/concept in the finance domain. It provides essential capabilities for professionals working with irr. ## Key Concepts - Core irr principles and fundamentals - How irr fits into the broader finance ecosystem - Essential terminology every practitioner should know ## Why Irr Matters Understanding irr is critical for: - Improving efficiency in finance workflows - Reducing errors and downtime - Meeting industry standards and compliance requirements - Enabling better decision-making with accurate data ## Getting Started 1. Understand the basic irr concepts 2. Learn the standard tools and interfaces 3. Practice with common scenarios 4. Review safety and compliance requirements EOF } cmd_formulas() { cat << 'EOF' # Irr — Key Formulas & Calculations ## Core Formulas - **Basic ratio**: Value = Input / Reference × 100 - **Growth rate**: (Current - Previous) / Previous × 100% - **Weighted average**: Sum(Value × Weight) / Sum(Weight) ## Common Calculations 1. Risk-adjusted return 2. Break-even analysis 3. Compound growth 4. Present/future value 5. Standard deviation ## Quick Reference | Metric | Formula | Use Case | |--------|---------|----------| | ROI | (Gain - Cost) / Cost | Investment evaluation | | CAGR | (End/Start)^(1/n) - 1 | Growth measurement | | Sharpe | (Return - RiskFree) / StdDev | Risk-adjusted performance | EOF } cmd_regulations() { cat << 'EOF' # Irr — Regulatory Framework ## Key Regulations - Primary governing laws and statutes - Industry-specific compliance requirements - International standards and agreements ## Compliance Requirements - Registration and licensing - Reporting obligations - Record-keeping requirements - Audit and inspection readiness ## Enforcement - Regulatory bodies and their jurisdiction - Penalty structures for non-compliance - Appeal and dispute resolution processes EOF } cmd_risks() { cat << 'EOF' # Irr — Risk Analysis ## Risk Categories 1. **Market Risk**: Price volatility and liquidity 2. **Operational Risk**: System failures and human error 3. **Regulatory Risk**: Changing laws and compliance 4. **Credit Risk**: Counterparty default ## Risk Mitigation - Diversification strategies - Hedging instruments - Insurance and guarantees - Contingency planning ## Risk Assessment Framework | Risk | Probability | Impact | Mitigation | |------|-------------|--------|------------| | High | Likely | Severe | Immediate action | | Medium | Possible | Moderate | Monitor closely | | Low | Unlikely | Minor | Accept or transfer | EOF } cmd_instruments() { cat << 'EOF' # Irr — Instruments & Tools Overview ## Primary Instruments - Core tools used in irr operations - Measurement and monitoring equipment - Software platforms and applications ## Selection Guide 1. Define requirements and constraints 2. Evaluate available options 3. Consider total cost of ownership 4. Assess vendor support and community 5. Test before committing EOF } cmd_strategies() { cat << 'EOF' # Irr — Common Strategies ## Fundamental Strategies 1. **Conservative**: Low risk, steady returns 2. **Balanced**: Moderate risk, diversified approach 3. **Aggressive**: Higher risk, growth-focused ## Implementation Steps 1. Define objectives and constraints 2. Select appropriate strategy 3. Execute with discipline 4. Monitor and adjust 5. Review periodically EOF } cmd_glossary() { cat << 'EOF' # Irr — Key Terms & Definitions ## Core Terminology - **Irr**: The primary subject of this reference - **finance**: The broader domain category - **Baseline**: A reference point for comparison - **Benchmark**: A standard for measuring performance - **Compliance**: Adherence to rules and standards - **Configuration**: System settings and parameters - **Diagnostics**: Tools and procedures for identifying issues - **Integration**: Connecting multiple systems together - **Protocol**: A set of rules governing communication - **Specification**: Detailed requirements document EOF } cmd_checklist() { cat << 'EOF' # Irr — Inspection Checklist ## Pre-Operation Checklist - [ ] Visual inspection completed - [ ] All connections secure - [ ] Safety systems functional - [ ] Operating parameters within range - [ ] Documentation current ## Daily Checks - [ ] System startup normal - [ ] No error indicators or alarms - [ ] Performance within expected range - [ ] Environmental conditions acceptable - [ ] Log entries reviewed ## Periodic Inspection - [ ] Comprehensive system test - [ ] Calibration verification - [ ] Wear component inspection - [ ] Firmware/software version check - [ ] Backup systems tested ## Shutdown Checklist - [ ] Proper shutdown sequence followed - [ ] All data saved and backed up - [ ] System secured - [ ] Maintenance items logged - [ ] Next startup requirements noted EOF } CMD="-help" shift 2>/dev/null || true case "$CMD" in intro) cmd_intro "$@" ;; formulas) cmd_formulas "$@" ;; regulations) cmd_regulations "$@" ;; risks) cmd_risks "$@" ;; instruments) cmd_instruments "$@" ;; strategies) cmd_strategies "$@" ;; glossary) cmd_glossary "$@" ;; checklist) cmd_checklist "$@" ;; help|--help|-h) show_help ;; version|--version|-v) echo "irr v$VERSION — Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: irr help"; exit 1 ;; esac
Black Scholes reference tool. Use when working with black scholes in finance contexts.
--- name: "black-scholes" version: "1.0.0" description: "Black Scholes reference tool. Use when working with black scholes in finance contexts." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [black-scholes, finance, finance, reference, cli] category: "finance" --- # Black Scholes Black Scholes reference tool. Use when working with black scholes in finance contexts. ## When to Use - Working with black scholes and need quick reference - Looking up finance standards or best practices for black scholes - Troubleshooting black scholes issues - Need a checklist or guide for black scholes tasks ## Commands ### `intro` ```bash scripts/script.sh intro ``` Overview and fundamentals ### `formulas` ```bash scripts/script.sh formulas ``` Key formulas and calculations ### `regulations` ```bash scripts/script.sh regulations ``` Regulatory framework and compliance ### `risks` ```bash scripts/script.sh risks ``` Risk factors and mitigation ### `instruments` ```bash scripts/script.sh instruments ``` Instruments and tools overview ### `strategies` ```bash scripts/script.sh strategies ``` Common strategies and approaches ### `glossary` ```bash scripts/script.sh glossary ``` Key terms and definitions ### `checklist` ```bash scripts/script.sh checklist ``` Due diligence checklist ### `help` ```bash scripts/script.sh help ``` ### `version` ```bash scripts/script.sh version ``` --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # black-scholes — Black Scholes reference tool. Use when working with black scholes in finance contexts. # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="1.0.0" show_help() { cat << 'HELPEOF' black-scholes v$VERSION — Black Scholes Reference Tool Usage: black-scholes <command> Commands: intro Overview and fundamentals formulas Key formulas and calculations regulations Regulatory framework and compliance risks Risk factors and mitigation instruments Instruments and tools overview strategies Common strategies and approaches glossary Key terms and definitions checklist Due diligence checklist help Show this help version Show version Powered by BytesAgain | bytesagain.com HELPEOF } cmd_intro() { cat << 'EOF' # Black Scholes — Overview ## What is Black Scholes? Black Scholes (black-scholes) is a specialized tool/concept in the finance domain. It provides essential capabilities for professionals working with black scholes. ## Key Concepts - Core black scholes principles and fundamentals - How black scholes fits into the broader finance ecosystem - Essential terminology every practitioner should know ## Why Black Scholes Matters Understanding black scholes is critical for: - Improving efficiency in finance workflows - Reducing errors and downtime - Meeting industry standards and compliance requirements - Enabling better decision-making with accurate data ## Getting Started 1. Understand the basic black scholes concepts 2. Learn the standard tools and interfaces 3. Practice with common scenarios 4. Review safety and compliance requirements EOF } cmd_formulas() { cat << 'EOF' # Black Scholes — Key Formulas & Calculations ## Core Formulas - **Basic ratio**: Value = Input / Reference × 100 - **Growth rate**: (Current - Previous) / Previous × 100% - **Weighted average**: Sum(Value × Weight) / Sum(Weight) ## Common Calculations 1. Risk-adjusted return 2. Break-even analysis 3. Compound growth 4. Present/future value 5. Standard deviation ## Quick Reference | Metric | Formula | Use Case | |--------|---------|----------| | ROI | (Gain - Cost) / Cost | Investment evaluation | | CAGR | (End/Start)^(1/n) - 1 | Growth measurement | | Sharpe | (Return - RiskFree) / StdDev | Risk-adjusted performance | EOF } cmd_regulations() { cat << 'EOF' # Black Scholes — Regulatory Framework ## Key Regulations - Primary governing laws and statutes - Industry-specific compliance requirements - International standards and agreements ## Compliance Requirements - Registration and licensing - Reporting obligations - Record-keeping requirements - Audit and inspection readiness ## Enforcement - Regulatory bodies and their jurisdiction - Penalty structures for non-compliance - Appeal and dispute resolution processes EOF } cmd_risks() { cat << 'EOF' # Black Scholes — Risk Analysis ## Risk Categories 1. **Market Risk**: Price volatility and liquidity 2. **Operational Risk**: System failures and human error 3. **Regulatory Risk**: Changing laws and compliance 4. **Credit Risk**: Counterparty default ## Risk Mitigation - Diversification strategies - Hedging instruments - Insurance and guarantees - Contingency planning ## Risk Assessment Framework | Risk | Probability | Impact | Mitigation | |------|-------------|--------|------------| | High | Likely | Severe | Immediate action | | Medium | Possible | Moderate | Monitor closely | | Low | Unlikely | Minor | Accept or transfer | EOF } cmd_instruments() { cat << 'EOF' # Black Scholes — Instruments & Tools Overview ## Primary Instruments - Core tools used in black scholes operations - Measurement and monitoring equipment - Software platforms and applications ## Selection Guide 1. Define requirements and constraints 2. Evaluate available options 3. Consider total cost of ownership 4. Assess vendor support and community 5. Test before committing EOF } cmd_strategies() { cat << 'EOF' # Black Scholes — Common Strategies ## Fundamental Strategies 1. **Conservative**: Low risk, steady returns 2. **Balanced**: Moderate risk, diversified approach 3. **Aggressive**: Higher risk, growth-focused ## Implementation Steps 1. Define objectives and constraints 2. Select appropriate strategy 3. Execute with discipline 4. Monitor and adjust 5. Review periodically EOF } cmd_glossary() { cat << 'EOF' # Black Scholes — Key Terms & Definitions ## Core Terminology - **Black Scholes**: The primary subject of this reference - **finance**: The broader domain category - **Baseline**: A reference point for comparison - **Benchmark**: A standard for measuring performance - **Compliance**: Adherence to rules and standards - **Configuration**: System settings and parameters - **Diagnostics**: Tools and procedures for identifying issues - **Integration**: Connecting multiple systems together - **Protocol**: A set of rules governing communication - **Specification**: Detailed requirements document EOF } cmd_checklist() { cat << 'EOF' # Black Scholes — Inspection Checklist ## Pre-Operation Checklist - [ ] Visual inspection completed - [ ] All connections secure - [ ] Safety systems functional - [ ] Operating parameters within range - [ ] Documentation current ## Daily Checks - [ ] System startup normal - [ ] No error indicators or alarms - [ ] Performance within expected range - [ ] Environmental conditions acceptable - [ ] Log entries reviewed ## Periodic Inspection - [ ] Comprehensive system test - [ ] Calibration verification - [ ] Wear component inspection - [ ] Firmware/software version check - [ ] Backup systems tested ## Shutdown Checklist - [ ] Proper shutdown sequence followed - [ ] All data saved and backed up - [ ] System secured - [ ] Maintenance items logged - [ ] Next startup requirements noted EOF } CMD="-help" shift 2>/dev/null || true case "$CMD" in intro) cmd_intro "$@" ;; formulas) cmd_formulas "$@" ;; regulations) cmd_regulations "$@" ;; risks) cmd_risks "$@" ;; instruments) cmd_instruments "$@" ;; strategies) cmd_strategies "$@" ;; glossary) cmd_glossary "$@" ;; checklist) cmd_checklist "$@" ;; help|--help|-h) show_help ;; version|--version|-v) echo "black-scholes v$VERSION — Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: black-scholes help"; exit 1 ;; esac
Delta reference tool. Use when working with delta in finance contexts.
--- name: "delta" version: "1.0.0" description: "Delta reference tool. Use when working with delta in finance contexts." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [delta, finance, finance, reference, cli] category: "finance" --- # Delta Delta reference tool. Use when working with delta in finance contexts. ## When to Use - Working with delta and need quick reference - Looking up finance standards or best practices for delta - Troubleshooting delta issues - Need a checklist or guide for delta tasks ## Commands ### `intro` ```bash scripts/script.sh intro ``` Overview and fundamentals ### `formulas` ```bash scripts/script.sh formulas ``` Key formulas and calculations ### `regulations` ```bash scripts/script.sh regulations ``` Regulatory framework and compliance ### `risks` ```bash scripts/script.sh risks ``` Risk factors and mitigation ### `instruments` ```bash scripts/script.sh instruments ``` Instruments and tools overview ### `strategies` ```bash scripts/script.sh strategies ``` Common strategies and approaches ### `glossary` ```bash scripts/script.sh glossary ``` Key terms and definitions ### `checklist` ```bash scripts/script.sh checklist ``` Due diligence checklist ### `help` ```bash scripts/script.sh help ``` ### `version` ```bash scripts/script.sh version ``` --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # delta — Delta reference tool. Use when working with delta in finance contexts. # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="1.0.0" show_help() { cat << 'HELPEOF' delta v$VERSION — Delta Reference Tool Usage: delta <command> Commands: intro Overview and fundamentals formulas Key formulas and calculations regulations Regulatory framework and compliance risks Risk factors and mitigation instruments Instruments and tools overview strategies Common strategies and approaches glossary Key terms and definitions checklist Due diligence checklist help Show this help version Show version Powered by BytesAgain | bytesagain.com HELPEOF } cmd_intro() { cat << 'EOF' # Delta — Overview ## What is Delta? Delta (delta) is a specialized tool/concept in the finance domain. It provides essential capabilities for professionals working with delta. ## Key Concepts - Core delta principles and fundamentals - How delta fits into the broader finance ecosystem - Essential terminology every practitioner should know ## Why Delta Matters Understanding delta is critical for: - Improving efficiency in finance workflows - Reducing errors and downtime - Meeting industry standards and compliance requirements - Enabling better decision-making with accurate data ## Getting Started 1. Understand the basic delta concepts 2. Learn the standard tools and interfaces 3. Practice with common scenarios 4. Review safety and compliance requirements EOF } cmd_formulas() { cat << 'EOF' # Delta — Key Formulas & Calculations ## Core Formulas - **Basic ratio**: Value = Input / Reference × 100 - **Growth rate**: (Current - Previous) / Previous × 100% - **Weighted average**: Sum(Value × Weight) / Sum(Weight) ## Common Calculations 1. Risk-adjusted return 2. Break-even analysis 3. Compound growth 4. Present/future value 5. Standard deviation ## Quick Reference | Metric | Formula | Use Case | |--------|---------|----------| | ROI | (Gain - Cost) / Cost | Investment evaluation | | CAGR | (End/Start)^(1/n) - 1 | Growth measurement | | Sharpe | (Return - RiskFree) / StdDev | Risk-adjusted performance | EOF } cmd_regulations() { cat << 'EOF' # Delta — Regulatory Framework ## Key Regulations - Primary governing laws and statutes - Industry-specific compliance requirements - International standards and agreements ## Compliance Requirements - Registration and licensing - Reporting obligations - Record-keeping requirements - Audit and inspection readiness ## Enforcement - Regulatory bodies and their jurisdiction - Penalty structures for non-compliance - Appeal and dispute resolution processes EOF } cmd_risks() { cat << 'EOF' # Delta — Risk Analysis ## Risk Categories 1. **Market Risk**: Price volatility and liquidity 2. **Operational Risk**: System failures and human error 3. **Regulatory Risk**: Changing laws and compliance 4. **Credit Risk**: Counterparty default ## Risk Mitigation - Diversification strategies - Hedging instruments - Insurance and guarantees - Contingency planning ## Risk Assessment Framework | Risk | Probability | Impact | Mitigation | |------|-------------|--------|------------| | High | Likely | Severe | Immediate action | | Medium | Possible | Moderate | Monitor closely | | Low | Unlikely | Minor | Accept or transfer | EOF } cmd_instruments() { cat << 'EOF' # Delta — Instruments & Tools Overview ## Primary Instruments - Core tools used in delta operations - Measurement and monitoring equipment - Software platforms and applications ## Selection Guide 1. Define requirements and constraints 2. Evaluate available options 3. Consider total cost of ownership 4. Assess vendor support and community 5. Test before committing EOF } cmd_strategies() { cat << 'EOF' # Delta — Common Strategies ## Fundamental Strategies 1. **Conservative**: Low risk, steady returns 2. **Balanced**: Moderate risk, diversified approach 3. **Aggressive**: Higher risk, growth-focused ## Implementation Steps 1. Define objectives and constraints 2. Select appropriate strategy 3. Execute with discipline 4. Monitor and adjust 5. Review periodically EOF } cmd_glossary() { cat << 'EOF' # Delta — Key Terms & Definitions ## Core Terminology - **Delta**: The primary subject of this reference - **finance**: The broader domain category - **Baseline**: A reference point for comparison - **Benchmark**: A standard for measuring performance - **Compliance**: Adherence to rules and standards - **Configuration**: System settings and parameters - **Diagnostics**: Tools and procedures for identifying issues - **Integration**: Connecting multiple systems together - **Protocol**: A set of rules governing communication - **Specification**: Detailed requirements document EOF } cmd_checklist() { cat << 'EOF' # Delta — Inspection Checklist ## Pre-Operation Checklist - [ ] Visual inspection completed - [ ] All connections secure - [ ] Safety systems functional - [ ] Operating parameters within range - [ ] Documentation current ## Daily Checks - [ ] System startup normal - [ ] No error indicators or alarms - [ ] Performance within expected range - [ ] Environmental conditions acceptable - [ ] Log entries reviewed ## Periodic Inspection - [ ] Comprehensive system test - [ ] Calibration verification - [ ] Wear component inspection - [ ] Firmware/software version check - [ ] Backup systems tested ## Shutdown Checklist - [ ] Proper shutdown sequence followed - [ ] All data saved and backed up - [ ] System secured - [ ] Maintenance items logged - [ ] Next startup requirements noted EOF } CMD="-help" shift 2>/dev/null || true case "$CMD" in intro) cmd_intro "$@" ;; formulas) cmd_formulas "$@" ;; regulations) cmd_regulations "$@" ;; risks) cmd_risks "$@" ;; instruments) cmd_instruments "$@" ;; strategies) cmd_strategies "$@" ;; glossary) cmd_glossary "$@" ;; checklist) cmd_checklist "$@" ;; help|--help|-h) show_help ;; version|--version|-v) echo "delta v$VERSION — Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: delta help"; exit 1 ;; esac
Coldwallet reference tool. Use when working with coldwallet in blockchain contexts.
--- name: "coldwallet" version: "1.0.0" description: "Coldwallet reference tool. Use when working with coldwallet in blockchain contexts." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [coldwallet, blockchain, finance, reference, cli] category: "blockchain" --- # Coldwallet Coldwallet reference tool. Use when working with coldwallet in blockchain contexts. ## When to Use - Working with coldwallet and need quick reference - Looking up blockchain standards or best practices for coldwallet - Troubleshooting coldwallet issues - Need a checklist or guide for coldwallet tasks ## Commands ### `intro` ```bash scripts/script.sh intro ``` Overview and fundamentals ### `formulas` ```bash scripts/script.sh formulas ``` Key formulas and calculations ### `regulations` ```bash scripts/script.sh regulations ``` Regulatory framework and compliance ### `risks` ```bash scripts/script.sh risks ``` Risk factors and mitigation ### `instruments` ```bash scripts/script.sh instruments ``` Instruments and tools overview ### `strategies` ```bash scripts/script.sh strategies ``` Common strategies and approaches ### `glossary` ```bash scripts/script.sh glossary ``` Key terms and definitions ### `checklist` ```bash scripts/script.sh checklist ``` Due diligence checklist ### `help` ```bash scripts/script.sh help ``` ### `version` ```bash scripts/script.sh version ``` --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # coldwallet — Coldwallet reference tool. Use when working with coldwallet in blockchain contexts. # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="1.0.0" show_help() { cat << 'HELPEOF' coldwallet v$VERSION — Coldwallet Reference Tool Usage: coldwallet <command> Commands: intro Overview and fundamentals formulas Key formulas and calculations regulations Regulatory framework and compliance risks Risk factors and mitigation instruments Instruments and tools overview strategies Common strategies and approaches glossary Key terms and definitions checklist Due diligence checklist help Show this help version Show version Powered by BytesAgain | bytesagain.com HELPEOF } cmd_intro() { cat << 'EOF' # Coldwallet — Overview ## What is Coldwallet? Coldwallet (coldwallet) is a specialized tool/concept in the blockchain domain. It provides essential capabilities for professionals working with coldwallet. ## Key Concepts - Core coldwallet principles and fundamentals - How coldwallet fits into the broader blockchain ecosystem - Essential terminology every practitioner should know ## Why Coldwallet Matters Understanding coldwallet is critical for: - Improving efficiency in blockchain workflows - Reducing errors and downtime - Meeting industry standards and compliance requirements - Enabling better decision-making with accurate data ## Getting Started 1. Understand the basic coldwallet concepts 2. Learn the standard tools and interfaces 3. Practice with common scenarios 4. Review safety and compliance requirements EOF } cmd_formulas() { cat << 'EOF' # Coldwallet — Key Formulas & Calculations ## Core Formulas - **Basic ratio**: Value = Input / Reference × 100 - **Growth rate**: (Current - Previous) / Previous × 100% - **Weighted average**: Sum(Value × Weight) / Sum(Weight) ## Common Calculations 1. Risk-adjusted return 2. Break-even analysis 3. Compound growth 4. Present/future value 5. Standard deviation ## Quick Reference | Metric | Formula | Use Case | |--------|---------|----------| | ROI | (Gain - Cost) / Cost | Investment evaluation | | CAGR | (End/Start)^(1/n) - 1 | Growth measurement | | Sharpe | (Return - RiskFree) / StdDev | Risk-adjusted performance | EOF } cmd_regulations() { cat << 'EOF' # Coldwallet — Regulatory Framework ## Key Regulations - Primary governing laws and statutes - Industry-specific compliance requirements - International standards and agreements ## Compliance Requirements - Registration and licensing - Reporting obligations - Record-keeping requirements - Audit and inspection readiness ## Enforcement - Regulatory bodies and their jurisdiction - Penalty structures for non-compliance - Appeal and dispute resolution processes EOF } cmd_risks() { cat << 'EOF' # Coldwallet — Risk Analysis ## Risk Categories 1. **Market Risk**: Price volatility and liquidity 2. **Operational Risk**: System failures and human error 3. **Regulatory Risk**: Changing laws and compliance 4. **Credit Risk**: Counterparty default ## Risk Mitigation - Diversification strategies - Hedging instruments - Insurance and guarantees - Contingency planning ## Risk Assessment Framework | Risk | Probability | Impact | Mitigation | |------|-------------|--------|------------| | High | Likely | Severe | Immediate action | | Medium | Possible | Moderate | Monitor closely | | Low | Unlikely | Minor | Accept or transfer | EOF } cmd_instruments() { cat << 'EOF' # Coldwallet — Instruments & Tools Overview ## Primary Instruments - Core tools used in coldwallet operations - Measurement and monitoring equipment - Software platforms and applications ## Selection Guide 1. Define requirements and constraints 2. Evaluate available options 3. Consider total cost of ownership 4. Assess vendor support and community 5. Test before committing EOF } cmd_strategies() { cat << 'EOF' # Coldwallet — Common Strategies ## Fundamental Strategies 1. **Conservative**: Low risk, steady returns 2. **Balanced**: Moderate risk, diversified approach 3. **Aggressive**: Higher risk, growth-focused ## Implementation Steps 1. Define objectives and constraints 2. Select appropriate strategy 3. Execute with discipline 4. Monitor and adjust 5. Review periodically EOF } cmd_glossary() { cat << 'EOF' # Coldwallet — Key Terms & Definitions ## Core Terminology - **Coldwallet**: The primary subject of this reference - **blockchain**: The broader domain category - **Baseline**: A reference point for comparison - **Benchmark**: A standard for measuring performance - **Compliance**: Adherence to rules and standards - **Configuration**: System settings and parameters - **Diagnostics**: Tools and procedures for identifying issues - **Integration**: Connecting multiple systems together - **Protocol**: A set of rules governing communication - **Specification**: Detailed requirements document EOF } cmd_checklist() { cat << 'EOF' # Coldwallet — Inspection Checklist ## Pre-Operation Checklist - [ ] Visual inspection completed - [ ] All connections secure - [ ] Safety systems functional - [ ] Operating parameters within range - [ ] Documentation current ## Daily Checks - [ ] System startup normal - [ ] No error indicators or alarms - [ ] Performance within expected range - [ ] Environmental conditions acceptable - [ ] Log entries reviewed ## Periodic Inspection - [ ] Comprehensive system test - [ ] Calibration verification - [ ] Wear component inspection - [ ] Firmware/software version check - [ ] Backup systems tested ## Shutdown Checklist - [ ] Proper shutdown sequence followed - [ ] All data saved and backed up - [ ] System secured - [ ] Maintenance items logged - [ ] Next startup requirements noted EOF } CMD="-help" shift 2>/dev/null || true case "$CMD" in intro) cmd_intro "$@" ;; formulas) cmd_formulas "$@" ;; regulations) cmd_regulations "$@" ;; risks) cmd_risks "$@" ;; instruments) cmd_instruments "$@" ;; strategies) cmd_strategies "$@" ;; glossary) cmd_glossary "$@" ;; checklist) cmd_checklist "$@" ;; help|--help|-h) show_help ;; version|--version|-v) echo "coldwallet v$VERSION — Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: coldwallet help"; exit 1 ;; esac
Nft reference tool. Use when working with nft in blockchain contexts.
--- name: "nft" version: "1.0.0" description: "Nft reference tool. Use when working with nft in blockchain contexts." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [nft, blockchain, finance, reference, cli] category: "blockchain" --- # Nft Nft reference tool. Use when working with nft in blockchain contexts. ## When to Use - Working with nft and need quick reference - Looking up blockchain standards or best practices for nft - Troubleshooting nft issues - Need a checklist or guide for nft tasks ## Commands ### `intro` ```bash scripts/script.sh intro ``` Overview and fundamentals ### `formulas` ```bash scripts/script.sh formulas ``` Key formulas and calculations ### `regulations` ```bash scripts/script.sh regulations ``` Regulatory framework and compliance ### `risks` ```bash scripts/script.sh risks ``` Risk factors and mitigation ### `instruments` ```bash scripts/script.sh instruments ``` Instruments and tools overview ### `strategies` ```bash scripts/script.sh strategies ``` Common strategies and approaches ### `glossary` ```bash scripts/script.sh glossary ``` Key terms and definitions ### `checklist` ```bash scripts/script.sh checklist ``` Due diligence checklist ### `help` ```bash scripts/script.sh help ``` ### `version` ```bash scripts/script.sh version ``` --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # nft — NFT (Non-Fungible Token) reference tool # Powered by BytesAgain | bytesagain.com set -euo pipefail VERSION="1.0.0" cmd_intro() { cat << 'EOF' # NFT (Non-Fungible Token) — Overview ## What is an NFT? A Non-Fungible Token is a unique digital asset on a blockchain. Unlike fungible tokens (ETH, USDC) where each unit is interchangeable, each NFT has a distinct identity (contract address + token ID). ## Core Standard: ERC-721 Introduced by CryptoKitties team (2018). Key interface: - balanceOf(owner) → how many NFTs the address holds - ownerOf(tokenId) → who owns a specific token - transferFrom(from, to, tokenId) → move ownership - approve(to, tokenId) → grant transfer permission - setApprovalForAll(operator, bool) → blanket approval - tokenURI(tokenId) → metadata location (URL or IPFS hash) ## Metadata Standard tokenURI returns a JSON file: { "name": "Cool Cat #1234", "description": "A unique cool cat", "image": "ipfs://QmX.../1234.png", "attributes": [ {"trait_type": "Background", "value": "Blue"}, {"trait_type": "Fur", "value": "Gold", "display_type": "string"} ] } ## Storage Models On-chain: Metadata + image stored in contract (expensive, permanent) IPFS: Content-addressed, immutable once pinned (ipfs://Qm...) Arweave: Permanent storage, pay once (ar://...) Centralized: Regular URL (https://api.example.com/meta/1) — risky ## Minting Flow 1. Deploy ERC-721 contract with mint function 2. User calls mint() → pays gas + mint price 3. Contract assigns new tokenId to caller 4. Transfer event emitted: Transfer(address(0), minter, tokenId) 5. Marketplaces index the Transfer event automatically ## Marketplace Mechanics Listing: Owner calls setApprovalForAll(marketplace, true) Buying: Marketplace calls transferFrom(seller, buyer, tokenId) Royalty: ERC-2981 returns (receiver, amount) for secondary sales Auction: Bids held in escrow contract, highest wins after deadline EOF } cmd_standards() { cat << 'EOF' # NFT Standards Reference ## ERC-721 — Non-Fungible Token Standard (EIP-721) Required: balanceOf, ownerOf, safeTransferFrom, transferFrom, approve, getApproved, setApprovalForAll, isApprovedForAll Events: Transfer(from, to, tokenId), Approval(owner, approved, tokenId) Optional: name(), symbol(), tokenURI(tokenId) Safe transfer: Receiver must implement onERC721Received() or tx reverts ## ERC-1155 — Multi Token Standard Single contract manages both fungible and non-fungible tokens balanceOf(account, id) — check balance of specific token type balanceOfBatch(accounts[], ids[]) — batch balance check safeTransferFrom(from, to, id, amount, data) — transfer any type uri(id) — metadata URI with {id} substitution pattern Use case: Game items (sword=NFT, gold=fungible, same contract) ## ERC-2981 — NFT Royalty Standard royaltyInfo(tokenId, salePrice) returns (receiver, royaltyAmount) Typical: 2.5-10% of sale price NOT enforced on-chain — marketplaces choose to honor or ignore OpenSea Operator Filter Registry: blocks marketplaces that skip royalties ## ERC-4907 — Rental NFT (Dual Role) setUser(tokenId, user, expires) — grant temporary usage rights userOf(tokenId) — current user (may differ from owner) userExpires(tokenId) — expiration timestamp Use case: Gaming item rental, metaverse land leasing ## ERC-6551 — Token Bound Accounts Each NFT gets its own smart contract wallet NFT can own other tokens, NFTs, interact with DeFi createAccount(implementation, chainId, tokenContract, tokenId, salt) Account address deterministic via CREATE2 Use case: NFT character that carries inventory ## ERC-5192 — Minimal Soulbound Token locked(tokenId) returns bool — true means non-transferable Locked(tokenId) / Unlocked(tokenId) events Use case: Credentials, membership, identity ## Metadata JSON Schema Required: name, description, image Optional: external_url, animation_url, background_color Attributes array: trait_type, value, display_type display_type options: string, number, boost_number, boost_percentage, date EOF } cmd_troubleshooting() { cat << 'EOF' # NFT Troubleshooting Guide ## Metadata Not Showing on OpenSea Problem: Minted NFT shows blank on OpenSea Causes: - Base URI missing trailing slash: "ipfs://QmX" vs "ipfs://QmX/" - tokenURI returns 404 or empty JSON - Metadata JSON missing required fields (name, image) - Image URL unreachable (IPFS not pinned, server down) Fix: - Force refresh: POST api.opensea.io/api/v2/chain/ethereum/contract/{addr}/nfts/{id}/refresh - Verify tokenURI output: cast call <contract> "tokenURI(uint256)" <id> - Ensure image is accessible via public IPFS gateway ## IPFS Gateway Timeout Problem: ipfs://Qm... not loading or very slow Causes: Content not pinned, or public gateways overloaded Fix: - Pin with Pinata: pinata.cloud (free 500MB) - Pin with nft.storage: nft.storage (free, backed by Filecoin) - Use dedicated gateway: gateway.pinata.cloud/ipfs/{hash} - Self-host IPFS node for production ## Gas Estimation Failure on Mint Problem: "execution reverted" during mint Common causes: - Sale not active (check isSaleActive/isPublicSale flag) - Max per wallet exceeded (check maxMintPerWallet) - Wrong mint price (check mintPrice * quantity) - Allowlist not set (merkle root not configured) - Contract paused (check Pausable.paused()) Debug: cast call <contract> "mint(uint256)" <qty> --value <price> ## Royalty Not Enforced Problem: Secondary sales on some marketplaces pay no royalty Reality: ERC-2981 is voluntary — marketplaces can ignore it Solutions: - Implement OperatorFilterRegistry (blocks non-royalty marketplaces) - Use LooksRare/X2Y2 with mandatory royalties - Accept that royalty enforcement is imperfect on-chain ## tokenURI Returning Wrong Data Problem: All tokens return same metadata or wrong token metadata Common bugs: - Hardcoded baseURI without tokenId concatenation - Off-by-one: tokenId starts at 0 but files start at 1 - String concatenation: Strings.toString(tokenId) missing - Revealed flag not set (still returning placeholder URI) EOF } cmd_performance() { cat << 'EOF' # NFT Gas Optimization ## ERC-721A (Azuki) — Batch Mint Optimization Standard ERC-721: Each mint writes owner + balance = ~50k gas each ERC-721A: Batch of N mints costs almost same as 1 mint How: Only writes to first token in batch, infers rest on read Savings: 5 mints saves ~60% gas vs standard Trade-off: Slightly more gas on transfers (must update gaps) Install: npm install erc721a ## Lazy Minting (Mint on Purchase) Creator signs metadata off-chain (no gas cost) Buyer pays gas to mint + purchase in single transaction Requires: EIP-712 typed signature, voucher struct Flow: sign(tokenId, price, uri) → buyer calls redeem(voucher) Used by: Rarible, Foundation ## Merkle Proof Whitelists Instead of storing 10k addresses on-chain (expensive): 1. Build Merkle tree off-chain from address list 2. Store only 32-byte root on-chain: setMerkleRoot(bytes32) 3. User submits proof[]: mint(proof, quantity) 4. Contract verifies: MerkleProof.verify(proof, root, leaf) Gas: ~2k per proof element vs ~20k per SSTORE Library: @openzeppelin/contracts/utils/cryptography/MerkleProof.sol ## Bitmap for Claimed Tracking Instead of mapping(address => bool) hasClaimed: Use bitmap: mapping(uint256 => uint256) where each bit = 1 address 256 addresses per storage slot vs 1 per slot Check: (bitmap[index/256] >> (index%256)) & 1 Savings: 256x reduction in storage slots ## SSTORE2 for On-Chain Art Regular SSTORE: ~20k gas per 32 bytes SSTORE2: Deploy data as contract bytecode via CREATE Read: EXTCODECOPY (much cheaper than SLOAD) Write once, read many pattern Used for: On-chain SVG, generative art parameters Library: solady/src/utils/SSTORE2.sol ## General Tips - Use uint96 for prices (fits in same slot as address) - Pack structs: address(20) + uint96(12) = 1 slot (32 bytes) - Avoid strings in events (use indexed bytes32 instead) - unchecked {} for counter increments (saves ~60 gas) - Custom errors vs require strings (saves ~200 gas per revert) EOF } cmd_security() { cat << 'EOF' # NFT Security Guide ## Reentrancy in Mint Functions Attack: Malicious onERC721Received callback re-enters mint() Impact: Mint more than maxPerWallet, drain contract Fix: Use ReentrancyGuard from OpenZeppelin import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; function mint(uint256 qty) external payable nonReentrant { ... } Alternative: Checks-Effects-Interactions pattern ## Signature Replay in Allowlist Mints Attack: Valid signature reused across chains or after contract upgrade Impact: Unauthorized mints, exceed allocation Fix: Include in signed message: - chainId (prevent cross-chain replay) - contract address (prevent cross-contract replay) - nonce or deadline (prevent reuse) - quantity allowed (prevent over-mint) Use EIP-712 for structured, verifiable signatures ## Front-Running Reveal Attack: Attacker sees pending reveal transaction, buys rare NFTs How: Monitor mempool for setBaseURI/reveal transactions Fix: Commit-reveal pattern: 1. Mint phase: All tokens show placeholder 2. Commit: Owner submits hash(baseURI + secret) 3. Reveal: Owner submits baseURI + secret (verified against hash) 4. Randomize: Use VRF (Chainlink) for token-to-metadata mapping ## setApprovalForAll Phishing Attack: Malicious site asks user to setApprovalForAll(attacker, true) Impact: Attacker can transfer ALL user's NFTs from that collection Prevention: - Wallet warnings (MetaMask shows approval scope) - Users: Never approve unknown contracts - Devs: Consider per-token approve() instead ## Unlimited Mint Exploits Attack: No maxSupply check, or maxPerWallet only checks current balance Impact: Unlimited minting, worthless collection Fix: - require(totalSupply() + qty <= MAX_SUPPLY) - Use mapping for mint count (not balanceOf — user can transfer out) - mapping(address => uint256) private _mintCount; ## Withdrawal Vulnerabilities Attack: Funds locked in contract, owner can't withdraw Cause: Using transfer() (2300 gas limit) to multisig or contract Fix: Use call{value: amount}("") instead of transfer() (bool success, ) = payable(owner).call{value: balance}(""); require(success, "Transfer failed"); EOF } cmd_migration() { cat << 'EOF' # NFT Migration Guide ## ERC-721 to ERC-1155 Migration Why: Multi-edition support, gas efficiency, batch transfers Steps: 1. Snapshot current holders: query Transfer events for ownership 2. Deploy new ERC-1155 contract with equivalent token IDs 3. Airdrop: Batch mint to all existing holders 4. Optional: Allow burn-to-claim (burn 721, receive 1155) 5. Update marketplace listings to new collection 6. Redirect old tokenURI to point to new contract Considerations: - 1:1 unique NFTs use amount=1 in ERC-1155 - Existing approvals don't carry over - Historical provenance stays on old contract ## Centralized Metadata to IPFS Migration Why: Server goes down = metadata lost forever Steps: 1. Download all metadata JSON + images from current server 2. Organize: metadata/0.json, metadata/1.json, images/0.png... 3. Upload images to IPFS: ipfs add -r images/ 4. Update metadata JSON: replace image URLs with ipfs:// hashes 5. Upload metadata to IPFS: ipfs add -r metadata/ 6. Pin on Pinata/nft.storage for persistence 7. Call setBaseURI("ipfs://QmNewMetadataFolder/") 8. Verify on OpenSea: refresh each token Tools: - nft.storage: Free permanent storage (Filecoin-backed) - Pinata: Free tier 500MB, paid for more - thirdweb Storage: SDK for automated uploads ## Marketplace Migration Checklist When moving from OpenSea to another marketplace: [ ] Verify new marketplace supports your token standard [ ] Check royalty enforcement policy [ ] Update collection metadata (banner, description, links) [ ] Notify community via Discord/Twitter [ ] Test listing and buying on testnet first [ ] Monitor for airdrop scams impersonating new marketplace [ ] Update project website marketplace links [ ] Consider multi-marketplace listing for max visibility EOF } cmd_cheatsheet() { cat << 'EOF' # NFT Developer Cheatsheet ## Foundry / Forge Commands forge init my-nft-project # New project forge install openzeppelin/openzeppelin-contracts # Add OZ forge build # Compile forge test -vvv # Test with traces forge create src/MyNFT.sol:MyNFT \ --rpc-url $RPC --private-key $KEY \ --constructor-args "MyNFT" "MNFT" # Deploy forge verify-contract $ADDR src/MyNFT.sol:MyNFT \ --etherscan-api-key $KEY --chain mainnet # Verify ## Hardhat Commands npx hardhat compile npx hardhat run scripts/deploy.js --network mainnet npx hardhat verify --network mainnet $ADDR "MyNFT" "MNFT" ## IPFS Commands ipfs add -r ./metadata/ # Upload folder ipfs pin add QmHash # Pin content ipfs cat QmHash/0.json # Read file ## OpenZeppelin Contracts Wizard https://wizard.openzeppelin.com/#erc721 Generate: Mintable, Burnable, Enumerable, URIStorage, Pausable ## API Endpoints OpenSea (v2): GET api.opensea.io/api/v2/chain/ethereum/contract/{addr}/nfts/{id} POST api.opensea.io/api/v2/chain/ethereum/contract/{addr}/nfts/{id}/refresh Alchemy NFT API: GET {network}.g.alchemy.com/nft/v3/{key}/getNFTsForOwner?owner={addr} GET {network}.g.alchemy.com/nft/v3/{key}/getNFTMetadata?contractAddress={addr}&tokenId={id} Reservoir (aggregator): GET api.reservoir.tools/tokens/v7?tokens={addr}:{id} ## Block Explorers Ethereum: etherscan.io/token/{addr} Polygon: polygonscan.com/token/{addr} Base: basescan.org/token/{addr} ## Common Contract Reads cast call $ADDR "totalSupply()(uint256)" cast call $ADDR "tokenURI(uint256)(string)" 1 cast call $ADDR "ownerOf(uint256)(address)" 1 cast call $ADDR "balanceOf(address)(uint256)" $WALLET cast call $ADDR "royaltyInfo(uint256,uint256)(address,uint256)" 1 10000 EOF } cmd_faq() { cat << 'EOF' # NFT — Frequently Asked Questions Q: How much gas does minting cost? A: Standard ERC-721 mint: ~50,000-80,000 gas (~$3-15 at typical prices). ERC-721A batch mint of 5: ~65,000 gas total (vs ~350,000 standard). ERC-1155 mint: ~26,000 gas (most efficient). Layer 2 (Polygon, Base): ~$0.01-0.10 per mint. Q: Are royalties enforced on-chain? A: Not automatically. ERC-2981 is informational only. OpenSea enforces via Operator Filter Registry (block non-paying marketplaces). Blur made royalties optional. Some chains (Stacks) have protocol-level royalties. Q: What are soulbound tokens (SBTs)? A: Non-transferable NFTs (ERC-5192). Once minted, cannot be sold or transferred. Use cases: university diplomas, proof of attendance (POAPs), professional certifications, on-chain reputation. Vitalik Buterin proposed them in "Decentralized Society" paper (2022). Q: What are dynamic NFTs? A: NFTs whose metadata changes based on external data. Examples: Sports NFT updates with player stats (Chainlink oracle), art NFT changes with weather, game character levels up. Implementation: On-chain SVG generation or oracle-triggered metadata refresh. Base URI points to API that serves dynamic JSON. Q: How do cross-chain NFTs work? A: LayerZero ONFT: Lock on source chain, mint on destination. Wormhole: Similar bridge mechanism with guardian network. Connext: Liquidity-based bridging for faster transfers. Risks: Bridge exploits, wrapped token depegs, metadata sync issues. Q: What's the difference between ERC-721 and ERC-1155? A: ERC-721: Each token unique, one contract per collection. ERC-1155: Multiple token types in one contract (unique + fungible). ERC-1155 is more gas efficient for batch operations. Choose 721 for PFP/art, 1155 for gaming/editions. Q: How do I make my NFT collection updatable? A: Use a proxy pattern (UUPS or Transparent Proxy) for contract logic. For metadata: use a revealable baseURI that owner can update. Warning: Upgradeable contracts reduce trust — users prefer immutable. Compromise: Lock metadata after reveal, keep contract logic upgradeable. Q: What's the cheapest way to launch an NFT collection? A: Use ERC-721A on a Layer 2 (Base, Polygon, Arbitrum). Tools: thirdweb (no-code), Manifold (creator tools), or custom Foundry. Cost breakdown: Contract deploy ~$2-5 on L2, metadata on IPFS (free). Total: Under $10 to launch 10,000 NFTs on L2. EOF } cmd_help() { echo "nft v$VERSION — NFT (Non-Fungible Token) Reference Tool" echo "" echo "Usage: nft <command>" echo "" echo "Commands:" echo " intro Overview of NFTs and core concepts" echo " standards ERC-721, ERC-1155, ERC-2981 and more" echo " troubleshooting Common problems and solutions" echo " performance Gas optimization techniques" echo " security Security vulnerabilities and fixes" echo " migration Migration and upgrade guides" echo " cheatsheet Quick reference commands and URLs" echo " faq Frequently asked questions" echo " help Show this help" } case "-help" in intro) cmd_intro ;; standards) cmd_standards ;; troubleshooting) cmd_troubleshooting ;; performance) cmd_performance ;; security) cmd_security ;; migration) cmd_migration ;; cheatsheet) cmd_cheatsheet ;; faq) cmd_faq ;; help|--help|-h) cmd_help ;; *) echo "Unknown: $1"; echo "Run: nft help" ;; esac
Scroll reference tool. Use when working with scroll in blockchain contexts.
--- name: "scroll" version: "1.0.0" description: "Scroll reference tool. Use when working with scroll in blockchain contexts." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [scroll, blockchain, finance, reference, cli] category: "blockchain" --- # Scroll Scroll reference tool. Use when working with scroll in blockchain contexts. ## When to Use - Working with scroll and need quick reference - Looking up blockchain standards or best practices for scroll - Troubleshooting scroll issues - Need a checklist or guide for scroll tasks ## Commands ### `intro` ```bash scripts/script.sh intro ``` Overview and fundamentals ### `formulas` ```bash scripts/script.sh formulas ``` Key formulas and calculations ### `regulations` ```bash scripts/script.sh regulations ``` Regulatory framework and compliance ### `risks` ```bash scripts/script.sh risks ``` Risk factors and mitigation ### `instruments` ```bash scripts/script.sh instruments ``` Instruments and tools overview ### `strategies` ```bash scripts/script.sh strategies ``` Common strategies and approaches ### `glossary` ```bash scripts/script.sh glossary ``` Key terms and definitions ### `checklist` ```bash scripts/script.sh checklist ``` Due diligence checklist ### `help` ```bash scripts/script.sh help ``` ### `version` ```bash scripts/script.sh version ``` --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # scroll — Scroll reference tool. Use when working with scroll in blockchain contexts. # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="1.0.0" show_help() { cat << 'HELPEOF' scroll v$VERSION — Scroll Reference Tool Usage: scroll <command> Commands: intro Overview and fundamentals formulas Key formulas and calculations regulations Regulatory framework and compliance risks Risk factors and mitigation instruments Instruments and tools overview strategies Common strategies and approaches glossary Key terms and definitions checklist Due diligence checklist help Show this help version Show version Powered by BytesAgain | bytesagain.com HELPEOF } cmd_intro() { cat << 'EOF' # Scroll — Overview ## What is Scroll? Scroll (scroll) is a specialized tool/concept in the blockchain domain. It provides essential capabilities for professionals working with scroll. ## Key Concepts - Core scroll principles and fundamentals - How scroll fits into the broader blockchain ecosystem - Essential terminology every practitioner should know ## Why Scroll Matters Understanding scroll is critical for: - Improving efficiency in blockchain workflows - Reducing errors and downtime - Meeting industry standards and compliance requirements - Enabling better decision-making with accurate data ## Getting Started 1. Understand the basic scroll concepts 2. Learn the standard tools and interfaces 3. Practice with common scenarios 4. Review safety and compliance requirements EOF } cmd_formulas() { cat << 'EOF' # Scroll — Key Formulas & Calculations ## Core Formulas - **Basic ratio**: Value = Input / Reference × 100 - **Growth rate**: (Current - Previous) / Previous × 100% - **Weighted average**: Sum(Value × Weight) / Sum(Weight) ## Common Calculations 1. Risk-adjusted return 2. Break-even analysis 3. Compound growth 4. Present/future value 5. Standard deviation ## Quick Reference | Metric | Formula | Use Case | |--------|---------|----------| | ROI | (Gain - Cost) / Cost | Investment evaluation | | CAGR | (End/Start)^(1/n) - 1 | Growth measurement | | Sharpe | (Return - RiskFree) / StdDev | Risk-adjusted performance | EOF } cmd_regulations() { cat << 'EOF' # Scroll — Regulatory Framework ## Key Regulations - Primary governing laws and statutes - Industry-specific compliance requirements - International standards and agreements ## Compliance Requirements - Registration and licensing - Reporting obligations - Record-keeping requirements - Audit and inspection readiness ## Enforcement - Regulatory bodies and their jurisdiction - Penalty structures for non-compliance - Appeal and dispute resolution processes EOF } cmd_risks() { cat << 'EOF' # Scroll — Risk Analysis ## Risk Categories 1. **Market Risk**: Price volatility and liquidity 2. **Operational Risk**: System failures and human error 3. **Regulatory Risk**: Changing laws and compliance 4. **Credit Risk**: Counterparty default ## Risk Mitigation - Diversification strategies - Hedging instruments - Insurance and guarantees - Contingency planning ## Risk Assessment Framework | Risk | Probability | Impact | Mitigation | |------|-------------|--------|------------| | High | Likely | Severe | Immediate action | | Medium | Possible | Moderate | Monitor closely | | Low | Unlikely | Minor | Accept or transfer | EOF } cmd_instruments() { cat << 'EOF' # Scroll — Instruments & Tools Overview ## Primary Instruments - Core tools used in scroll operations - Measurement and monitoring equipment - Software platforms and applications ## Selection Guide 1. Define requirements and constraints 2. Evaluate available options 3. Consider total cost of ownership 4. Assess vendor support and community 5. Test before committing EOF } cmd_strategies() { cat << 'EOF' # Scroll — Common Strategies ## Fundamental Strategies 1. **Conservative**: Low risk, steady returns 2. **Balanced**: Moderate risk, diversified approach 3. **Aggressive**: Higher risk, growth-focused ## Implementation Steps 1. Define objectives and constraints 2. Select appropriate strategy 3. Execute with discipline 4. Monitor and adjust 5. Review periodically EOF } cmd_glossary() { cat << 'EOF' # Scroll — Key Terms & Definitions ## Core Terminology - **Scroll**: The primary subject of this reference - **blockchain**: The broader domain category - **Baseline**: A reference point for comparison - **Benchmark**: A standard for measuring performance - **Compliance**: Adherence to rules and standards - **Configuration**: System settings and parameters - **Diagnostics**: Tools and procedures for identifying issues - **Integration**: Connecting multiple systems together - **Protocol**: A set of rules governing communication - **Specification**: Detailed requirements document EOF } cmd_checklist() { cat << 'EOF' # Scroll — Inspection Checklist ## Pre-Operation Checklist - [ ] Visual inspection completed - [ ] All connections secure - [ ] Safety systems functional - [ ] Operating parameters within range - [ ] Documentation current ## Daily Checks - [ ] System startup normal - [ ] No error indicators or alarms - [ ] Performance within expected range - [ ] Environmental conditions acceptable - [ ] Log entries reviewed ## Periodic Inspection - [ ] Comprehensive system test - [ ] Calibration verification - [ ] Wear component inspection - [ ] Firmware/software version check - [ ] Backup systems tested ## Shutdown Checklist - [ ] Proper shutdown sequence followed - [ ] All data saved and backed up - [ ] System secured - [ ] Maintenance items logged - [ ] Next startup requirements noted EOF } CMD="-help" shift 2>/dev/null || true case "$CMD" in intro) cmd_intro "$@" ;; formulas) cmd_formulas "$@" ;; regulations) cmd_regulations "$@" ;; risks) cmd_risks "$@" ;; instruments) cmd_instruments "$@" ;; strategies) cmd_strategies "$@" ;; glossary) cmd_glossary "$@" ;; checklist) cmd_checklist "$@" ;; help|--help|-h) show_help ;; version|--version|-v) echo "scroll v$VERSION — Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: scroll help"; exit 1 ;; esac
Vyper reference tool. Use when working with vyper in blockchain contexts.
--- name: "vyper" version: "1.0.0" description: "Vyper reference tool. Use when working with vyper in blockchain contexts." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [vyper, blockchain, finance, reference, cli] category: "blockchain" --- # Vyper Vyper reference tool. Use when working with vyper in blockchain contexts. ## When to Use - Working with vyper and need quick reference - Looking up blockchain standards or best practices for vyper - Troubleshooting vyper issues - Need a checklist or guide for vyper tasks ## Commands ### `intro` ```bash scripts/script.sh intro ``` Overview and fundamentals ### `formulas` ```bash scripts/script.sh formulas ``` Key formulas and calculations ### `regulations` ```bash scripts/script.sh regulations ``` Regulatory framework and compliance ### `risks` ```bash scripts/script.sh risks ``` Risk factors and mitigation ### `instruments` ```bash scripts/script.sh instruments ``` Instruments and tools overview ### `strategies` ```bash scripts/script.sh strategies ``` Common strategies and approaches ### `glossary` ```bash scripts/script.sh glossary ``` Key terms and definitions ### `checklist` ```bash scripts/script.sh checklist ``` Due diligence checklist ### `help` ```bash scripts/script.sh help ``` ### `version` ```bash scripts/script.sh version ``` --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # vyper — Vyper reference tool. Use when working with vyper in blockchain contexts. # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="1.0.0" show_help() { cat << 'HELPEOF' vyper v$VERSION — Vyper Reference Tool Usage: vyper <command> Commands: intro Overview and fundamentals formulas Key formulas and calculations regulations Regulatory framework and compliance risks Risk factors and mitigation instruments Instruments and tools overview strategies Common strategies and approaches glossary Key terms and definitions checklist Due diligence checklist help Show this help version Show version Powered by BytesAgain | bytesagain.com HELPEOF } cmd_intro() { cat << 'EOF' # Vyper — Overview ## What is Vyper? Vyper (vyper) is a specialized tool/concept in the blockchain domain. It provides essential capabilities for professionals working with vyper. ## Key Concepts - Core vyper principles and fundamentals - How vyper fits into the broader blockchain ecosystem - Essential terminology every practitioner should know ## Why Vyper Matters Understanding vyper is critical for: - Improving efficiency in blockchain workflows - Reducing errors and downtime - Meeting industry standards and compliance requirements - Enabling better decision-making with accurate data ## Getting Started 1. Understand the basic vyper concepts 2. Learn the standard tools and interfaces 3. Practice with common scenarios 4. Review safety and compliance requirements EOF } cmd_formulas() { cat << 'EOF' # Vyper — Key Formulas & Calculations ## Core Formulas - **Basic ratio**: Value = Input / Reference × 100 - **Growth rate**: (Current - Previous) / Previous × 100% - **Weighted average**: Sum(Value × Weight) / Sum(Weight) ## Common Calculations 1. Risk-adjusted return 2. Break-even analysis 3. Compound growth 4. Present/future value 5. Standard deviation ## Quick Reference | Metric | Formula | Use Case | |--------|---------|----------| | ROI | (Gain - Cost) / Cost | Investment evaluation | | CAGR | (End/Start)^(1/n) - 1 | Growth measurement | | Sharpe | (Return - RiskFree) / StdDev | Risk-adjusted performance | EOF } cmd_regulations() { cat << 'EOF' # Vyper — Regulatory Framework ## Key Regulations - Primary governing laws and statutes - Industry-specific compliance requirements - International standards and agreements ## Compliance Requirements - Registration and licensing - Reporting obligations - Record-keeping requirements - Audit and inspection readiness ## Enforcement - Regulatory bodies and their jurisdiction - Penalty structures for non-compliance - Appeal and dispute resolution processes EOF } cmd_risks() { cat << 'EOF' # Vyper — Risk Analysis ## Risk Categories 1. **Market Risk**: Price volatility and liquidity 2. **Operational Risk**: System failures and human error 3. **Regulatory Risk**: Changing laws and compliance 4. **Credit Risk**: Counterparty default ## Risk Mitigation - Diversification strategies - Hedging instruments - Insurance and guarantees - Contingency planning ## Risk Assessment Framework | Risk | Probability | Impact | Mitigation | |------|-------------|--------|------------| | High | Likely | Severe | Immediate action | | Medium | Possible | Moderate | Monitor closely | | Low | Unlikely | Minor | Accept or transfer | EOF } cmd_instruments() { cat << 'EOF' # Vyper — Instruments & Tools Overview ## Primary Instruments - Core tools used in vyper operations - Measurement and monitoring equipment - Software platforms and applications ## Selection Guide 1. Define requirements and constraints 2. Evaluate available options 3. Consider total cost of ownership 4. Assess vendor support and community 5. Test before committing EOF } cmd_strategies() { cat << 'EOF' # Vyper — Common Strategies ## Fundamental Strategies 1. **Conservative**: Low risk, steady returns 2. **Balanced**: Moderate risk, diversified approach 3. **Aggressive**: Higher risk, growth-focused ## Implementation Steps 1. Define objectives and constraints 2. Select appropriate strategy 3. Execute with discipline 4. Monitor and adjust 5. Review periodically EOF } cmd_glossary() { cat << 'EOF' # Vyper — Key Terms & Definitions ## Core Terminology - **Vyper**: The primary subject of this reference - **blockchain**: The broader domain category - **Baseline**: A reference point for comparison - **Benchmark**: A standard for measuring performance - **Compliance**: Adherence to rules and standards - **Configuration**: System settings and parameters - **Diagnostics**: Tools and procedures for identifying issues - **Integration**: Connecting multiple systems together - **Protocol**: A set of rules governing communication - **Specification**: Detailed requirements document EOF } cmd_checklist() { cat << 'EOF' # Vyper — Inspection Checklist ## Pre-Operation Checklist - [ ] Visual inspection completed - [ ] All connections secure - [ ] Safety systems functional - [ ] Operating parameters within range - [ ] Documentation current ## Daily Checks - [ ] System startup normal - [ ] No error indicators or alarms - [ ] Performance within expected range - [ ] Environmental conditions acceptable - [ ] Log entries reviewed ## Periodic Inspection - [ ] Comprehensive system test - [ ] Calibration verification - [ ] Wear component inspection - [ ] Firmware/software version check - [ ] Backup systems tested ## Shutdown Checklist - [ ] Proper shutdown sequence followed - [ ] All data saved and backed up - [ ] System secured - [ ] Maintenance items logged - [ ] Next startup requirements noted EOF } CMD="-help" shift 2>/dev/null || true case "$CMD" in intro) cmd_intro "$@" ;; formulas) cmd_formulas "$@" ;; regulations) cmd_regulations "$@" ;; risks) cmd_risks "$@" ;; instruments) cmd_instruments "$@" ;; strategies) cmd_strategies "$@" ;; glossary) cmd_glossary "$@" ;; checklist) cmd_checklist "$@" ;; help|--help|-h) show_help ;; version|--version|-v) echo "vyper v$VERSION — Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: vyper help"; exit 1 ;; esac
Obv reference tool. Use when working with obv in finance contexts.
--- name: "obv" version: "1.0.0" description: "Obv reference tool. Use when working with obv in finance contexts." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [obv, finance, finance, reference, cli] category: "finance" --- # Obv Obv reference tool. Use when working with obv in finance contexts. ## When to Use - Working with obv and need quick reference - Looking up finance standards or best practices for obv - Troubleshooting obv issues - Need a checklist or guide for obv tasks ## Commands ### `intro` ```bash scripts/script.sh intro ``` Overview and fundamentals ### `formulas` ```bash scripts/script.sh formulas ``` Key formulas and calculations ### `regulations` ```bash scripts/script.sh regulations ``` Regulatory framework and compliance ### `risks` ```bash scripts/script.sh risks ``` Risk factors and mitigation ### `instruments` ```bash scripts/script.sh instruments ``` Instruments and tools overview ### `strategies` ```bash scripts/script.sh strategies ``` Common strategies and approaches ### `glossary` ```bash scripts/script.sh glossary ``` Key terms and definitions ### `checklist` ```bash scripts/script.sh checklist ``` Due diligence checklist ### `help` ```bash scripts/script.sh help ``` ### `version` ```bash scripts/script.sh version ``` --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # obv — Obv reference tool. Use when working with obv in finance contexts. # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="1.0.0" show_help() { cat << 'HELPEOF' obv v$VERSION — Obv Reference Tool Usage: obv <command> Commands: intro Overview and fundamentals formulas Key formulas and calculations regulations Regulatory framework and compliance risks Risk factors and mitigation instruments Instruments and tools overview strategies Common strategies and approaches glossary Key terms and definitions checklist Due diligence checklist help Show this help version Show version Powered by BytesAgain | bytesagain.com HELPEOF } cmd_intro() { cat << 'EOF' # Obv — Overview ## What is Obv? Obv (obv) is a specialized tool/concept in the finance domain. It provides essential capabilities for professionals working with obv. ## Key Concepts - Core obv principles and fundamentals - How obv fits into the broader finance ecosystem - Essential terminology every practitioner should know ## Why Obv Matters Understanding obv is critical for: - Improving efficiency in finance workflows - Reducing errors and downtime - Meeting industry standards and compliance requirements - Enabling better decision-making with accurate data ## Getting Started 1. Understand the basic obv concepts 2. Learn the standard tools and interfaces 3. Practice with common scenarios 4. Review safety and compliance requirements EOF } cmd_formulas() { cat << 'EOF' # Obv — Key Formulas & Calculations ## Core Formulas - **Basic ratio**: Value = Input / Reference × 100 - **Growth rate**: (Current - Previous) / Previous × 100% - **Weighted average**: Sum(Value × Weight) / Sum(Weight) ## Common Calculations 1. Risk-adjusted return 2. Break-even analysis 3. Compound growth 4. Present/future value 5. Standard deviation ## Quick Reference | Metric | Formula | Use Case | |--------|---------|----------| | ROI | (Gain - Cost) / Cost | Investment evaluation | | CAGR | (End/Start)^(1/n) - 1 | Growth measurement | | Sharpe | (Return - RiskFree) / StdDev | Risk-adjusted performance | EOF } cmd_regulations() { cat << 'EOF' # Obv — Regulatory Framework ## Key Regulations - Primary governing laws and statutes - Industry-specific compliance requirements - International standards and agreements ## Compliance Requirements - Registration and licensing - Reporting obligations - Record-keeping requirements - Audit and inspection readiness ## Enforcement - Regulatory bodies and their jurisdiction - Penalty structures for non-compliance - Appeal and dispute resolution processes EOF } cmd_risks() { cat << 'EOF' # Obv — Risk Analysis ## Risk Categories 1. **Market Risk**: Price volatility and liquidity 2. **Operational Risk**: System failures and human error 3. **Regulatory Risk**: Changing laws and compliance 4. **Credit Risk**: Counterparty default ## Risk Mitigation - Diversification strategies - Hedging instruments - Insurance and guarantees - Contingency planning ## Risk Assessment Framework | Risk | Probability | Impact | Mitigation | |------|-------------|--------|------------| | High | Likely | Severe | Immediate action | | Medium | Possible | Moderate | Monitor closely | | Low | Unlikely | Minor | Accept or transfer | EOF } cmd_instruments() { cat << 'EOF' # Obv — Instruments & Tools Overview ## Primary Instruments - Core tools used in obv operations - Measurement and monitoring equipment - Software platforms and applications ## Selection Guide 1. Define requirements and constraints 2. Evaluate available options 3. Consider total cost of ownership 4. Assess vendor support and community 5. Test before committing EOF } cmd_strategies() { cat << 'EOF' # Obv — Common Strategies ## Fundamental Strategies 1. **Conservative**: Low risk, steady returns 2. **Balanced**: Moderate risk, diversified approach 3. **Aggressive**: Higher risk, growth-focused ## Implementation Steps 1. Define objectives and constraints 2. Select appropriate strategy 3. Execute with discipline 4. Monitor and adjust 5. Review periodically EOF } cmd_glossary() { cat << 'EOF' # Obv — Key Terms & Definitions ## Core Terminology - **Obv**: The primary subject of this reference - **finance**: The broader domain category - **Baseline**: A reference point for comparison - **Benchmark**: A standard for measuring performance - **Compliance**: Adherence to rules and standards - **Configuration**: System settings and parameters - **Diagnostics**: Tools and procedures for identifying issues - **Integration**: Connecting multiple systems together - **Protocol**: A set of rules governing communication - **Specification**: Detailed requirements document EOF } cmd_checklist() { cat << 'EOF' # Obv — Inspection Checklist ## Pre-Operation Checklist - [ ] Visual inspection completed - [ ] All connections secure - [ ] Safety systems functional - [ ] Operating parameters within range - [ ] Documentation current ## Daily Checks - [ ] System startup normal - [ ] No error indicators or alarms - [ ] Performance within expected range - [ ] Environmental conditions acceptable - [ ] Log entries reviewed ## Periodic Inspection - [ ] Comprehensive system test - [ ] Calibration verification - [ ] Wear component inspection - [ ] Firmware/software version check - [ ] Backup systems tested ## Shutdown Checklist - [ ] Proper shutdown sequence followed - [ ] All data saved and backed up - [ ] System secured - [ ] Maintenance items logged - [ ] Next startup requirements noted EOF } CMD="-help" shift 2>/dev/null || true case "$CMD" in intro) cmd_intro "$@" ;; formulas) cmd_formulas "$@" ;; regulations) cmd_regulations "$@" ;; risks) cmd_risks "$@" ;; instruments) cmd_instruments "$@" ;; strategies) cmd_strategies "$@" ;; glossary) cmd_glossary "$@" ;; checklist) cmd_checklist "$@" ;; help|--help|-h) show_help ;; version|--version|-v) echo "obv v$VERSION — Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: obv help"; exit 1 ;; esac