@clawhub-bytesagain-lab-4f4db08043
Localize product listings across English and Chinese ecommerce channels. Use when adapting Amazon, Shopify, Taobao, Pinduoduo, TK, or independent-site copy.
---
name: "BytesAgain Crossborder Product Localizer"
description: "Localize product listings across English and Chinese ecommerce channels. Use when adapting Amazon, Shopify, Taobao, Pinduoduo, TK, or independent-site copy."
version: "1.0.0"
author: "BytesAgain"
homepage: "https://bytesagain.com"
source: "https://github.com/bytesagain/ai-skills"
tags: ["ecommerce", "localization", "crossborder", "amazon", "shopify", "taobao", "pinduoduo"]
category: "ecommerce"
---
# BytesAgain Crossborder Product Localizer
Localize product listings across English and Chinese ecommerce channels. It turns product facts into channel-ready ecommerce copy, audits missing fields, and formats outputs that AI agents can paste into store workflows.
## Commands
### map
Map source product facts to target channel fields.
```bash
bash scripts/script.sh map --product "portable blender" --channel "Amazon" --features "USB-C charging,400ml cup,easy cleaning" --keywords "portable blender,smoothie maker"
```
### localize
Rewrite copy for a target market.
```bash
bash scripts/script.sh localize --product "portable blender" --channel "Amazon" --features "USB-C charging,400ml cup,easy cleaning" --keywords "portable blender,smoothie maker"
```
### tone
Generate tone variants for platform norms.
```bash
bash scripts/script.sh tone --product "portable blender" --channel "Amazon" --features "USB-C charging,400ml cup,easy cleaning" --keywords "portable blender,smoothie maker"
```
### compliance
Check risky claims and missing disclaimers.
```bash
bash scripts/script.sh compliance --product "portable blender" --channel "Amazon" --features "USB-C charging,400ml cup,easy cleaning" --keywords "portable blender,smoothie maker"
```
### bundle
Create a multi-channel launch bundle.
```bash
bash scripts/script.sh bundle --product "portable blender" --channel "Amazon" --features "USB-C charging,400ml cup,easy cleaning" --keywords "portable blender,smoothie maker"
```
### demo
Print a bilingual product localization pack.
```bash
bash scripts/script.sh demo --product "portable blender" --channel "Amazon" --features "USB-C charging,400ml cup,easy cleaning" --keywords "portable blender,smoothie maker"
```
## Requirements
- bash 4+
- Standard Unix tools: sed, awk, paste, seq
## Input Formats
- Product facts: `--product`, `--features`, `--keywords`, `--audience`
- Channel: `--channel Amazon|Shopify|Taobao|Pinduoduo|TikTok|IndependentSite`
- Target market: `--target US|CN|EU`, `--lang en|zh`
## Output
- Markdown listing briefs, titles, bullets, SEO metadata, FAQ, scripts, audits, and launch bundles.
## Notes
Use official marketplace policies before publishing claims. This skill drafts and audits copy; it does not upload products or ask for seller credentials.
## Feedback
https://bytesagain.com/feedback/
Powered by BytesAgain | bytesagain.com
FILE:scripts/script.sh
#!/usr/bin/env bash
set -euo pipefail
VERSION="1.0.0"
SKILL_NAME="BytesAgain Crossborder Product Localizer"
FOCUS="localize"
err(){ printf 'Error: %s\n' "$*" >&2; }
slugify(){ printf '%s' "$1" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9]+/-/g;s/^-//;s/-$//'; }
trim(){ sed 's/^ *//;s/ *$//'; }
split_csv(){ printf '%s' "$1" | tr ',' '\n' | trim | sed '/^$/d'; }
PRODUCT=""; CHANNEL="marketplace"; AUDIENCE="buyers"; FEATURES=""; KEYWORDS=""; PRICE=""; TONE="clear"; LANG="en"; INPUT=""; TARGET="US"; LENGTH="medium"
parse_opts(){
while [ "$#" -gt 0 ]; do
case "$1" in
--product) PRODUCT="-"; shift 2;;
--channel) CHANNEL="-"; shift 2;;
--audience) AUDIENCE="-"; shift 2;;
--features) FEATURES="-"; shift 2;;
--keywords) KEYWORDS="-"; shift 2;;
--price) PRICE="-"; shift 2;;
--tone) TONE="-"; shift 2;;
--lang) LANG="-"; shift 2;;
--input) INPUT="-"; shift 2;;
--target) TARGET="-"; shift 2;;
--length) LENGTH="-"; shift 2;;
*) if [[ "$1" == --* ]]; then err "unknown option: $1"; return 1; else INPUT="$1"; shift; fi;;
esac
done
[ -n "$PRODUCT" ] || PRODUCT="wireless desk lamp"
[ -n "$FEATURES" ] || FEATURES="adjustable brightness, USB-C charging, foldable arm, eye comfort"
[ -n "$KEYWORDS" ] || KEYWORDS="desk lamp, study light, home office"
}
channel_style(){
case "$(printf '%s' "$CHANNEL" | tr '[:upper:]' '[:lower:]')" in
amazon*) echo "Amazon: concise title, five scannable bullets, searchable attributes, claim-safe wording";;
shopify*) echo "Shopify/independent site: brand story, benefit blocks, FAQ, trust cues, SEO metadata";;
taobao*|taotao*) echo "Taobao: benefit-led Chinese title, scenario keywords, promo-friendly bullets";;
pinduoduo*) echo "Pinduoduo: price-value framing, group-buy angle, direct feature proof";;
tiktok*|tk*) echo "TikTok Shop: hook first, demo sequence, social proof, short CTA";;
*) echo "Marketplace: clear title, benefits, specs, search terms, buyer objections";;
esac
}
print_brief(){
echo "# $SKILL_NAME Brief"
echo "Product: $PRODUCT"
echo "Channel: $CHANNEL"
echo "Audience: $AUDIENCE"
echo "Tone: $TONE"
[ -n "$PRICE" ] && echo "Price: $PRICE"
echo "Style: $(channel_style)"
echo
echo "## Core Features"
split_csv "$FEATURES" | awk '{print "- " $0}'
echo
echo "## Search Terms"
split_csv "$KEYWORDS" | awk '{print "- " $0}'
echo
echo "## Buyer Promise"
echo "Help $AUDIENCE understand what $PRODUCT does, why it is credible, and when to buy it."
}
make_title(){
local base="$PRODUCT"
local kw; kw=$(split_csv "$KEYWORDS" | head -1)
case "$(printf '%s' "$CHANNEL" | tr '[:upper:]' '[:lower:]')" in
amazon*) echo "$base, $kw for Home Office, Adjustable and Gift Ready";;
shopify*) echo "$base for Focused Work and Better Desk Lighting";;
taobao*|taotao*) echo "$base 办公学习护眼灯 多档调光 桌面宿舍适用";;
pinduoduo*) echo "$base 高性价比护眼台灯 学生办公可折叠";;
tiktok*|tk*) echo "This $base fixes the messy desk lighting problem";;
*) echo "$base - $kw with Practical Everyday Benefits";;
esac
}
cmd_brief(){ parse_opts "$@"; print_brief; }
cmd_title(){ parse_opts "$@"; echo "# Title Options"; for i in 1 2 3 4 5; do echo "$i. $(make_title) - Option $i"; done; }
cmd_bullets(){
parse_opts "$@"; echo "# Listing Bullets for $PRODUCT"; i=1
split_csv "$FEATURES" | while read -r f; do
echo "$i. $f: explain the concrete buyer benefit, include one proof point, avoid unsupported medical or guaranteed-result claims."
i=$((i+1))
done
echo
echo "## Attribute Hints"
echo "- Material: fill from source facts"
echo "- Size: include exact dimensions when available"
echo "- Compatibility: state only verified devices or use cases"
echo "- Package: list what buyers receive"
}
cmd_compare(){
parse_opts "$@"; echo "# Channel Comparison for $PRODUCT"
for c in Amazon Shopify Taobao Pinduoduo TikTokShop IndependentSite; do
CHANNEL="$c"; echo "## $c"; echo "Title: $(make_title)"; echo "Style: $(channel_style)"; echo
done
}
cmd_audit(){
parse_opts "$@"; echo "# Audit Checklist"
local score=100
[ -n "$PRODUCT" ] || score=$((score-15))
[ -n "$FEATURES" ] || score=$((score-20))
[ -n "$KEYWORDS" ] || score=$((score-15))
echo "Score: $score/100"
echo "- Title includes product type and primary keyword"
echo "- Bullets connect each feature to a buyer benefit"
echo "- Claims are specific and supportable"
echo "- Specs include size, material, compatibility, and package contents"
echo "- CTA matches channel norms"
}
cmd_pdp(){ parse_opts "$@"; echo "# Product Detail Page"; print_brief; echo "## Sections"; echo "- Hero: $(make_title)"; echo "- Benefits grid from features"; echo "- How it works"; echo "- Reviews and trust badges"; echo "- FAQ and shipping notes"; }
cmd_seo(){ parse_opts "$@"; echo "SEO Title: $(make_title) | BytesAgain"; echo "Meta Description: Shop $PRODUCT for $AUDIENCE. Features include $(split_csv "$FEATURES" | paste -sd ', ' -)."; echo "URL Slug: $(slugify "$PRODUCT-$CHANNEL")"; }
cmd_faq(){ parse_opts "$@"; echo "# FAQ"; echo "- Who is this for? $AUDIENCE."; echo "- What problem does it solve? It addresses the main buying need behind $PRODUCT."; echo "- What should buyers check before ordering? Size, compatibility, shipping, and warranty."; echo "- What is included? List package contents from source facts."; }
cmd_hook(){ parse_opts "$@"; echo "# Hooks"; echo "1. Stop buying $PRODUCT before checking this one thing."; echo "2. If your desk setup feels wrong, this may be why."; echo "3. I tested this $PRODUCT for seven common buyer questions."; }
cmd_script(){ parse_opts "$@"; echo "# Short Video Script"; echo "0-3s: Hook with the buyer pain."; echo "3-12s: Show $PRODUCT in use."; echo "12-25s: Demonstrate top features: $FEATURES."; echo "25-35s: Compare before/after."; echo "35-45s: CTA: comment with your use case or visit product page."; }
cmd_live(){ parse_opts "$@"; echo "# Livestream Cues"; echo "- Open with use case and price anchor."; echo "- Demo one feature every 2 minutes."; echo "- Repeat shipping, guarantee, and bundle details."; echo "- Ask viewers to comment their scenario."; }
cmd_caption(){ parse_opts "$@"; echo "# Captions"; echo "- Testing a $PRODUCT for real desk setups. Would you use this?"; echo "- Three details most listings forget to explain."; echo "- Save this before you compare similar products."; }
cmd_keywords(){ parse_opts "$@"; echo "# Keyword Clusters"; for k in $(split_csv "$KEYWORDS"); do echo "## $k"; echo "- $k review"; echo "- best $k for $AUDIENCE"; echo "- $k price"; echo "- $k alternative"; done; }
cmd_rewrite(){ parse_opts "$@"; echo "# Rewritten Copy"; echo "$(make_title)"; echo; cmd_bullets --product "$PRODUCT" --features "$FEATURES" --keywords "$KEYWORDS" --channel "$CHANNEL"; }
cmd_category(){ parse_opts "$@"; echo "# Category Copy"; echo "$PRODUCT options help $AUDIENCE compare features, price, materials, and use cases before buying."; echo "Choose by primary scenario, required specs, and after-sales expectations."; }
cmd_calendar(){ parse_opts "$@"; echo "# 14-Day Ecommerce SEO Plan"; for i in $(seq 1 14); do echo "Day $i: publish one keyword-focused asset around $PRODUCT and validate search intent."; done; }
cmd_map(){ parse_opts "$@"; print_brief; echo "## Field Map"; echo "- Source facts -> title, bullets, specs, FAQ, search terms"; echo "- Target market -> tone, units, objections, compliance notes"; }
cmd_localize(){ parse_opts "$@"; echo "# Localized Copy ($TARGET, $LANG)"; echo "Title: $(make_title)"; echo "Tone: adapt to $TARGET buyer expectations; preserve factual specs."; cmd_bullets --product "$PRODUCT" --features "$FEATURES" --keywords "$KEYWORDS" --channel "$CHANNEL"; }
cmd_tone(){ parse_opts "$@"; echo "# Tone Variants"; for t in premium value technical social; do echo "## $t"; TONE="$t"; echo "$(make_title)"; done; }
cmd_compliance(){ parse_opts "$@"; echo "# Claim Safety Check"; echo "- Avoid guaranteed income, medical claims, fake scarcity, and unsupported comparisons."; echo "- Keep dimensions, materials, certifications, and compatibility factual."; echo "- Add marketplace-specific disclaimers when needed."; }
cmd_bundle(){ parse_opts "$@"; echo "# Multi-Channel Bundle"; cmd_title --product "$PRODUCT" --features "$FEATURES" --keywords "$KEYWORDS" --channel Amazon; cmd_seo --product "$PRODUCT" --features "$FEATURES" --keywords "$KEYWORDS" --channel Shopify; cmd_script --product "$PRODUCT" --features "$FEATURES" --keywords "$KEYWORDS" --channel TikTok; }
cmd_demo(){ parse_opts --product "portable blender" --channel "Amazon" --audience "busy commuters" --features "USB-C charging, 400ml cup, stainless blades, easy cleaning" --keywords "portable blender, smoothie maker, travel blender"; print_brief; echo; cmd_title; echo; cmd_bullets; echo; cmd_audit; }
usage(){ cat <<EOF
$SKILL_NAME v$VERSION
Commands: map localize tone compliance bundle demo help version
Common options: --product TEXT --channel NAME --features CSV --keywords CSV --audience TEXT --target MARKET --lang CODE
EOF
}
case "-help" in
map) shift; cmd_map "$@";;
localize) shift; cmd_localize "$@";;
tone) shift; cmd_tone "$@";;
compliance) shift; cmd_compliance "$@";;
bundle) shift; cmd_bundle "$@";;
demo) shift; cmd_demo "$@";;
help|-h|--help) usage;;
version) echo "$VERSION";;
*) err "unknown command: $1"; usage; exit 1;;
esac
Optimize ecommerce keywords and product copy. Use when building keyword maps, rewriting titles, improving category text, auditing listings, or planning searc...
---
name: "BytesAgain Ecommerce SEO Optimizer"
description: "Optimize ecommerce keywords and product copy. Use when building keyword maps, rewriting titles, improving category text, auditing listings, or planning search terms."
version: "1.0.0"
author: "BytesAgain"
homepage: "https://bytesagain.com"
source: "https://github.com/bytesagain/ai-skills"
tags: ["ecommerce", "seo", "keywords", "product-copy", "category", "listing"]
category: "ecommerce"
---
# BytesAgain Ecommerce SEO Optimizer
Optimize ecommerce keywords and product copy. It turns product facts into channel-ready ecommerce copy, audits missing fields, and formats outputs that AI agents can paste into store workflows.
## Commands
### keywords
Build keyword clusters from seed terms.
```bash
bash scripts/script.sh keywords --product "portable blender" --channel "Amazon" --features "USB-C charging,400ml cup,easy cleaning" --keywords "portable blender,smoothie maker"
```
### rewrite
Rewrite product copy with search intent.
```bash
bash scripts/script.sh rewrite --product "portable blender" --channel "Amazon" --features "USB-C charging,400ml cup,easy cleaning" --keywords "portable blender,smoothie maker"
```
### category
Generate category-page SEO copy.
```bash
bash scripts/script.sh category --product "portable blender" --channel "Amazon" --features "USB-C charging,400ml cup,easy cleaning" --keywords "portable blender,smoothie maker"
```
### audit
Audit title and description coverage.
```bash
bash scripts/script.sh audit --product "portable blender" --channel "Amazon" --features "USB-C charging,400ml cup,easy cleaning" --keywords "portable blender,smoothie maker"
```
### calendar
Create a 14-day SEO content plan.
```bash
bash scripts/script.sh calendar --product "portable blender" --channel "Amazon" --features "USB-C charging,400ml cup,easy cleaning" --keywords "portable blender,smoothie maker"
```
### demo
Print a sample ecommerce SEO pack.
```bash
bash scripts/script.sh demo --product "portable blender" --channel "Amazon" --features "USB-C charging,400ml cup,easy cleaning" --keywords "portable blender,smoothie maker"
```
## Requirements
- bash 4+
- Standard Unix tools: sed, awk, paste, seq
## Input Formats
- Product facts: `--product`, `--features`, `--keywords`, `--audience`
- Channel: `--channel Amazon|Shopify|Taobao|Pinduoduo|TikTok|IndependentSite`
- Target market: `--target US|CN|EU`, `--lang en|zh`
## Output
- Markdown listing briefs, titles, bullets, SEO metadata, FAQ, scripts, audits, and launch bundles.
## Notes
Use official marketplace policies before publishing claims. This skill drafts and audits copy; it does not upload products or ask for seller credentials.
## Feedback
https://bytesagain.com/feedback/
Powered by BytesAgain | bytesagain.com
FILE:scripts/script.sh
#!/usr/bin/env bash
set -euo pipefail
VERSION="1.0.0"
SKILL_NAME="BytesAgain Ecommerce SEO Optimizer"
FOCUS="seo"
err(){ printf 'Error: %s\n' "$*" >&2; }
slugify(){ printf '%s' "$1" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9]+/-/g;s/^-//;s/-$//'; }
trim(){ sed 's/^ *//;s/ *$//'; }
split_csv(){ printf '%s' "$1" | tr ',' '\n' | trim | sed '/^$/d'; }
PRODUCT=""; CHANNEL="marketplace"; AUDIENCE="buyers"; FEATURES=""; KEYWORDS=""; PRICE=""; TONE="clear"; LANG="en"; INPUT=""; TARGET="US"; LENGTH="medium"
parse_opts(){
while [ "$#" -gt 0 ]; do
case "$1" in
--product) PRODUCT="-"; shift 2;;
--channel) CHANNEL="-"; shift 2;;
--audience) AUDIENCE="-"; shift 2;;
--features) FEATURES="-"; shift 2;;
--keywords) KEYWORDS="-"; shift 2;;
--price) PRICE="-"; shift 2;;
--tone) TONE="-"; shift 2;;
--lang) LANG="-"; shift 2;;
--input) INPUT="-"; shift 2;;
--target) TARGET="-"; shift 2;;
--length) LENGTH="-"; shift 2;;
*) if [[ "$1" == --* ]]; then err "unknown option: $1"; return 1; else INPUT="$1"; shift; fi;;
esac
done
[ -n "$PRODUCT" ] || PRODUCT="wireless desk lamp"
[ -n "$FEATURES" ] || FEATURES="adjustable brightness, USB-C charging, foldable arm, eye comfort"
[ -n "$KEYWORDS" ] || KEYWORDS="desk lamp, study light, home office"
}
channel_style(){
case "$(printf '%s' "$CHANNEL" | tr '[:upper:]' '[:lower:]')" in
amazon*) echo "Amazon: concise title, five scannable bullets, searchable attributes, claim-safe wording";;
shopify*) echo "Shopify/independent site: brand story, benefit blocks, FAQ, trust cues, SEO metadata";;
taobao*|taotao*) echo "Taobao: benefit-led Chinese title, scenario keywords, promo-friendly bullets";;
pinduoduo*) echo "Pinduoduo: price-value framing, group-buy angle, direct feature proof";;
tiktok*|tk*) echo "TikTok Shop: hook first, demo sequence, social proof, short CTA";;
*) echo "Marketplace: clear title, benefits, specs, search terms, buyer objections";;
esac
}
print_brief(){
echo "# $SKILL_NAME Brief"
echo "Product: $PRODUCT"
echo "Channel: $CHANNEL"
echo "Audience: $AUDIENCE"
echo "Tone: $TONE"
[ -n "$PRICE" ] && echo "Price: $PRICE"
echo "Style: $(channel_style)"
echo
echo "## Core Features"
split_csv "$FEATURES" | awk '{print "- " $0}'
echo
echo "## Search Terms"
split_csv "$KEYWORDS" | awk '{print "- " $0}'
echo
echo "## Buyer Promise"
echo "Help $AUDIENCE understand what $PRODUCT does, why it is credible, and when to buy it."
}
make_title(){
local base="$PRODUCT"
local kw; kw=$(split_csv "$KEYWORDS" | head -1)
case "$(printf '%s' "$CHANNEL" | tr '[:upper:]' '[:lower:]')" in
amazon*) echo "$base, $kw for Home Office, Adjustable and Gift Ready";;
shopify*) echo "$base for Focused Work and Better Desk Lighting";;
taobao*|taotao*) echo "$base 办公学习护眼灯 多档调光 桌面宿舍适用";;
pinduoduo*) echo "$base 高性价比护眼台灯 学生办公可折叠";;
tiktok*|tk*) echo "This $base fixes the messy desk lighting problem";;
*) echo "$base - $kw with Practical Everyday Benefits";;
esac
}
cmd_brief(){ parse_opts "$@"; print_brief; }
cmd_title(){ parse_opts "$@"; echo "# Title Options"; for i in 1 2 3 4 5; do echo "$i. $(make_title) - Option $i"; done; }
cmd_bullets(){
parse_opts "$@"; echo "# Listing Bullets for $PRODUCT"; i=1
split_csv "$FEATURES" | while read -r f; do
echo "$i. $f: explain the concrete buyer benefit, include one proof point, avoid unsupported medical or guaranteed-result claims."
i=$((i+1))
done
echo
echo "## Attribute Hints"
echo "- Material: fill from source facts"
echo "- Size: include exact dimensions when available"
echo "- Compatibility: state only verified devices or use cases"
echo "- Package: list what buyers receive"
}
cmd_compare(){
parse_opts "$@"; echo "# Channel Comparison for $PRODUCT"
for c in Amazon Shopify Taobao Pinduoduo TikTokShop IndependentSite; do
CHANNEL="$c"; echo "## $c"; echo "Title: $(make_title)"; echo "Style: $(channel_style)"; echo
done
}
cmd_audit(){
parse_opts "$@"; echo "# Audit Checklist"
local score=100
[ -n "$PRODUCT" ] || score=$((score-15))
[ -n "$FEATURES" ] || score=$((score-20))
[ -n "$KEYWORDS" ] || score=$((score-15))
echo "Score: $score/100"
echo "- Title includes product type and primary keyword"
echo "- Bullets connect each feature to a buyer benefit"
echo "- Claims are specific and supportable"
echo "- Specs include size, material, compatibility, and package contents"
echo "- CTA matches channel norms"
}
cmd_pdp(){ parse_opts "$@"; echo "# Product Detail Page"; print_brief; echo "## Sections"; echo "- Hero: $(make_title)"; echo "- Benefits grid from features"; echo "- How it works"; echo "- Reviews and trust badges"; echo "- FAQ and shipping notes"; }
cmd_seo(){ parse_opts "$@"; echo "SEO Title: $(make_title) | BytesAgain"; echo "Meta Description: Shop $PRODUCT for $AUDIENCE. Features include $(split_csv "$FEATURES" | paste -sd ', ' -)."; echo "URL Slug: $(slugify "$PRODUCT-$CHANNEL")"; }
cmd_faq(){ parse_opts "$@"; echo "# FAQ"; echo "- Who is this for? $AUDIENCE."; echo "- What problem does it solve? It addresses the main buying need behind $PRODUCT."; echo "- What should buyers check before ordering? Size, compatibility, shipping, and warranty."; echo "- What is included? List package contents from source facts."; }
cmd_hook(){ parse_opts "$@"; echo "# Hooks"; echo "1. Stop buying $PRODUCT before checking this one thing."; echo "2. If your desk setup feels wrong, this may be why."; echo "3. I tested this $PRODUCT for seven common buyer questions."; }
cmd_script(){ parse_opts "$@"; echo "# Short Video Script"; echo "0-3s: Hook with the buyer pain."; echo "3-12s: Show $PRODUCT in use."; echo "12-25s: Demonstrate top features: $FEATURES."; echo "25-35s: Compare before/after."; echo "35-45s: CTA: comment with your use case or visit product page."; }
cmd_live(){ parse_opts "$@"; echo "# Livestream Cues"; echo "- Open with use case and price anchor."; echo "- Demo one feature every 2 minutes."; echo "- Repeat shipping, guarantee, and bundle details."; echo "- Ask viewers to comment their scenario."; }
cmd_caption(){ parse_opts "$@"; echo "# Captions"; echo "- Testing a $PRODUCT for real desk setups. Would you use this?"; echo "- Three details most listings forget to explain."; echo "- Save this before you compare similar products."; }
cmd_keywords(){ parse_opts "$@"; echo "# Keyword Clusters"; for k in $(split_csv "$KEYWORDS"); do echo "## $k"; echo "- $k review"; echo "- best $k for $AUDIENCE"; echo "- $k price"; echo "- $k alternative"; done; }
cmd_rewrite(){ parse_opts "$@"; echo "# Rewritten Copy"; echo "$(make_title)"; echo; cmd_bullets --product "$PRODUCT" --features "$FEATURES" --keywords "$KEYWORDS" --channel "$CHANNEL"; }
cmd_category(){ parse_opts "$@"; echo "# Category Copy"; echo "$PRODUCT options help $AUDIENCE compare features, price, materials, and use cases before buying."; echo "Choose by primary scenario, required specs, and after-sales expectations."; }
cmd_calendar(){ parse_opts "$@"; echo "# 14-Day Ecommerce SEO Plan"; for i in $(seq 1 14); do echo "Day $i: publish one keyword-focused asset around $PRODUCT and validate search intent."; done; }
cmd_map(){ parse_opts "$@"; print_brief; echo "## Field Map"; echo "- Source facts -> title, bullets, specs, FAQ, search terms"; echo "- Target market -> tone, units, objections, compliance notes"; }
cmd_localize(){ parse_opts "$@"; echo "# Localized Copy ($TARGET, $LANG)"; echo "Title: $(make_title)"; echo "Tone: adapt to $TARGET buyer expectations; preserve factual specs."; cmd_bullets --product "$PRODUCT" --features "$FEATURES" --keywords "$KEYWORDS" --channel "$CHANNEL"; }
cmd_tone(){ parse_opts "$@"; echo "# Tone Variants"; for t in premium value technical social; do echo "## $t"; TONE="$t"; echo "$(make_title)"; done; }
cmd_compliance(){ parse_opts "$@"; echo "# Claim Safety Check"; echo "- Avoid guaranteed income, medical claims, fake scarcity, and unsupported comparisons."; echo "- Keep dimensions, materials, certifications, and compatibility factual."; echo "- Add marketplace-specific disclaimers when needed."; }
cmd_bundle(){ parse_opts "$@"; echo "# Multi-Channel Bundle"; cmd_title --product "$PRODUCT" --features "$FEATURES" --keywords "$KEYWORDS" --channel Amazon; cmd_seo --product "$PRODUCT" --features "$FEATURES" --keywords "$KEYWORDS" --channel Shopify; cmd_script --product "$PRODUCT" --features "$FEATURES" --keywords "$KEYWORDS" --channel TikTok; }
cmd_demo(){ parse_opts --product "portable blender" --channel "Amazon" --audience "busy commuters" --features "USB-C charging, 400ml cup, stainless blades, easy cleaning" --keywords "portable blender, smoothie maker, travel blender"; print_brief; echo; cmd_title; echo; cmd_bullets; echo; cmd_audit; }
usage(){ cat <<EOF
$SKILL_NAME v$VERSION
Commands: keywords rewrite category audit calendar demo help version
Common options: --product TEXT --channel NAME --features CSV --keywords CSV --audience TEXT --target MARKET --lang CODE
EOF
}
case "-help" in
keywords) shift; cmd_keywords "$@";;
rewrite) shift; cmd_rewrite "$@";;
category) shift; cmd_category "$@";;
audit) shift; cmd_audit "$@";;
calendar) shift; cmd_calendar "$@";;
demo) shift; cmd_demo "$@";;
help|-h|--help) usage;;
version) echo "$VERSION";;
*) err "unknown command: $1"; usage; exit 1;;
esac
Draft TikTok Shop and short-video commerce scripts. Use when creating hooks, UGC scripts, product demos, livestream cues, captions, or creator briefs.
---
name: "BytesAgain Social Commerce Video Kit"
description: "Draft TikTok Shop and short-video commerce scripts. Use when creating hooks, UGC scripts, product demos, livestream cues, captions, or creator briefs."
version: "1.0.0"
author: "BytesAgain"
homepage: "https://bytesagain.com"
source: "https://github.com/bytesagain/ai-skills"
tags: ["ecommerce", "tiktok", "short-video", "ugc", "livestream", "social-commerce"]
category: "ecommerce"
---
# BytesAgain Social Commerce Video Kit
Draft TikTok Shop and short-video commerce scripts. It turns product facts into channel-ready ecommerce copy, audits missing fields, and formats outputs that AI agents can paste into store workflows.
## Commands
### brief
Create a creator brief.
```bash
bash scripts/script.sh brief --product "portable blender" --channel "Amazon" --features "USB-C charging,400ml cup,easy cleaning" --keywords "portable blender,smoothie maker"
```
### hook
Generate opening hooks.
```bash
bash scripts/script.sh hook --product "portable blender" --channel "Amazon" --features "USB-C charging,400ml cup,easy cleaning" --keywords "portable blender,smoothie maker"
```
### script
Write a 30-60 second product video script.
```bash
bash scripts/script.sh script --product "portable blender" --channel "Amazon" --features "USB-C charging,400ml cup,easy cleaning" --keywords "portable blender,smoothie maker"
```
### live
Generate livestream selling cues.
```bash
bash scripts/script.sh live --product "portable blender" --channel "Amazon" --features "USB-C charging,400ml cup,easy cleaning" --keywords "portable blender,smoothie maker"
```
### caption
Write captions and CTA variants.
```bash
bash scripts/script.sh caption --product "portable blender" --channel "Amazon" --features "USB-C charging,400ml cup,easy cleaning" --keywords "portable blender,smoothie maker"
```
### demo
Print a sample TikTok Shop launch pack.
```bash
bash scripts/script.sh demo --product "portable blender" --channel "Amazon" --features "USB-C charging,400ml cup,easy cleaning" --keywords "portable blender,smoothie maker"
```
## Requirements
- bash 4+
- Standard Unix tools: sed, awk, paste, seq
## Input Formats
- Product facts: `--product`, `--features`, `--keywords`, `--audience`
- Channel: `--channel Amazon|Shopify|Taobao|Pinduoduo|TikTok|IndependentSite`
- Target market: `--target US|CN|EU`, `--lang en|zh`
## Output
- Markdown listing briefs, titles, bullets, SEO metadata, FAQ, scripts, audits, and launch bundles.
## Notes
Use official marketplace policies before publishing claims. This skill drafts and audits copy; it does not upload products or ask for seller credentials.
## Feedback
https://bytesagain.com/feedback/
Powered by BytesAgain | bytesagain.com
FILE:scripts/script.sh
#!/usr/bin/env bash
set -euo pipefail
VERSION="1.0.0"
SKILL_NAME="BytesAgain Social Commerce Video Kit"
FOCUS="social"
err(){ printf 'Error: %s\n' "$*" >&2; }
slugify(){ printf '%s' "$1" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9]+/-/g;s/^-//;s/-$//'; }
trim(){ sed 's/^ *//;s/ *$//'; }
split_csv(){ printf '%s' "$1" | tr ',' '\n' | trim | sed '/^$/d'; }
PRODUCT=""; CHANNEL="marketplace"; AUDIENCE="buyers"; FEATURES=""; KEYWORDS=""; PRICE=""; TONE="clear"; LANG="en"; INPUT=""; TARGET="US"; LENGTH="medium"
parse_opts(){
while [ "$#" -gt 0 ]; do
case "$1" in
--product) PRODUCT="-"; shift 2;;
--channel) CHANNEL="-"; shift 2;;
--audience) AUDIENCE="-"; shift 2;;
--features) FEATURES="-"; shift 2;;
--keywords) KEYWORDS="-"; shift 2;;
--price) PRICE="-"; shift 2;;
--tone) TONE="-"; shift 2;;
--lang) LANG="-"; shift 2;;
--input) INPUT="-"; shift 2;;
--target) TARGET="-"; shift 2;;
--length) LENGTH="-"; shift 2;;
*) if [[ "$1" == --* ]]; then err "unknown option: $1"; return 1; else INPUT="$1"; shift; fi;;
esac
done
[ -n "$PRODUCT" ] || PRODUCT="wireless desk lamp"
[ -n "$FEATURES" ] || FEATURES="adjustable brightness, USB-C charging, foldable arm, eye comfort"
[ -n "$KEYWORDS" ] || KEYWORDS="desk lamp, study light, home office"
}
channel_style(){
case "$(printf '%s' "$CHANNEL" | tr '[:upper:]' '[:lower:]')" in
amazon*) echo "Amazon: concise title, five scannable bullets, searchable attributes, claim-safe wording";;
shopify*) echo "Shopify/independent site: brand story, benefit blocks, FAQ, trust cues, SEO metadata";;
taobao*|taotao*) echo "Taobao: benefit-led Chinese title, scenario keywords, promo-friendly bullets";;
pinduoduo*) echo "Pinduoduo: price-value framing, group-buy angle, direct feature proof";;
tiktok*|tk*) echo "TikTok Shop: hook first, demo sequence, social proof, short CTA";;
*) echo "Marketplace: clear title, benefits, specs, search terms, buyer objections";;
esac
}
print_brief(){
echo "# $SKILL_NAME Brief"
echo "Product: $PRODUCT"
echo "Channel: $CHANNEL"
echo "Audience: $AUDIENCE"
echo "Tone: $TONE"
[ -n "$PRICE" ] && echo "Price: $PRICE"
echo "Style: $(channel_style)"
echo
echo "## Core Features"
split_csv "$FEATURES" | awk '{print "- " $0}'
echo
echo "## Search Terms"
split_csv "$KEYWORDS" | awk '{print "- " $0}'
echo
echo "## Buyer Promise"
echo "Help $AUDIENCE understand what $PRODUCT does, why it is credible, and when to buy it."
}
make_title(){
local base="$PRODUCT"
local kw; kw=$(split_csv "$KEYWORDS" | head -1)
case "$(printf '%s' "$CHANNEL" | tr '[:upper:]' '[:lower:]')" in
amazon*) echo "$base, $kw for Home Office, Adjustable and Gift Ready";;
shopify*) echo "$base for Focused Work and Better Desk Lighting";;
taobao*|taotao*) echo "$base 办公学习护眼灯 多档调光 桌面宿舍适用";;
pinduoduo*) echo "$base 高性价比护眼台灯 学生办公可折叠";;
tiktok*|tk*) echo "This $base fixes the messy desk lighting problem";;
*) echo "$base - $kw with Practical Everyday Benefits";;
esac
}
cmd_brief(){ parse_opts "$@"; print_brief; }
cmd_title(){ parse_opts "$@"; echo "# Title Options"; for i in 1 2 3 4 5; do echo "$i. $(make_title) - Option $i"; done; }
cmd_bullets(){
parse_opts "$@"; echo "# Listing Bullets for $PRODUCT"; i=1
split_csv "$FEATURES" | while read -r f; do
echo "$i. $f: explain the concrete buyer benefit, include one proof point, avoid unsupported medical or guaranteed-result claims."
i=$((i+1))
done
echo
echo "## Attribute Hints"
echo "- Material: fill from source facts"
echo "- Size: include exact dimensions when available"
echo "- Compatibility: state only verified devices or use cases"
echo "- Package: list what buyers receive"
}
cmd_compare(){
parse_opts "$@"; echo "# Channel Comparison for $PRODUCT"
for c in Amazon Shopify Taobao Pinduoduo TikTokShop IndependentSite; do
CHANNEL="$c"; echo "## $c"; echo "Title: $(make_title)"; echo "Style: $(channel_style)"; echo
done
}
cmd_audit(){
parse_opts "$@"; echo "# Audit Checklist"
local score=100
[ -n "$PRODUCT" ] || score=$((score-15))
[ -n "$FEATURES" ] || score=$((score-20))
[ -n "$KEYWORDS" ] || score=$((score-15))
echo "Score: $score/100"
echo "- Title includes product type and primary keyword"
echo "- Bullets connect each feature to a buyer benefit"
echo "- Claims are specific and supportable"
echo "- Specs include size, material, compatibility, and package contents"
echo "- CTA matches channel norms"
}
cmd_pdp(){ parse_opts "$@"; echo "# Product Detail Page"; print_brief; echo "## Sections"; echo "- Hero: $(make_title)"; echo "- Benefits grid from features"; echo "- How it works"; echo "- Reviews and trust badges"; echo "- FAQ and shipping notes"; }
cmd_seo(){ parse_opts "$@"; echo "SEO Title: $(make_title) | BytesAgain"; echo "Meta Description: Shop $PRODUCT for $AUDIENCE. Features include $(split_csv "$FEATURES" | paste -sd ', ' -)."; echo "URL Slug: $(slugify "$PRODUCT-$CHANNEL")"; }
cmd_faq(){ parse_opts "$@"; echo "# FAQ"; echo "- Who is this for? $AUDIENCE."; echo "- What problem does it solve? It addresses the main buying need behind $PRODUCT."; echo "- What should buyers check before ordering? Size, compatibility, shipping, and warranty."; echo "- What is included? List package contents from source facts."; }
cmd_hook(){ parse_opts "$@"; echo "# Hooks"; echo "1. Stop buying $PRODUCT before checking this one thing."; echo "2. If your desk setup feels wrong, this may be why."; echo "3. I tested this $PRODUCT for seven common buyer questions."; }
cmd_script(){ parse_opts "$@"; echo "# Short Video Script"; echo "0-3s: Hook with the buyer pain."; echo "3-12s: Show $PRODUCT in use."; echo "12-25s: Demonstrate top features: $FEATURES."; echo "25-35s: Compare before/after."; echo "35-45s: CTA: comment with your use case or visit product page."; }
cmd_live(){ parse_opts "$@"; echo "# Livestream Cues"; echo "- Open with use case and price anchor."; echo "- Demo one feature every 2 minutes."; echo "- Repeat shipping, guarantee, and bundle details."; echo "- Ask viewers to comment their scenario."; }
cmd_caption(){ parse_opts "$@"; echo "# Captions"; echo "- Testing a $PRODUCT for real desk setups. Would you use this?"; echo "- Three details most listings forget to explain."; echo "- Save this before you compare similar products."; }
cmd_keywords(){ parse_opts "$@"; echo "# Keyword Clusters"; for k in $(split_csv "$KEYWORDS"); do echo "## $k"; echo "- $k review"; echo "- best $k for $AUDIENCE"; echo "- $k price"; echo "- $k alternative"; done; }
cmd_rewrite(){ parse_opts "$@"; echo "# Rewritten Copy"; echo "$(make_title)"; echo; cmd_bullets --product "$PRODUCT" --features "$FEATURES" --keywords "$KEYWORDS" --channel "$CHANNEL"; }
cmd_category(){ parse_opts "$@"; echo "# Category Copy"; echo "$PRODUCT options help $AUDIENCE compare features, price, materials, and use cases before buying."; echo "Choose by primary scenario, required specs, and after-sales expectations."; }
cmd_calendar(){ parse_opts "$@"; echo "# 14-Day Ecommerce SEO Plan"; for i in $(seq 1 14); do echo "Day $i: publish one keyword-focused asset around $PRODUCT and validate search intent."; done; }
cmd_map(){ parse_opts "$@"; print_brief; echo "## Field Map"; echo "- Source facts -> title, bullets, specs, FAQ, search terms"; echo "- Target market -> tone, units, objections, compliance notes"; }
cmd_localize(){ parse_opts "$@"; echo "# Localized Copy ($TARGET, $LANG)"; echo "Title: $(make_title)"; echo "Tone: adapt to $TARGET buyer expectations; preserve factual specs."; cmd_bullets --product "$PRODUCT" --features "$FEATURES" --keywords "$KEYWORDS" --channel "$CHANNEL"; }
cmd_tone(){ parse_opts "$@"; echo "# Tone Variants"; for t in premium value technical social; do echo "## $t"; TONE="$t"; echo "$(make_title)"; done; }
cmd_compliance(){ parse_opts "$@"; echo "# Claim Safety Check"; echo "- Avoid guaranteed income, medical claims, fake scarcity, and unsupported comparisons."; echo "- Keep dimensions, materials, certifications, and compatibility factual."; echo "- Add marketplace-specific disclaimers when needed."; }
cmd_bundle(){ parse_opts "$@"; echo "# Multi-Channel Bundle"; cmd_title --product "$PRODUCT" --features "$FEATURES" --keywords "$KEYWORDS" --channel Amazon; cmd_seo --product "$PRODUCT" --features "$FEATURES" --keywords "$KEYWORDS" --channel Shopify; cmd_script --product "$PRODUCT" --features "$FEATURES" --keywords "$KEYWORDS" --channel TikTok; }
cmd_demo(){ parse_opts --product "portable blender" --channel "Amazon" --audience "busy commuters" --features "USB-C charging, 400ml cup, stainless blades, easy cleaning" --keywords "portable blender, smoothie maker, travel blender"; print_brief; echo; cmd_title; echo; cmd_bullets; echo; cmd_audit; }
usage(){ cat <<EOF
$SKILL_NAME v$VERSION
Commands: brief hook script live caption demo help version
Common options: --product TEXT --channel NAME --features CSV --keywords CSV --audience TEXT --target MARKET --lang CODE
EOF
}
case "-help" in
brief) shift; cmd_brief "$@";;
hook) shift; cmd_hook "$@";;
script) shift; cmd_script "$@";;
live) shift; cmd_live "$@";;
caption) shift; cmd_caption "$@";;
demo) shift; cmd_demo "$@";;
help|-h|--help) usage;;
version) echo "$VERSION";;
*) err "unknown command: $1"; usage; exit 1;;
esac
Build product pages for Shopify-style stores and independent sites. Use when drafting PDP sections, SEO metadata, FAQ blocks, trust badges, and conversion copy.
---
name: "BytesAgain Storefront Page Kit"
description: "Build product pages for Shopify-style stores and independent sites. Use when drafting PDP sections, SEO metadata, FAQ blocks, trust badges, and conversion copy."
version: "1.0.0"
author: "BytesAgain"
homepage: "https://bytesagain.com"
source: "https://github.com/bytesagain/ai-skills"
tags: ["ecommerce", "storefront", "shopify", "independent-site", "product-page", "seo", "conversion"]
category: "ecommerce"
---
# BytesAgain Storefront Page Kit
Build product pages for Shopify-style stores and independent sites. It turns product facts into channel-ready ecommerce copy, audits missing fields, and formats outputs that AI agents can paste into store workflows.
## Commands
### brief
Create a product page brief.
```bash
bash scripts/script.sh brief --product "portable blender" --channel "Amazon" --features "USB-C charging,400ml cup,easy cleaning" --keywords "portable blender,smoothie maker"
```
### pdp
Generate a product detail page outline.
```bash
bash scripts/script.sh pdp --product "portable blender" --channel "Amazon" --features "USB-C charging,400ml cup,easy cleaning" --keywords "portable blender,smoothie maker"
```
### seo
Write SEO title, description, and URL slug.
```bash
bash scripts/script.sh seo --product "portable blender" --channel "Amazon" --features "USB-C charging,400ml cup,easy cleaning" --keywords "portable blender,smoothie maker"
```
### faq
Generate buyer FAQ and objection handling.
```bash
bash scripts/script.sh faq --product "portable blender" --channel "Amazon" --features "USB-C charging,400ml cup,easy cleaning" --keywords "portable blender,smoothie maker"
```
### audit
Check a product page for missing conversion elements.
```bash
bash scripts/script.sh audit --product "portable blender" --channel "Amazon" --features "USB-C charging,400ml cup,easy cleaning" --keywords "portable blender,smoothie maker"
```
### demo
Print a complete storefront page pack.
```bash
bash scripts/script.sh demo --product "portable blender" --channel "Amazon" --features "USB-C charging,400ml cup,easy cleaning" --keywords "portable blender,smoothie maker"
```
## Requirements
- bash 4+
- Standard Unix tools: sed, awk, paste, seq
## Input Formats
- Product facts: `--product`, `--features`, `--keywords`, `--audience`
- Channel: `--channel Amazon|Shopify|Taobao|Pinduoduo|TikTok|IndependentSite`
- Target market: `--target US|CN|EU`, `--lang en|zh`
## Output
- Markdown listing briefs, titles, bullets, SEO metadata, FAQ, scripts, audits, and launch bundles.
## Notes
Use official marketplace policies before publishing claims. This skill drafts and audits copy; it does not upload products or ask for seller credentials.
## Feedback
https://bytesagain.com/feedback/
Powered by BytesAgain | bytesagain.com
FILE:scripts/script.sh
#!/usr/bin/env bash
set -euo pipefail
VERSION="1.0.0"
SKILL_NAME="BytesAgain Storefront Page Kit"
FOCUS="storefront"
err(){ printf 'Error: %s\n' "$*" >&2; }
slugify(){ printf '%s' "$1" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9]+/-/g;s/^-//;s/-$//'; }
trim(){ sed 's/^ *//;s/ *$//'; }
split_csv(){ printf '%s' "$1" | tr ',' '\n' | trim | sed '/^$/d'; }
PRODUCT=""; CHANNEL="marketplace"; AUDIENCE="buyers"; FEATURES=""; KEYWORDS=""; PRICE=""; TONE="clear"; LANG="en"; INPUT=""; TARGET="US"; LENGTH="medium"
parse_opts(){
while [ "$#" -gt 0 ]; do
case "$1" in
--product) PRODUCT="-"; shift 2;;
--channel) CHANNEL="-"; shift 2;;
--audience) AUDIENCE="-"; shift 2;;
--features) FEATURES="-"; shift 2;;
--keywords) KEYWORDS="-"; shift 2;;
--price) PRICE="-"; shift 2;;
--tone) TONE="-"; shift 2;;
--lang) LANG="-"; shift 2;;
--input) INPUT="-"; shift 2;;
--target) TARGET="-"; shift 2;;
--length) LENGTH="-"; shift 2;;
*) if [[ "$1" == --* ]]; then err "unknown option: $1"; return 1; else INPUT="$1"; shift; fi;;
esac
done
[ -n "$PRODUCT" ] || PRODUCT="wireless desk lamp"
[ -n "$FEATURES" ] || FEATURES="adjustable brightness, USB-C charging, foldable arm, eye comfort"
[ -n "$KEYWORDS" ] || KEYWORDS="desk lamp, study light, home office"
}
channel_style(){
case "$(printf '%s' "$CHANNEL" | tr '[:upper:]' '[:lower:]')" in
amazon*) echo "Amazon: concise title, five scannable bullets, searchable attributes, claim-safe wording";;
shopify*) echo "Shopify/independent site: brand story, benefit blocks, FAQ, trust cues, SEO metadata";;
taobao*|taotao*) echo "Taobao: benefit-led Chinese title, scenario keywords, promo-friendly bullets";;
pinduoduo*) echo "Pinduoduo: price-value framing, group-buy angle, direct feature proof";;
tiktok*|tk*) echo "TikTok Shop: hook first, demo sequence, social proof, short CTA";;
*) echo "Marketplace: clear title, benefits, specs, search terms, buyer objections";;
esac
}
print_brief(){
echo "# $SKILL_NAME Brief"
echo "Product: $PRODUCT"
echo "Channel: $CHANNEL"
echo "Audience: $AUDIENCE"
echo "Tone: $TONE"
[ -n "$PRICE" ] && echo "Price: $PRICE"
echo "Style: $(channel_style)"
echo
echo "## Core Features"
split_csv "$FEATURES" | awk '{print "- " $0}'
echo
echo "## Search Terms"
split_csv "$KEYWORDS" | awk '{print "- " $0}'
echo
echo "## Buyer Promise"
echo "Help $AUDIENCE understand what $PRODUCT does, why it is credible, and when to buy it."
}
make_title(){
local base="$PRODUCT"
local kw; kw=$(split_csv "$KEYWORDS" | head -1)
case "$(printf '%s' "$CHANNEL" | tr '[:upper:]' '[:lower:]')" in
amazon*) echo "$base, $kw for Home Office, Adjustable and Gift Ready";;
shopify*) echo "$base for Focused Work and Better Desk Lighting";;
taobao*|taotao*) echo "$base 办公学习护眼灯 多档调光 桌面宿舍适用";;
pinduoduo*) echo "$base 高性价比护眼台灯 学生办公可折叠";;
tiktok*|tk*) echo "This $base fixes the messy desk lighting problem";;
*) echo "$base - $kw with Practical Everyday Benefits";;
esac
}
cmd_brief(){ parse_opts "$@"; print_brief; }
cmd_title(){ parse_opts "$@"; echo "# Title Options"; for i in 1 2 3 4 5; do echo "$i. $(make_title) - Option $i"; done; }
cmd_bullets(){
parse_opts "$@"; echo "# Listing Bullets for $PRODUCT"; i=1
split_csv "$FEATURES" | while read -r f; do
echo "$i. $f: explain the concrete buyer benefit, include one proof point, avoid unsupported medical or guaranteed-result claims."
i=$((i+1))
done
echo
echo "## Attribute Hints"
echo "- Material: fill from source facts"
echo "- Size: include exact dimensions when available"
echo "- Compatibility: state only verified devices or use cases"
echo "- Package: list what buyers receive"
}
cmd_compare(){
parse_opts "$@"; echo "# Channel Comparison for $PRODUCT"
for c in Amazon Shopify Taobao Pinduoduo TikTokShop IndependentSite; do
CHANNEL="$c"; echo "## $c"; echo "Title: $(make_title)"; echo "Style: $(channel_style)"; echo
done
}
cmd_audit(){
parse_opts "$@"; echo "# Audit Checklist"
local score=100
[ -n "$PRODUCT" ] || score=$((score-15))
[ -n "$FEATURES" ] || score=$((score-20))
[ -n "$KEYWORDS" ] || score=$((score-15))
echo "Score: $score/100"
echo "- Title includes product type and primary keyword"
echo "- Bullets connect each feature to a buyer benefit"
echo "- Claims are specific and supportable"
echo "- Specs include size, material, compatibility, and package contents"
echo "- CTA matches channel norms"
}
cmd_pdp(){ parse_opts "$@"; echo "# Product Detail Page"; print_brief; echo "## Sections"; echo "- Hero: $(make_title)"; echo "- Benefits grid from features"; echo "- How it works"; echo "- Reviews and trust badges"; echo "- FAQ and shipping notes"; }
cmd_seo(){ parse_opts "$@"; echo "SEO Title: $(make_title) | BytesAgain"; echo "Meta Description: Shop $PRODUCT for $AUDIENCE. Features include $(split_csv "$FEATURES" | paste -sd ', ' -)."; echo "URL Slug: $(slugify "$PRODUCT-$CHANNEL")"; }
cmd_faq(){ parse_opts "$@"; echo "# FAQ"; echo "- Who is this for? $AUDIENCE."; echo "- What problem does it solve? It addresses the main buying need behind $PRODUCT."; echo "- What should buyers check before ordering? Size, compatibility, shipping, and warranty."; echo "- What is included? List package contents from source facts."; }
cmd_hook(){ parse_opts "$@"; echo "# Hooks"; echo "1. Stop buying $PRODUCT before checking this one thing."; echo "2. If your desk setup feels wrong, this may be why."; echo "3. I tested this $PRODUCT for seven common buyer questions."; }
cmd_script(){ parse_opts "$@"; echo "# Short Video Script"; echo "0-3s: Hook with the buyer pain."; echo "3-12s: Show $PRODUCT in use."; echo "12-25s: Demonstrate top features: $FEATURES."; echo "25-35s: Compare before/after."; echo "35-45s: CTA: comment with your use case or visit product page."; }
cmd_live(){ parse_opts "$@"; echo "# Livestream Cues"; echo "- Open with use case and price anchor."; echo "- Demo one feature every 2 minutes."; echo "- Repeat shipping, guarantee, and bundle details."; echo "- Ask viewers to comment their scenario."; }
cmd_caption(){ parse_opts "$@"; echo "# Captions"; echo "- Testing a $PRODUCT for real desk setups. Would you use this?"; echo "- Three details most listings forget to explain."; echo "- Save this before you compare similar products."; }
cmd_keywords(){ parse_opts "$@"; echo "# Keyword Clusters"; for k in $(split_csv "$KEYWORDS"); do echo "## $k"; echo "- $k review"; echo "- best $k for $AUDIENCE"; echo "- $k price"; echo "- $k alternative"; done; }
cmd_rewrite(){ parse_opts "$@"; echo "# Rewritten Copy"; echo "$(make_title)"; echo; cmd_bullets --product "$PRODUCT" --features "$FEATURES" --keywords "$KEYWORDS" --channel "$CHANNEL"; }
cmd_category(){ parse_opts "$@"; echo "# Category Copy"; echo "$PRODUCT options help $AUDIENCE compare features, price, materials, and use cases before buying."; echo "Choose by primary scenario, required specs, and after-sales expectations."; }
cmd_calendar(){ parse_opts "$@"; echo "# 14-Day Ecommerce SEO Plan"; for i in $(seq 1 14); do echo "Day $i: publish one keyword-focused asset around $PRODUCT and validate search intent."; done; }
cmd_map(){ parse_opts "$@"; print_brief; echo "## Field Map"; echo "- Source facts -> title, bullets, specs, FAQ, search terms"; echo "- Target market -> tone, units, objections, compliance notes"; }
cmd_localize(){ parse_opts "$@"; echo "# Localized Copy ($TARGET, $LANG)"; echo "Title: $(make_title)"; echo "Tone: adapt to $TARGET buyer expectations; preserve factual specs."; cmd_bullets --product "$PRODUCT" --features "$FEATURES" --keywords "$KEYWORDS" --channel "$CHANNEL"; }
cmd_tone(){ parse_opts "$@"; echo "# Tone Variants"; for t in premium value technical social; do echo "## $t"; TONE="$t"; echo "$(make_title)"; done; }
cmd_compliance(){ parse_opts "$@"; echo "# Claim Safety Check"; echo "- Avoid guaranteed income, medical claims, fake scarcity, and unsupported comparisons."; echo "- Keep dimensions, materials, certifications, and compatibility factual."; echo "- Add marketplace-specific disclaimers when needed."; }
cmd_bundle(){ parse_opts "$@"; echo "# Multi-Channel Bundle"; cmd_title --product "$PRODUCT" --features "$FEATURES" --keywords "$KEYWORDS" --channel Amazon; cmd_seo --product "$PRODUCT" --features "$FEATURES" --keywords "$KEYWORDS" --channel Shopify; cmd_script --product "$PRODUCT" --features "$FEATURES" --keywords "$KEYWORDS" --channel TikTok; }
cmd_demo(){ parse_opts --product "portable blender" --channel "Amazon" --audience "busy commuters" --features "USB-C charging, 400ml cup, stainless blades, easy cleaning" --keywords "portable blender, smoothie maker, travel blender"; print_brief; echo; cmd_title; echo; cmd_bullets; echo; cmd_audit; }
usage(){ cat <<EOF
$SKILL_NAME v$VERSION
Commands: brief pdp seo faq audit demo help version
Common options: --product TEXT --channel NAME --features CSV --keywords CSV --audience TEXT --target MARKET --lang CODE
EOF
}
case "-help" in
brief) shift; cmd_brief "$@";;
pdp) shift; cmd_pdp "$@";;
seo) shift; cmd_seo "$@";;
faq) shift; cmd_faq "$@";;
audit) shift; cmd_audit "$@";;
demo) shift; cmd_demo "$@";;
help|-h|--help) usage;;
version) echo "$VERSION";;
*) err "unknown command: $1"; usage; exit 1;;
esac
Generate marketplace listings and SEO copy. Use when writing Amazon, Taobao, Pinduoduo, Shopee, or marketplace product titles, bullets, attributes, and QA ch...
---
name: "BytesAgain Marketplace Listing Lab"
description: "Generate marketplace listings and SEO copy. Use when writing Amazon, Taobao, Pinduoduo, Shopee, or marketplace product titles, bullets, attributes, and QA checks."
version: "1.0.0"
author: "BytesAgain"
homepage: "https://bytesagain.com"
source: "https://github.com/bytesagain/ai-skills"
tags: ["ecommerce", "marketplace", "amazon", "taobao", "pinduoduo", "listing", "seo"]
category: "ecommerce"
---
# BytesAgain Marketplace Listing Lab
Generate marketplace listings and SEO copy. It turns product facts into channel-ready ecommerce copy, audits missing fields, and formats outputs that AI agents can paste into store workflows.
## Commands
### brief
Create a listing brief from product facts.
```bash
bash scripts/script.sh brief --product "portable blender" --channel "Amazon" --features "USB-C charging,400ml cup,easy cleaning" --keywords "portable blender,smoothie maker"
```
### title
Generate channel-specific product titles.
```bash
bash scripts/script.sh title --product "portable blender" --channel "Amazon" --features "USB-C charging,400ml cup,easy cleaning" --keywords "portable blender,smoothie maker"
```
### bullets
Write benefits, bullets, and attributes.
```bash
bash scripts/script.sh bullets --product "portable blender" --channel "Amazon" --features "USB-C charging,400ml cup,easy cleaning" --keywords "portable blender,smoothie maker"
```
### compare
Compare copy across Amazon/Taobao/Pinduoduo styles.
```bash
bash scripts/script.sh compare --product "portable blender" --channel "Amazon" --features "USB-C charging,400ml cup,easy cleaning" --keywords "portable blender,smoothie maker"
```
### audit
Check a listing for missing fields and risk words.
```bash
bash scripts/script.sh audit --product "portable blender" --channel "Amazon" --features "USB-C charging,400ml cup,easy cleaning" --keywords "portable blender,smoothie maker"
```
### demo
Print a sample cross-marketplace listing pack.
```bash
bash scripts/script.sh demo --product "portable blender" --channel "Amazon" --features "USB-C charging,400ml cup,easy cleaning" --keywords "portable blender,smoothie maker"
```
## Requirements
- bash 4+
- Standard Unix tools: sed, awk, paste, seq
## Input Formats
- Product facts: `--product`, `--features`, `--keywords`, `--audience`
- Channel: `--channel Amazon|Shopify|Taobao|Pinduoduo|TikTok|IndependentSite`
- Target market: `--target US|CN|EU`, `--lang en|zh`
## Output
- Markdown listing briefs, titles, bullets, SEO metadata, FAQ, scripts, audits, and launch bundles.
## Notes
Use official marketplace policies before publishing claims. This skill drafts and audits copy; it does not upload products or ask for seller credentials.
## Feedback
https://bytesagain.com/feedback/
Powered by BytesAgain | bytesagain.com
FILE:scripts/script.sh
#!/usr/bin/env bash
set -euo pipefail
VERSION="1.0.0"
SKILL_NAME="BytesAgain Marketplace Listing Lab"
FOCUS="marketplace"
err(){ printf 'Error: %s\n' "$*" >&2; }
slugify(){ printf '%s' "$1" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9]+/-/g;s/^-//;s/-$//'; }
trim(){ sed 's/^ *//;s/ *$//'; }
split_csv(){ printf '%s' "$1" | tr ',' '\n' | trim | sed '/^$/d'; }
PRODUCT=""; CHANNEL="marketplace"; AUDIENCE="buyers"; FEATURES=""; KEYWORDS=""; PRICE=""; TONE="clear"; LANG="en"; INPUT=""; TARGET="US"; LENGTH="medium"
parse_opts(){
while [ "$#" -gt 0 ]; do
case "$1" in
--product) PRODUCT="-"; shift 2;;
--channel) CHANNEL="-"; shift 2;;
--audience) AUDIENCE="-"; shift 2;;
--features) FEATURES="-"; shift 2;;
--keywords) KEYWORDS="-"; shift 2;;
--price) PRICE="-"; shift 2;;
--tone) TONE="-"; shift 2;;
--lang) LANG="-"; shift 2;;
--input) INPUT="-"; shift 2;;
--target) TARGET="-"; shift 2;;
--length) LENGTH="-"; shift 2;;
*) if [[ "$1" == --* ]]; then err "unknown option: $1"; return 1; else INPUT="$1"; shift; fi;;
esac
done
[ -n "$PRODUCT" ] || PRODUCT="wireless desk lamp"
[ -n "$FEATURES" ] || FEATURES="adjustable brightness, USB-C charging, foldable arm, eye comfort"
[ -n "$KEYWORDS" ] || KEYWORDS="desk lamp, study light, home office"
}
channel_style(){
case "$(printf '%s' "$CHANNEL" | tr '[:upper:]' '[:lower:]')" in
amazon*) echo "Amazon: concise title, five scannable bullets, searchable attributes, claim-safe wording";;
shopify*) echo "Shopify/independent site: brand story, benefit blocks, FAQ, trust cues, SEO metadata";;
taobao*|taotao*) echo "Taobao: benefit-led Chinese title, scenario keywords, promo-friendly bullets";;
pinduoduo*) echo "Pinduoduo: price-value framing, group-buy angle, direct feature proof";;
tiktok*|tk*) echo "TikTok Shop: hook first, demo sequence, social proof, short CTA";;
*) echo "Marketplace: clear title, benefits, specs, search terms, buyer objections";;
esac
}
print_brief(){
echo "# $SKILL_NAME Brief"
echo "Product: $PRODUCT"
echo "Channel: $CHANNEL"
echo "Audience: $AUDIENCE"
echo "Tone: $TONE"
[ -n "$PRICE" ] && echo "Price: $PRICE"
echo "Style: $(channel_style)"
echo
echo "## Core Features"
split_csv "$FEATURES" | awk '{print "- " $0}'
echo
echo "## Search Terms"
split_csv "$KEYWORDS" | awk '{print "- " $0}'
echo
echo "## Buyer Promise"
echo "Help $AUDIENCE understand what $PRODUCT does, why it is credible, and when to buy it."
}
make_title(){
local base="$PRODUCT"
local kw; kw=$(split_csv "$KEYWORDS" | head -1)
case "$(printf '%s' "$CHANNEL" | tr '[:upper:]' '[:lower:]')" in
amazon*) echo "$base, $kw for Home Office, Adjustable and Gift Ready";;
shopify*) echo "$base for Focused Work and Better Desk Lighting";;
taobao*|taotao*) echo "$base 办公学习护眼灯 多档调光 桌面宿舍适用";;
pinduoduo*) echo "$base 高性价比护眼台灯 学生办公可折叠";;
tiktok*|tk*) echo "This $base fixes the messy desk lighting problem";;
*) echo "$base - $kw with Practical Everyday Benefits";;
esac
}
cmd_brief(){ parse_opts "$@"; print_brief; }
cmd_title(){ parse_opts "$@"; echo "# Title Options"; for i in 1 2 3 4 5; do echo "$i. $(make_title) - Option $i"; done; }
cmd_bullets(){
parse_opts "$@"; echo "# Listing Bullets for $PRODUCT"; i=1
split_csv "$FEATURES" | while read -r f; do
echo "$i. $f: explain the concrete buyer benefit, include one proof point, avoid unsupported medical or guaranteed-result claims."
i=$((i+1))
done
echo
echo "## Attribute Hints"
echo "- Material: fill from source facts"
echo "- Size: include exact dimensions when available"
echo "- Compatibility: state only verified devices or use cases"
echo "- Package: list what buyers receive"
}
cmd_compare(){
parse_opts "$@"; echo "# Channel Comparison for $PRODUCT"
for c in Amazon Shopify Taobao Pinduoduo TikTokShop IndependentSite; do
CHANNEL="$c"; echo "## $c"; echo "Title: $(make_title)"; echo "Style: $(channel_style)"; echo
done
}
cmd_audit(){
parse_opts "$@"; echo "# Audit Checklist"
local score=100
[ -n "$PRODUCT" ] || score=$((score-15))
[ -n "$FEATURES" ] || score=$((score-20))
[ -n "$KEYWORDS" ] || score=$((score-15))
echo "Score: $score/100"
echo "- Title includes product type and primary keyword"
echo "- Bullets connect each feature to a buyer benefit"
echo "- Claims are specific and supportable"
echo "- Specs include size, material, compatibility, and package contents"
echo "- CTA matches channel norms"
}
cmd_pdp(){ parse_opts "$@"; echo "# Product Detail Page"; print_brief; echo "## Sections"; echo "- Hero: $(make_title)"; echo "- Benefits grid from features"; echo "- How it works"; echo "- Reviews and trust badges"; echo "- FAQ and shipping notes"; }
cmd_seo(){ parse_opts "$@"; echo "SEO Title: $(make_title) | BytesAgain"; echo "Meta Description: Shop $PRODUCT for $AUDIENCE. Features include $(split_csv "$FEATURES" | paste -sd ', ' -)."; echo "URL Slug: $(slugify "$PRODUCT-$CHANNEL")"; }
cmd_faq(){ parse_opts "$@"; echo "# FAQ"; echo "- Who is this for? $AUDIENCE."; echo "- What problem does it solve? It addresses the main buying need behind $PRODUCT."; echo "- What should buyers check before ordering? Size, compatibility, shipping, and warranty."; echo "- What is included? List package contents from source facts."; }
cmd_hook(){ parse_opts "$@"; echo "# Hooks"; echo "1. Stop buying $PRODUCT before checking this one thing."; echo "2. If your desk setup feels wrong, this may be why."; echo "3. I tested this $PRODUCT for seven common buyer questions."; }
cmd_script(){ parse_opts "$@"; echo "# Short Video Script"; echo "0-3s: Hook with the buyer pain."; echo "3-12s: Show $PRODUCT in use."; echo "12-25s: Demonstrate top features: $FEATURES."; echo "25-35s: Compare before/after."; echo "35-45s: CTA: comment with your use case or visit product page."; }
cmd_live(){ parse_opts "$@"; echo "# Livestream Cues"; echo "- Open with use case and price anchor."; echo "- Demo one feature every 2 minutes."; echo "- Repeat shipping, guarantee, and bundle details."; echo "- Ask viewers to comment their scenario."; }
cmd_caption(){ parse_opts "$@"; echo "# Captions"; echo "- Testing a $PRODUCT for real desk setups. Would you use this?"; echo "- Three details most listings forget to explain."; echo "- Save this before you compare similar products."; }
cmd_keywords(){ parse_opts "$@"; echo "# Keyword Clusters"; for k in $(split_csv "$KEYWORDS"); do echo "## $k"; echo "- $k review"; echo "- best $k for $AUDIENCE"; echo "- $k price"; echo "- $k alternative"; done; }
cmd_rewrite(){ parse_opts "$@"; echo "# Rewritten Copy"; echo "$(make_title)"; echo; cmd_bullets --product "$PRODUCT" --features "$FEATURES" --keywords "$KEYWORDS" --channel "$CHANNEL"; }
cmd_category(){ parse_opts "$@"; echo "# Category Copy"; echo "$PRODUCT options help $AUDIENCE compare features, price, materials, and use cases before buying."; echo "Choose by primary scenario, required specs, and after-sales expectations."; }
cmd_calendar(){ parse_opts "$@"; echo "# 14-Day Ecommerce SEO Plan"; for i in $(seq 1 14); do echo "Day $i: publish one keyword-focused asset around $PRODUCT and validate search intent."; done; }
cmd_map(){ parse_opts "$@"; print_brief; echo "## Field Map"; echo "- Source facts -> title, bullets, specs, FAQ, search terms"; echo "- Target market -> tone, units, objections, compliance notes"; }
cmd_localize(){ parse_opts "$@"; echo "# Localized Copy ($TARGET, $LANG)"; echo "Title: $(make_title)"; echo "Tone: adapt to $TARGET buyer expectations; preserve factual specs."; cmd_bullets --product "$PRODUCT" --features "$FEATURES" --keywords "$KEYWORDS" --channel "$CHANNEL"; }
cmd_tone(){ parse_opts "$@"; echo "# Tone Variants"; for t in premium value technical social; do echo "## $t"; TONE="$t"; echo "$(make_title)"; done; }
cmd_compliance(){ parse_opts "$@"; echo "# Claim Safety Check"; echo "- Avoid guaranteed income, medical claims, fake scarcity, and unsupported comparisons."; echo "- Keep dimensions, materials, certifications, and compatibility factual."; echo "- Add marketplace-specific disclaimers when needed."; }
cmd_bundle(){ parse_opts "$@"; echo "# Multi-Channel Bundle"; cmd_title --product "$PRODUCT" --features "$FEATURES" --keywords "$KEYWORDS" --channel Amazon; cmd_seo --product "$PRODUCT" --features "$FEATURES" --keywords "$KEYWORDS" --channel Shopify; cmd_script --product "$PRODUCT" --features "$FEATURES" --keywords "$KEYWORDS" --channel TikTok; }
cmd_demo(){ parse_opts --product "portable blender" --channel "Amazon" --audience "busy commuters" --features "USB-C charging, 400ml cup, stainless blades, easy cleaning" --keywords "portable blender, smoothie maker, travel blender"; print_brief; echo; cmd_title; echo; cmd_bullets; echo; cmd_audit; }
usage(){ cat <<EOF
$SKILL_NAME v$VERSION
Commands: brief title bullets compare audit demo help version
Common options: --product TEXT --channel NAME --features CSV --keywords CSV --audience TEXT --target MARKET --lang CODE
EOF
}
case "-help" in
brief) shift; cmd_brief "$@";;
title) shift; cmd_title "$@";;
bullets) shift; cmd_bullets "$@";;
compare) shift; cmd_compare "$@";;
audit) shift; cmd_audit "$@";;
demo) shift; cmd_demo "$@";;
help|-h|--help) usage;;
version) echo "$VERSION";;
*) err "unknown command: $1"; usage; exit 1;;
esac
Build BI dashboard specs, chart plans, SQL queries, and Apache Superset chart JSON. Use when creating dashboards, BI reports, KPI charts, or visualization la...
---
name: "BytesAgain BI Dashboard Builder"
description: "Build BI dashboard specs, chart plans, SQL queries, and Apache Superset chart JSON. Use when creating dashboards, BI reports, KPI charts, or visualization layouts."
version: "1.1.0"
author: "BytesAgain"
homepage: "https://bytesagain.com"
source: "https://github.com/bytesagain/ai-skills"
tags: ["bi", "dashboard", "chart", "data", "sql", "superset", "visualization"]
category: "data"
---
# BytesAgain BI Dashboard Builder
Build BI dashboard specs from natural language, CSV headers, JSON metrics, or KPI lists. Outputs dashboard plans, SQL query templates, chart definitions, Apache Superset-compatible chart JSON snippets, KPI dictionaries, and dashboard QA reports.
## Commands
### generate
Create a dashboard plan with KPIs, charts, filters, and layout.
```bash
bash scripts/script.sh generate --goal "sales dashboard" --metrics "revenue,orders,aov" --dimensions "date,region,channel"
```
### chart
Create a single chart spec for bar, line, pie, table, metric, or time-series visualization.
```bash
bash scripts/script.sh chart --type line --metric revenue --dimension date --title "Revenue Trend"
```
### sql
Generate SQL templates for chart datasets and KPI cards.
```bash
bash scripts/script.sh sql --table orders --metrics "revenue,orders" --dimensions "date,region"
```
### superset
Export Apache Superset chart JSON snippets from a chart spec.
```bash
bash scripts/script.sh superset --type bar --metric revenue --dimension region --datasource "orders"
```
### kpi
Create KPI formulas, target hints, and owner notes for a BI dashboard.
```bash
bash scripts/script.sh kpi --metrics "revenue,orders,aov,conversion_rate" --dimensions "date,channel"
```
### dataset
Create a dataset contract with columns, grain, freshness, and quality checks.
```bash
bash scripts/script.sh dataset --table orders --metrics "revenue,orders" --dimensions "date,channel,region"
```
### qa
Audit a dashboard plan for business clarity, chart fit, and missing data definitions.
```bash
bash scripts/script.sh qa --goal "ecommerce growth dashboard" --metrics "revenue,orders,aov" --dimensions "date,channel"
```
### validate
Check a dashboard spec for missing metrics, dimensions, filters, and chart titles.
```bash
bash scripts/script.sh validate dashboard.json
```
### demo
Print a demo e-commerce BI dashboard with SQL and chart JSON.
```bash
bash scripts/script.sh demo
```
## Input Formats
- Natural language goal: `--goal "growth dashboard"`
- Metric list: `--metrics "revenue,orders,conversion_rate"`
- Dimension list: `--dimensions "date,region,channel"`
- JSON spec file for validation
## Output
- Markdown dashboard plan
- SQL query templates
- JSON chart specs
- Apache Superset chart JSON snippets
## Setup
| Variable | Required | Description |
|----------|----------|-------------|
| None | No | Runs with bash and standard Unix tools only |
## Notes
Use generic names for slugs and assets. Apache Superset output is supported as an export format, but this skill is a general BI dashboard builder.
## Feedback
https://bytesagain.com/feedback/
Powered by BytesAgain | bytesagain.com
FILE:scripts/script.sh
#!/usr/bin/env bash
set -euo pipefail
VERSION="1.1.0"
err() { printf 'Error: %s\n' "$*" >&2; }
slugify() { printf '%s' "$1" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9_ -]/ /g;s/[ _][ _]*/_/g;s/^_//;s/_$//'; }
split_csv() { printf '%s' "$1" | tr ',' '\n' | sed 's/^ *//;s/ *$//' | sed '/^$/d'; }
json_escape() { printf '%s' "$1" | sed 's/\\/\\\\/g;s/"/\\"/g'; }
usage() {
cat <<EOF_HELP
bytesagain-bi-dashboard-builder v$VERSION
Commands:
generate Build a BI dashboard plan from goal, metrics, and dimensions
chart Create one chart spec
sql Generate SQL templates for KPIs and charts
superset Export Apache Superset chart JSON snippets
kpi Create KPI formulas and owner notes
dataset Create a dataset contract
qa Audit dashboard clarity and chart fit
validate Check a dashboard JSON/spec file
demo Print a demo dashboard
help Show help
version Show version
Examples:
bash scripts/script.sh generate --goal "sales dashboard" --metrics "revenue,orders,aov" --dimensions "date,region,channel"
bash scripts/script.sh chart --type line --metric revenue --dimension date --title "Revenue Trend"
bash scripts/script.sh sql --table orders --metrics "revenue,orders" --dimensions "date,region"
bash scripts/script.sh superset --type bar --metric revenue --dimension region --datasource orders
EOF_HELP
}
parse_opts() {
GOAL=""; METRICS=""; DIMENSIONS=""; TYPE="bar"; METRIC=""; DIMENSION=""; TITLE=""; TABLE="events"; DATASOURCE=""
while [ "$#" -gt 0 ]; do
case "$1" in
--goal) GOAL="-"; shift 2 ;;
--metrics) METRICS="-"; shift 2 ;;
--dimensions) DIMENSIONS="-"; shift 2 ;;
--type) TYPE="-"; shift 2 ;;
--metric) METRIC="-"; shift 2 ;;
--dimension) DIMENSION="-"; shift 2 ;;
--title) TITLE="-"; shift 2 ;;
--table) TABLE="-"; shift 2 ;;
--datasource) DATASOURCE="-"; shift 2 ;;
*) err "unknown option: $1"; return 1 ;;
esac
done
}
metric_formula() {
local m="$(slugify "$1")"
case "$m" in
revenue|sales|gmv) echo "SUM(amount) AS $m" ;;
orders|users|customers|sessions) echo "COUNT(DISTINCT m%?_id) AS $m" ;;
conversion_rate|cr) echo "ROUND(100.0 * SUM(conversions) / NULLIF(SUM(sessions), 0), 2) AS conversion_rate" ;;
aov|avg_order_value) echo "ROUND(SUM(amount) / NULLIF(COUNT(DISTINCT order_id), 0), 2) AS aov" ;;
retention|retention_rate) echo "ROUND(100.0 * SUM(returning_users) / NULLIF(SUM(users), 0), 2) AS retention_rate" ;;
*) echo "SUM($m) AS $m" ;;
esac
}
chart_for_metric() {
local metric="$1" dim="$2"
local m="$(slugify "$metric")" d="$(slugify "$dim")"
case "$d" in
date|day|week|month|created_at) echo "line" ;;
region|country|channel|category|source) echo "bar" ;;
status|segment) echo "pie" ;;
*) echo "table" ;;
esac
}
cmd_generate() {
parse_opts "$@"
[ -n "$GOAL" ] || GOAL="BI dashboard"
[ -n "$METRICS" ] || METRICS="revenue,orders,conversion_rate"
[ -n "$DIMENSIONS" ] || DIMENSIONS="date,region,channel"
echo "# Dashboard Plan: $GOAL"
echo
echo "## KPIs"
split_csv "$METRICS" | while read -r m; do
printf -- '- **%s** — primary KPI card with current value, trend, and target delta\n' "$m"
done
echo
echo "## Charts"
local first_dim
first_dim=$(split_csv "$DIMENSIONS" | head -1)
split_csv "$METRICS" | while read -r m; do
local ctype
ctype=$(chart_for_metric "$m" "$first_dim")
printf -- '- %s by %s — %s chart for trend and comparison\n' "$m" "$first_dim" "$ctype"
done
echo
echo "## Filters"
split_csv "$DIMENSIONS" | while read -r d; do
printf -- '- %s filter for slicing dashboard views\n' "$d"
done
echo
echo "## Layout"
echo "- Row 1: KPI cards"
echo "- Row 2: trend charts"
echo "- Row 3: breakdown charts and detail table"
echo
echo "## Next Commands"
echo "bash scripts/script.sh sql --table events --metrics \"$METRICS\" --dimensions \"$DIMENSIONS\""
echo "bash scripts/script.sh superset --type bar --metric $(split_csv "$METRICS" | head -1) --dimension $first_dim --datasource events"
}
cmd_chart() {
parse_opts "$@"
[ -n "$METRIC" ] || METRIC="revenue"
[ -n "$DIMENSION" ] || DIMENSION="date"
[ -n "$TITLE" ] || TITLE="$METRIC by $DIMENSION"
local id="$(slugify "$TITLE")"
cat <<EOF_JSON
{
"id": "$id",
"title": "$(json_escape "$TITLE")",
"type": "$(json_escape "$TYPE")",
"metric": "$(json_escape "$METRIC")",
"dimension": "$(json_escape "$DIMENSION")",
"sort": "$(slugify "$METRIC") DESC",
"limit": 100,
"notes": "Use this chart in BI dashboards, reports, or Superset exports."
}
EOF_JSON
}
cmd_sql() {
parse_opts "$@"
[ -n "$METRICS" ] || METRICS="revenue,orders"
[ -n "$DIMENSIONS" ] || DIMENSIONS="date"
local dims select_metrics group_by
dims=$(split_csv "$DIMENSIONS" | while read -r d; do slugify "$d"; done | paste -sd ', ' -)
select_metrics=$(split_csv "$METRICS" | while read -r m; do metric_formula "$m"; done | sed 's/^/ /' | paste -sd ',\n' -)
group_by=$(split_csv "$DIMENSIONS" | while read -r d; do slugify "$d"; done | paste -sd ', ' -)
cat <<EOF_SQL
-- BI dashboard dataset query
SELECT
$dims,
$select_metrics
FROM $TABLE
WHERE event_date >= CURRENT_DATE - INTERVAL '90 days'
GROUP BY $group_by
ORDER BY $group_by;
-- KPI card query
SELECT
$(split_csv "$METRICS" | while read -r m; do metric_formula "$m"; done | sed 's/^/ /' | paste -sd ',\n' -)
FROM $TABLE
WHERE event_date >= CURRENT_DATE - INTERVAL '30 days';
EOF_SQL
}
cmd_superset() {
parse_opts "$@"
[ -n "$METRIC" ] || METRIC="revenue"
[ -n "$DIMENSION" ] || DIMENSION="date"
[ -n "$DATASOURCE" ] || DATASOURCE="$TABLE"
[ -n "$TITLE" ] || TITLE="$METRIC by $DIMENSION"
local viz="$TYPE"
case "$TYPE" in
line|timeseries) viz="echarts_timeseries_line" ;;
bar) viz="echarts_timeseries_bar" ;;
pie) viz="pie" ;;
table) viz="table" ;;
metric|big_number) viz="big_number_total" ;;
esac
cat <<EOF_JSON
{
"slice_name": "$(json_escape "$TITLE")",
"viz_type": "$viz",
"datasource_name": "$(json_escape "$DATASOURCE")",
"params": {
"metrics": ["$(slugify "$METRIC")"],
"groupby": ["$(slugify "$DIMENSION")"],
"row_limit": 1000,
"order_desc": true,
"show_legend": true,
"adhoc_filters": []
},
"dashboard_position": {
"type": "CHART",
"meta": { "width": 6, "height": 50 }
}
}
EOF_JSON
}
cmd_kpi() {
parse_opts "$@"
[ -n "$METRICS" ] || METRICS="revenue,orders,aov,conversion_rate"
[ -n "$DIMENSIONS" ] || DIMENSIONS="date,channel"
echo "# KPI Dictionary"
split_csv "$METRICS" | while read -r m; do
local key; key=$(slugify "$m")
echo "## $key"
echo "- Formula: $(metric_formula "$m")"
echo "- Owner: assign business owner before launch"
echo "- Grain: match dashboard grain across $(echo "$DIMENSIONS" | tr ',' '/')"
echo "- Target: define current period, previous period, and goal threshold"
echo "- Alert: flag if value changes more than expected week over week"
echo
done
}
cmd_dataset() {
parse_opts "$@"
[ -n "$METRICS" ] || METRICS="revenue,orders"
[ -n "$DIMENSIONS" ] || DIMENSIONS="date,channel"
echo "# Dataset Contract: $TABLE"
echo "Grain: one row per $(echo "$DIMENSIONS" | tr ',' '+')"
echo "Freshness: update daily before business review"
echo
echo "## Required Columns"
split_csv "$DIMENSIONS" | while read -r d; do echo "- $(slugify "$d") dimension column"; done
split_csv "$METRICS" | while read -r m; do echo "- $(slugify "$m") metric source column or derived formula"; done
echo
echo "## Quality Checks"
echo "- No duplicate rows at declared grain"
echo "- Date range covers reporting window"
echo "- Null rate reviewed for every dimension"
echo "- Metric totals reconcile with source system"
}
cmd_qa() {
parse_opts "$@"
[ -n "$GOAL" ] || GOAL="BI dashboard"
[ -n "$METRICS" ] || METRICS="revenue,orders,conversion_rate"
[ -n "$DIMENSIONS" ] || DIMENSIONS="date,channel"
local score=100
local mc dc
mc=$(split_csv "$METRICS" | wc -l | tr -d ' ')
dc=$(split_csv "$DIMENSIONS" | wc -l | tr -d ' ')
[ "$mc" -lt 2 ] && score=$((score-15))
[ "$dc" -lt 1 ] && score=$((score-15))
echo "# Dashboard QA: $GOAL"
echo "Score: $score/100"
echo
echo "## Checks"
echo "- Goal is stated as a business decision, not only a chart collection"
echo "- Each KPI has formula, owner, grain, and target"
echo "- Trend chart uses date/time dimension"
echo "- Breakdown chart uses channel, region, category, or segment"
echo "- Superset export uses supported viz_type values"
echo "- Dashboard has filters that match user questions"
}
cmd_validate() {
local file="-"
if [ -z "$file" ]; then
tmp=$(mktemp); cmd_chart --metric revenue --dimension date --title "Revenue Trend" > "$tmp"; file="$tmp"
fi
if [ ! -f "$file" ]; then
tmp=$(mktemp); cmd_chart --metric revenue --dimension date --title "Revenue Trend" > "$tmp"; file="$tmp"
fi
local problems=0
grep -q '"title"' "$file" || { echo "missing title"; problems=$((problems+1)); }
grep -q '"metric"\|"metrics"' "$file" || { echo "missing metric(s)"; problems=$((problems+1)); }
grep -q '"dimension"\|"groupby"' "$file" || { echo "missing dimension/groupby"; problems=$((problems+1)); }
grep -q '"type"\|"viz_type"' "$file" || { echo "missing chart type"; problems=$((problems+1)); }
if [ "$problems" -eq 0 ]; then echo "valid dashboard spec: $file"; else echo "$problems problem(s) found"; return 1; fi
}
cmd_demo() {
echo "## Demo: E-commerce BI Dashboard"
cmd_generate --goal "e-commerce growth dashboard" --metrics "revenue,orders,aov,conversion_rate" --dimensions "date,channel,region"
echo
echo "## SQL"
cmd_sql --table orders --metrics "revenue,orders,aov,conversion_rate" --dimensions "date,channel"
echo
echo "## Superset Chart JSON"
cmd_superset --type bar --metric revenue --dimension channel --datasource orders --title "Revenue by Channel"
}
case "-help" in
generate) shift; cmd_generate "$@" ;;
chart) shift; cmd_chart "$@" ;;
sql) shift; cmd_sql "$@" ;;
superset) shift; cmd_superset "$@" ;;
kpi) shift; cmd_kpi "$@" ;;
dataset) shift; cmd_dataset "$@" ;;
qa) shift; cmd_qa "$@" ;;
validate) shift; cmd_validate "$@" ;;
demo) shift; cmd_demo "$@" ;;
version) echo "$VERSION" ;;
help|-h|--help) usage ;;
*) err "unknown command: $1"; usage; exit 1 ;;
esac
Machine learning skill: find, explain, and implement ML algorithms with interactive Jupyter Notebook links. Covers linear regression, logistic regression, ne...
--- name: homemade-machine-learning-skill description: "Machine learning skill: find, explain, and implement ML algorithms with interactive Jupyter Notebook links. Covers linear regression, logistic regression, neural network, K-Means clustering, anomaly detection — with math, Python code, and skill demos." version: "1.0.0" author: "BytesAgain" homepage: "https://bytesagain.com/skill/homemade-machine-learning-skill" tags: ["machine learning", "jupyter notebook", "python", "data science", "education", "linear regression", "neural network", "skill"] --- # Homemade Machine Learning Skill Machine learning skill: learn, explain, and implement ML algorithms from scratch. Based on [trekhleb/homemade-machine-learning](https://github.com/trekhleb/homemade-machine-learning) (MIT, 22k+ ⭐) > 📦 Install: `clawhub install homemade-machine-learning-skill` 5 algorithms · 11 interactive notebooks · math explained · Python code included ## Commands ### explain — 解释算法原理 + 数学 + 代码 ```bash bash scripts/ml-notebook-finder.sh explain "linear regression" bash scripts/ml-notebook-finder.sh explain "neural network" bash scripts/ml-notebook-finder.sh explain "kmeans" ``` ### notebook — 获取交互式 Jupyter Notebook 链接 ```bash bash scripts/ml-notebook-finder.sh notebook "logistic regression" bash scripts/ml-notebook-finder.sh notebook "anomaly detection" ``` ### code — 获取 Python 实现代码片段 ```bash bash scripts/ml-notebook-finder.sh code "linear regression" bash scripts/ml-notebook-finder.sh code "kmeans" ``` ### path — 生成学习路径(按难度排序) ```bash bash scripts/ml-notebook-finder.sh path beginner bash scripts/ml-notebook-finder.sh path intermediate bash scripts/ml-notebook-finder.sh path advanced ``` ### list — 列出所有算法 ```bash bash scripts/ml-notebook-finder.sh list ``` ## Algorithms | Algorithm | Type | Notebooks | Use Case | |-----------|------|-----------|----------| | linear regression | supervised | 3 | price prediction, forecasting | | logistic regression | supervised | 4 | classification, MNIST | | neural network (MLP) | supervised | 2 | image recognition, deep learning | | k-means | unsupervised | 1 | clustering, segmentation | | anomaly detection | unsupervised | 1 | fraud detection, monitoring | ## Source MIT License — Original author: [trekhleb](https://github.com/trekhleb/homemade-machine-learning) Indexed by [BytesAgain](https://bytesagain.com) — AI skill discovery platform FILE:scripts/ml-notebook-finder.sh #!/bin/bash # ml-notebook-finder.sh v2.0.0 # Machine learning skill: explain algorithms, get notebooks, generate code # Based on trekhleb/homemade-machine-learning (MIT License) set -euo pipefail CMD="-list" QUERY="-" NBBASE="https://nbviewer.jupyter.org/github/trekhleb/homemade-machine-learning/blob/master/notebooks" GHBASE="https://github.com/trekhleb/homemade-machine-learning/blob/master/homemade" # ── Resolve algorithm key ────────────────────────────────────── resolve() { local q q=$(echo "$1" | tr '[:upper:]' '[:lower:]') if echo "$q" | grep -qE "linear|regress|univar|multivari|predict"; then echo "linear_regression" elif echo "$q" | grep -qE "logistic|sigmoid|classif|mnist|iris|spam|binary"; then echo "logistic_regression" elif echo "$q" | grep -qE "neural|mlp|perceptron|deep|backprop|network"; then echo "neural_network" elif echo "$q" | grep -qE "kmean|k-mean|cluster|segment|unsupervis"; then echo "k_means" elif echo "$q" | grep -qE "anomal|outlier|gaussian|fraud|detect"; then echo "anomaly_detection" else echo "" fi } # ── Explain command ──────────────────────────────────────────── do_explain() { local key="$1" case "$key" in linear_regression) cat << 'EOF' ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 🤖 LINEAR REGRESSION ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ WHAT IT DOES: Predicts a continuous numeric value by fitting a line (or plane) through training data. Minimizes the sum of squared errors. WHEN TO USE: • Stock/house price prediction • Sales forecasting • Any "predict a number" task MATH (core): hypothesis: h(x) = θ₀ + θ₁x₁ + θ₂x₂ + ... cost: J(θ) = (1/2m) Σ(h(xᵢ) - yᵢ)² update: θⱼ := θⱼ - α · ∂J/∂θⱼ (gradient descent — α is learning rate) PYTHON SNIPPET: import numpy as np class LinearRegression: def __init__(self, lr=0.01, epochs=1000): self.lr = lr self.epochs = epochs def fit(self, X, y): m, n = X.shape self.theta = np.zeros(n + 1) X_b = np.c_[np.ones(m), X] # add bias column for _ in range(self.epochs): pred = X_b @ self.theta grad = X_b.T @ (pred - y) / m self.theta -= self.lr * grad def predict(self, X): X_b = np.c_[np.ones(len(X)), X] return X_b @ self.theta INTERACTIVE NOTEBOOKS: ▶ Univariate (predict happiness by GDP): $NBBASE/linear_regression/univariate_linear_regression_demo.ipynb ▶ Multivariate (multiple features): $NBBASE/linear_regression/multivariate_linear_regression_demo.ipynb ▶ Non-linear (polynomial features): $NBBASE/linear_regression/non_linear_regression_demo.ipynb SOURCE CODE: $GHBASE/linear_regression/linear_regression.py EOF ;; logistic_regression) cat << 'EOF' ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 🤖 LOGISTIC REGRESSION ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ WHAT IT DOES: Classifies input into discrete categories. Uses sigmoid function to output a probability (0–1), then applies a threshold. WHEN TO USE: • Spam detection (spam / not spam) • Medical diagnosis (positive / negative) • Handwritten digit recognition (MNIST) MATH (core): sigmoid: σ(z) = 1 / (1 + e⁻ᶻ) hypothesis: h(x) = σ(θᵀx) cost: J = -(1/m) Σ [y·log(h) + (1-y)·log(1-h)] update: θⱼ := θⱼ - α · (1/m) Σ(h(xᵢ)-yᵢ)·xᵢⱼ PYTHON SNIPPET: import numpy as np class LogisticRegression: def __init__(self, lr=0.1, epochs=1000): self.lr = lr self.epochs = epochs def sigmoid(self, z): return 1 / (1 + np.exp(-z)) def fit(self, X, y): m, n = X.shape self.theta = np.zeros(n + 1) X_b = np.c_[np.ones(m), X] for _ in range(self.epochs): h = self.sigmoid(X_b @ self.theta) grad = X_b.T @ (h - y) / m self.theta -= self.lr * grad def predict(self, X, threshold=0.5): X_b = np.c_[np.ones(len(X)), X] return (self.sigmoid(X_b @ self.theta) >= threshold).astype(int) INTERACTIVE NOTEBOOKS: ▶ Linear boundary (Iris flower classification): $NBBASE/logistic_regression/logistic_regression_with_linear_boundary_demo.ipynb ▶ Non-linear boundary (microchip validity): $NBBASE/logistic_regression/logistic_regression_with_non_linear_boundary_demo.ipynb ▶ MNIST handwritten digits (28x28 pixels): $NBBASE/logistic_regression/multivariate_logistic_regression_demo.ipynb ▶ Fashion MNIST (clothes recognition): $NBBASE/logistic_regression/multivariate_logistic_regression_fashion_demo.ipynb SOURCE CODE: $GHBASE/logistic_regression/logistic_regression.py EOF ;; neural_network) cat << 'EOF' ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 🤖 NEURAL NETWORK (Multilayer Perceptron) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ WHAT IT DOES: Stacks layers of neurons to learn complex non-linear patterns. Each neuron computes a weighted sum + activation function. Trains via backpropagation (chain rule of calculus). WHEN TO USE: • Image/voice recognition • Complex classification where linear models fail • Foundation for CNN, RNN, Transformers MATH (core): forward pass: a[l] = σ(W[l] · a[l-1] + b[l]) loss (cross-entropy): L = -Σ y·log(ŷ) backprop: δ[l] = (W[l+1]ᵀ · δ[l+1]) ⊙ σ'(z[l]) weight update: W[l] -= α · δ[l] · a[l-1]ᵀ PYTHON SNIPPET: import numpy as np def sigmoid(z): return 1 / (1 + np.exp(-z)) def sigmoid_prime(z): s = sigmoid(z); return s * (1 - s) class MLP: def __init__(self, layers): # e.g. [784, 128, 10] self.W = [np.random.randn(layers[i+1], layers[i]) * 0.01 for i in range(len(layers)-1)] self.b = [np.zeros((n, 1)) for n in layers[1:]] def forward(self, x): a = x self.activations = [a] for W, b in zip(self.W, self.b): z = W @ a + b a = sigmoid(z) self.activations.append(a) return a def predict(self, x): return np.argmax(self.forward(x)) INTERACTIVE NOTEBOOKS: ▶ MNIST handwritten digits (28x28): $NBBASE/neural_network/multilayer_perceptron_demo.ipynb ▶ Fashion MNIST (clothes type recognition): $NBBASE/neural_network/multilayer_perceptron_fashion_demo.ipynb SOURCE CODE: $GHBASE/neural_network/multilayer_perceptron.py EOF ;; k_means) cat << 'EOF' ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 🤖 K-MEANS CLUSTERING ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ WHAT IT DOES: Unsupervised algorithm that groups data into K clusters. Iteratively assigns points to nearest centroid, then recomputes centroids until convergence. WHEN TO USE: • Customer segmentation • Image compression (reduce colors) • Document clustering • Any task where you need to group unlabeled data MATH (core): assign: cᵢ = argmin_k ||xᵢ - μₖ||² update: μₖ = (1/|Cₖ|) Σᵢ∈Cₖ xᵢ (repeat until centroids stop moving) PYTHON SNIPPET: import numpy as np class KMeans: def __init__(self, k=3, epochs=100): self.k = k self.epochs = epochs def fit(self, X): # Random init idx = np.random.choice(len(X), self.k, replace=False) self.centroids = X[idx] for _ in range(self.epochs): # Assign dists = np.linalg.norm(X[:, None] - self.centroids, axis=2) labels = np.argmin(dists, axis=1) # Update new_c = np.array([X[labels==k].mean(0) for k in range(self.k)]) if np.allclose(self.centroids, new_c): break self.centroids = new_c return labels INTERACTIVE NOTEBOOK: ▶ Cluster Iris flowers by petal dimensions: $NBBASE/k_means/k_means_demo.ipynb SOURCE CODE: $GHBASE/k_means/k_means.py EOF ;; anomaly_detection) cat << 'EOF' ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 🤖 ANOMALY DETECTION (Gaussian) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ WHAT IT DOES: Models normal data as a multivariate Gaussian distribution. Points with very low probability density are flagged as anomalies. No labels needed — purely unsupervised. WHEN TO USE: • Fraud detection (unusual transactions) • Server health monitoring (CPU/latency spikes) • Manufacturing defect detection • Network intrusion detection MATH (core): fit: μⱼ = (1/m) Σ xᵢⱼ σⱼ² = (1/m) Σ (xᵢⱼ - μⱼ)² density: p(x) = Π p(xⱼ; μⱼ, σⱼ²) flag: if p(x) < ε → anomaly PYTHON SNIPPET: import numpy as np class GaussianAnomalyDetector: def fit(self, X): self.mu = X.mean(axis=0) self.sigma2 = X.var(axis=0) def probability(self, X): coef = 1 / np.sqrt(2 * np.pi * self.sigma2) exponent = np.exp(-((X - self.mu)**2) / (2 * self.sigma2)) return np.prod(coef * exponent, axis=1) def predict(self, X, epsilon=1e-5): return self.probability(X) < epsilon # True = anomaly INTERACTIVE NOTEBOOK: ▶ Detect server anomalies by latency + throughput: $NBBASE/anomaly_detection/anomaly_detection_gaussian_demo.ipynb SOURCE CODE: $GHBASE/anomaly_detection/gaussian_anomaly_detection.py EOF ;; esac } # ── Notebook command ──────────────────────────────────────────── do_notebook() { local key="$1" echo "📓 Jupyter Notebooks for: key//_/" echo "" case "$key" in linear_regression) echo "▶ Univariate Linear Regression" echo " $NBBASE/linear_regression/univariate_linear_regression_demo.ipynb" echo "" echo "▶ Multivariate Linear Regression" echo " $NBBASE/linear_regression/multivariate_linear_regression_demo.ipynb" echo "" echo "▶ Non-linear Regression (polynomial)" echo " $NBBASE/linear_regression/non_linear_regression_demo.ipynb" ;; logistic_regression) echo "▶ Logistic Regression — Linear Boundary (Iris)" echo " $NBBASE/logistic_regression/logistic_regression_with_linear_boundary_demo.ipynb" echo "" echo "▶ Logistic Regression — Non-Linear Boundary" echo " $NBBASE/logistic_regression/logistic_regression_with_non_linear_boundary_demo.ipynb" echo "" echo "▶ Multivariate — MNIST Digits" echo " $NBBASE/logistic_regression/multivariate_logistic_regression_demo.ipynb" echo "" echo "▶ Multivariate — Fashion MNIST" echo " $NBBASE/logistic_regression/multivariate_logistic_regression_fashion_demo.ipynb" ;; neural_network) echo "▶ MLP — MNIST Handwritten Digits" echo " $NBBASE/neural_network/multilayer_perceptron_demo.ipynb" echo "" echo "▶ MLP — Fashion MNIST Clothes" echo " $NBBASE/neural_network/multilayer_perceptron_fashion_demo.ipynb" ;; k_means) echo "▶ K-Means Clustering — Iris Flowers" echo " $NBBASE/k_means/k_means_demo.ipynb" ;; anomaly_detection) echo "▶ Anomaly Detection — Server Monitoring" echo " $NBBASE/anomaly_detection/anomaly_detection_gaussian_demo.ipynb" ;; esac echo "" echo "💡 Open any link in browser for interactive demo" echo "📜 Source: github.com/trekhleb/homemade-machine-learning (MIT)" } # ── Code command ──────────────────────────────────────────────── do_code() { local key="$1" do_explain "$key" | grep -A 999 "PYTHON SNIPPET:" | grep -B 999 "INTERACTIVE NOTEBOOKS:" | grep -v "INTERACTIVE NOTEBOOKS:" } # ── Learning path ─────────────────────────────────────────────── do_path() { local level="-beginner" echo "🎓 ML Learning Path: $level" echo "============================================" case "$level" in beginner) echo "" echo "Step 1 — Linear Regression (predict numbers)" echo " → Understand gradient descent and cost functions" echo " → bash scripts/ml-notebook-finder.sh explain 'linear regression'" echo "" echo "Step 2 — Logistic Regression (classify things)" echo " → Learn sigmoid, cross-entropy loss, decision boundaries" echo " → bash scripts/ml-notebook-finder.sh explain 'logistic regression'" echo "" echo "Step 3 — K-Means (group without labels)" echo " → Your first unsupervised algorithm" echo " → bash scripts/ml-notebook-finder.sh explain 'kmeans'" echo "" echo "Prerequisites: Python basics, NumPy arrays, high school math" ;; intermediate) echo "" echo "Step 1 — Neural Network (MLP)" echo " → Backpropagation, activation functions, weight init" echo " → bash scripts/ml-notebook-finder.sh explain 'neural network'" echo "" echo "Step 2 — Anomaly Detection" echo " → Gaussian distributions, probability density" echo " → bash scripts/ml-notebook-finder.sh explain 'anomaly detection'" echo "" echo "Prerequisites: linear regression + logistic regression" ;; advanced) echo "" echo "All 5 algorithms → implement from scratch:" echo " 1. linear_regression → 2. logistic_regression" echo " 3. neural_network → 4. k_means → 5. anomaly_detection" echo "" echo "Full source: github.com/trekhleb/homemade-machine-learning" echo "Run all notebooks via Binder (no install):" echo " https://mybinder.org/v2/gh/trekhleb/homemade-machine-learning/master?filepath=notebooks" ;; *) echo "Levels: beginner, intermediate, advanced" ;; esac echo "" echo "📜 MIT License | bytesagain.com/skill/ml-notebook-finder" } # ── List ──────────────────────────────────────────────────────── do_list() { echo "🤖 ML Notebook Finder v2.0 — Skill by BytesAgain" echo "=================================================" echo "5 algorithms · 11 interactive notebooks · Python from scratch" echo "" echo "SUPERVISED LEARNING" echo " linear regression 3 notebooks predict continuous values" echo " logistic regression 4 notebooks classification (MNIST, Iris)" echo " neural network 2 notebooks MLP, image recognition" echo "" echo "UNSUPERVISED LEARNING" echo " kmeans 1 notebook clustering, segmentation" echo " anomaly detection 1 notebook fraud detection, monitoring" echo "" echo "COMMANDS" echo " explain \"algorithm\" — math + Python code + notebook links" echo " notebook \"algorithm\" — all notebook links for algorithm" echo " code \"algorithm\" — Python implementation snippet" echo " path [level] — learning roadmap (beginner/intermediate/advanced)" echo " list — this menu" echo "" echo "EXAMPLE" echo " bash scripts/ml-notebook-finder.sh explain 'neural network'" echo "" echo "📜 Based on github.com/trekhleb/homemade-machine-learning (MIT)" echo "🌐 bytesagain.com/skill/ml-notebook-finder" } # ── Main ──────────────────────────────────────────────────────── case "$CMD" in explain|notebook|code) if [ -z "$QUERY" ]; then echo "Usage: ml-notebook-finder.sh $CMD \"algorithm name\"" echo "Algorithms: linear regression, logistic regression, neural network, kmeans, anomaly detection" exit 1 fi KEY=$(resolve "$QUERY") if [ -z "$KEY" ]; then echo "❌ Algorithm not found: '$QUERY'" echo "Try: linear regression, logistic regression, neural network, kmeans, anomaly detection" exit 1 fi case "$CMD" in explain) do_explain "$KEY" ;; notebook) do_notebook "$KEY" ;; code) do_code "$KEY" ;; esac ;; path) do_path "$QUERY" ;; list) do_list ;; *) echo "Usage: ml-notebook-finder.sh [list|explain|notebook|code|path] [query]" ;; esac
Connect AI agents to BytesAgain skill search via MCP SSE. Shows setup commands for OpenClaw, Claude Desktop, and curl. No files modified.
---
name: "BytesAgain MCP"
description: "Connect AI agents to BytesAgain skill search via MCP SSE. Shows setup commands for OpenClaw, Claude Desktop, and curl. No files modified."
version: "1.1.0"
author: "bytesagain-lab"
tags: ["mcp", "skills", "agent", "openclaw", "setup"]
---
# BytesAgain MCP
Connect your AI agent to BytesAgain skill search via MCP SSE protocol. Works with OpenClaw, Claude Desktop, and any MCP-compatible client.
**MCP SSE:** `https://bytesagain.com/api/mcp/sse` (streamable-http)
**REST API:** `https://bytesagain.com/api/mcp?action=search&q=<query>` (sandbox-friendly)
**Auth:** none required
**Languages:** English, Chinese, Japanese, Korean, German, French, Portuguese, Spanish
## Commands
### setup
Show MCP connection commands for your client.
```bash
bash scripts/script.sh setup
```
### setup --client openclaw
Show OpenClaw setup command.
```bash
bash scripts/script.sh setup --client openclaw
```
### setup --client claude
Show Claude Desktop config JSON.
```bash
bash scripts/script.sh setup --client claude
```
### test
Test the MCP endpoint is reachable and responding.
```bash
bash scripts/script.sh test
```
### tools
List available MCP tools exposed by BytesAgain.
```bash
bash scripts/script.sh tools
```
## Available MCP Tools
Once connected, your agent can call:
| Tool | Description |
|------|-------------|
| `search_skills` | Search 788+ BytesAgain skills by keyword |
| `get_skill` | Get full details + install command for a skill |
| `popular_skills` | Top skills ranked by downloads |
## Requirements
- curl
- python3 (for JSON formatting)
## Notes
- After registering, restart your gateway and start a **new session** to activate tools
- Only returns skills published by BytesAgain authors
- Free, no API key needed
- Docs: https://bytesagain.com/mcp
FILE:scripts/script.sh
#!/usr/bin/env bash
# BytesAgain MCP — show MCP connection setup commands
set -euo pipefail
MCP_URL="https://bytesagain.com/api/mcp/sse"
DOCS_URL="https://bytesagain.com/mcp"
cmd_setup() {
local client="-all"
case "$client" in
openclaw|--client)
# handle --client openclaw
shift || true
local c="-all"
cmd_setup "$c"
return
;;
esac
if [[ "$client" == "openclaw" ]]; then
echo "=== OpenClaw Setup ==="
echo ""
echo "Run this command:"
echo ""
echo " openclaw mcp set bytesagain '{\"url\":\"MCP_URL\",\"transport\":\"streamable-http\"}'"
echo ""
echo "Then restart your gateway and start a new session."
elif [[ "$client" == "claude" ]]; then
echo "=== Claude Desktop Setup ==="
echo ""
echo "Add to ~/Library/Application Support/Claude/claude_desktop_config.json:"
echo ""
cat << 'JSON'
{
"mcpServers": {
"bytesagain": {
"url": "https://bytesagain.com/api/mcp/sse",
"transport": "streamable-http"
}
}
}
JSON
echo ""
echo "Then restart Claude Desktop."
else
echo "=== BytesAgain MCP Setup ==="
echo ""
echo "Endpoint: MCP_URL"
echo "Transport: streamable-http"
echo "Auth: none"
echo ""
echo "--- OpenClaw ---"
echo " openclaw mcp set bytesagain '{\"url\":\"MCP_URL\",\"transport\":\"streamable-http\"}'"
echo ""
echo "--- Claude Desktop ---"
echo " Add to claude_desktop_config.json:"
echo ' {"mcpServers":{"bytesagain":{"url":"'"MCP_URL"'","transport":"streamable-http"}}}'
echo ""
echo "--- curl (JSON-RPC) ---"
echo " curl -X POST MCP_URL \\"
echo " -H 'Content-Type: application/json' \\"
echo " -d '{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/list\",\"params\":{}}'"
echo ""
echo "Docs: DOCS_URL"
fi
}
cmd_test() {
echo "Testing BytesAgain MCP endpoint..."
echo ""
response=$(curl -s -w "\n%{http_code}" -X POST "MCP_URL" \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"test","version":"1.0"}}}' \
--max-time 10 2>/dev/null)
http_code=$(echo "$response" | tail -1)
body=$(echo "$response" | head -1)
if [[ "$http_code" == "200" ]]; then
echo "✅ MCP endpoint reachable (HTTP http_code)"
if echo "$body" | python3 -c "import json,sys; d=json.load(sys.stdin); print('✅ Protocol:', d['result']['protocolVersion'])" 2>/dev/null; then
:
else
echo "Response: body"
fi
else
echo "❌ Endpoint returned HTTP http_code"
echo "Response: body"
exit 1
fi
}
cmd_tools() {
echo "Fetching available MCP tools..."
echo ""
tmpfile=$(mktemp)
curl -s -X POST "MCP_URL" \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}' \
--max-time 10 2>/dev/null > "$tmpfile"
python3 - "$tmpfile" << 'PYEOF'
import json, sys
try:
with open(sys.argv[1]) as f:
d = json.load(f)
tools = d.get("result", {}).get("tools", [])
print(f"Found {len(tools)} tools:")
print()
for t in tools:
print(f' {t["name"]}')
print(f' {t["description"]}')
print()
except Exception as e:
print(f"Parse error: {e}")
sys.exit(1)
PYEOF
rm -f "$tmpfile"
}
REST_URL="https://bytesagain.com/api/mcp"
cmd_rest() {
echo "=== BytesAgain REST API (Sandbox-friendly) ==="
echo ""
echo "No SSE needed. Works in any environment including sandboxes."
echo ""
echo "Search skills:"
echo " curl 'REST_URL?action=search&q=email+automation&limit=10'"
echo ""
echo "Get skill details:"
echo " curl 'REST_URL?action=get&slug=<slug>'"
echo ""
echo "Popular skills:"
echo " curl 'REST_URL?action=popular&limit=20'"
echo ""
echo "Supports 7 languages: ZH/JA/KO/DE/FR/PT/ES"
echo "Example (Chinese): curl 'REST_URL?action=search&q=%E9%82%AE%E4%BB%B6%E8%87%AA%E5%8A%A8%E5%8C%96'"
}
cmd_search() {
local q="-"
if [[ -z "$q" ]]; then
echo "Usage: bash scripts/script.sh search <keyword>"
exit 1
fi
local encoded
encoded=$(python3 -c "import urllib.parse,sys; print(urllib.parse.quote(sys.argv[1]))" "$q")
echo "Searching: $q"
echo ""
tmpfile=$(mktemp)
curl -s "REST_URL?action=search&q=encoded&limit=5" > "$tmpfile"
python3 - "$tmpfile" << 'PYEOF'
import json, sys
with open(sys.argv[1]) as f:
d = json.load(f)
t = d.get('translated_query','')
if t: print(f"Translated: {t}\n")
print(f"Found {d.get('count',0)} results:")
for r in d.get('results',[]):
print(f" [{r.get('downloads',0)}dl] {r['name']} — {r['slug']}")
PYEOF
rm -f "$tmpfile"
}
# ── Main ──────────────────────────────────────────────────────
COMMAND="-setup"
shift || true
case "$COMMAND" in
setup) cmd_setup "$@" ;;
test) cmd_test ;;
tools) cmd_tools ;;
rest) cmd_rest ;;
search) cmd_search "$@" ;;
--help|-h|help)
echo "Usage: bash scripts/script.sh <command>"
echo ""
echo "Commands:"
echo " setup Show all client setup commands"
echo " setup --client openclaw OpenClaw setup"
echo " setup --client claude Claude Desktop setup"
echo " test Test MCP endpoint connectivity"
echo " tools List available MCP tools"
echo " rest Show REST API usage (sandbox-friendly)"
echo " search <keyword> Search skills via REST API"
echo ""
echo "Docs: DOCS_URL"
;;
*)
echo "Unknown command: $COMMAND"
echo "Run: bash scripts/script.sh --help"
exit 1
;;
esac
Xss reference tool. Use when working with xss in devtools contexts.
--- name: "xss" version: "1.0.0" description: "Xss reference tool. Use when working with xss in devtools contexts." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [xss, devtools, dev, reference, cli] category: "devtools" --- # Xss Xss reference tool. Use when working with xss in devtools contexts. ## When to Use - Working with xss and need quick reference - Looking up devtools standards or best practices for xss - Troubleshooting xss issues - Need a checklist or guide for xss 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 # xss — Xss reference tool. Use when working with xss in devtools contexts. # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="1.0.0" show_help() { cat << 'HELPEOF' xss v$VERSION — Xss Reference Tool Usage: xss <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' # Xss — Overview ## What is Xss? Xss (xss) is a specialized tool/concept in the devtools domain. It provides essential capabilities for professionals working with xss. ## Key Concepts - Core xss principles and fundamentals - How xss fits into the broader devtools ecosystem - Essential terminology every practitioner should know ## Why Xss Matters Understanding xss 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 xss concepts 2. Learn the standard tools and interfaces 3. Practice with common scenarios 4. Review safety and compliance requirements EOF } cmd_quickstart() { cat << 'EOF' # Xss — Quick Start Guide ## Prerequisites - Basic understanding of devtools concepts - Required tools and access credentials - System meeting minimum requirements ## Installation 1. Download or clone the xss 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' # Xss — Common Patterns & Best Practices ## Design Patterns 1. **Standard Pattern**: The most common approach for xss 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' # Xss — 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' # Xss — 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' # Xss — 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' # Xss — 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' # Xss — 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 "xss v$VERSION — Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: xss help"; exit 1 ;; esac
Use when writing Cairo smart contracts for StarkNet, looking up syntax and types, defining storage and events, generating contract templates, or reviewing te...
--- name: "Cairo — StarkNet Smart Contract Reference" description: "Use when writing Cairo smart contracts for StarkNet, looking up syntax and types, defining storage and events, generating contract templates, or reviewing test patterns." version: "2.0.0" author: "BytesAgain" homepage: https://bytesagain.com source: https://github.com/bytesagain/ai-skills tags: ["cairo", "starknet", "smart-contract", "blockchain", "ethereum", "zk-rollup"] --- # Cairo — StarkNet Smart Contract Reference Quick reference for Cairo language syntax, types, storage patterns, events, contract templates, and testing guidance for StarkNet development. ## Commands ### syntax Core Cairo syntax reference — variables, functions, control flow. ```bash bash scripts/script.sh syntax ``` ### types Cairo type system — felt252, integers, structs, enums, arrays. ```bash bash scripts/script.sh types ``` ### storage Storage variable patterns and access. ```bash bash scripts/script.sh storage ``` ### events Event declaration, emission, and indexing. ```bash bash scripts/script.sh events ``` ### template Generate a starter contract template. ```bash bash scripts/script.sh template erc20 bash scripts/script.sh template ownable ``` ### help Show all commands. ```bash bash scripts/script.sh help ``` ## Output - Syntax examples with explanations - Contract boilerplate code - Storage and event patterns ## Feedback https://bytesagain.com/feedback/ Powered by BytesAgain | bytesagain.com FILE:scripts/script.sh #!/usr/bin/env bash # cairo — Cairo / StarkNet Smart Contract Reference # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="2.0.0" cmd_syntax() { cat <<'EOF' ═══════════════════════════════════════════════════ Cairo Language Syntax Reference ═══════════════════════════════════════════════════ 【Variables & Mutability】 let x = 5; // immutable by default let mut x = 5; // mutable x = 10; // OK, x is mut let x: felt252 = 100; // explicit type annotation const MAX: u32 = 1000; // compile-time constant 【Functions】 fn add(a: felt252, b: felt252) -> felt252 { a + b // last expression = return value (no semicolon) } fn greet() { // no return value println!("Hello"); } fn multi_return() -> (u32, u32) { (10, 20) } 【Control Flow】 // if-else (expression-based, returns value) let max = if a > b { a } else { b }; // match (exhaustive pattern matching) match color { Color::Red => println!("red"), Color::Blue => println!("blue"), _ => println!("other"), } // loop loop { if count >= 10 { break; } count += 1; }; 【Ownership & References (Cairo-specific)】 // Cairo uses a linear type system (like Rust, stricter) fn consume(arr: Array<u32>) { ... } // takes ownership fn borrow(ref arr: Array<u32>) { ... } // mutable reference fn snapshot(arr: @Array<u32>) { ... } // immutable snapshot let mut arr = ArrayTrait::new(); arr.append(1); let snap = @arr; // snapshot (read-only view) let len = snap.len(); // OK 【Modules & Imports】 mod my_module; // declare module (file: my_module.cairo) use core::traits::Into; use starknet::ContractAddress; use super::MyStruct; 【Traits & Implementations】 trait Shape<T> { fn area(self: @T) -> u256; } impl RectangleShape of Shape<Rectangle> { fn area(self: @Rectangle) -> u256 { (*self.width) * (*self.height) } } 【Attributes (common)】 #[contract] // mark a module as a contract #[external(v0)] // public external function #[constructor] // constructor function #[event] // event struct #[derive(Drop, Serde)] // auto-derive traits #[abi(embed_v0)] // embed interface impl #[storage] // storage struct 【Macros】 println!("value: {}", x); // debug printing assert(x > 0, 'x must > 0'); // assertion with felt short string array![1, 2, 3] // array literal 📖 More skills: bytesagain.com EOF } cmd_types() { cat <<'EOF' ═══════════════════════════════════════════════════ Cairo Type System ═══════════════════════════════════════════════════ 【Primitive Types】 felt252 Field element (0 to P-1, P ≈ 2^251 + 17·2^192 + 1) bool true / false u8 Unsigned 8-bit (0 to 255) u16 Unsigned 16-bit (0 to 65535) u32 Unsigned 32-bit (0 to 4,294,967,295) u64 Unsigned 64-bit u128 Unsigned 128-bit u256 Unsigned 256-bit (two felt252 limbs) i8..i128 Signed integers usize Alias for u32 【Type Size on StarkNet】 felt252 1 storage slot u256 2 storage slots (high + low) ContractAddress 1 slot (felt252 wrapper) bool 1 slot 【Struct】 #[derive(Drop, Serde, starknet::Store)] struct Position { x: u128, y: u128, } let pos = Position { x: 10, y: 20 }; let x_val = pos.x; 【Enum】 #[derive(Drop, Serde)] enum Direction { North, South, East: u128, // variant with data West: u128, } let d = Direction::North; match d { Direction::North => ..., Direction::South => ..., Direction::East(val) => ..., Direction::West(val) => ..., } 【Option & Result】 use core::option::OptionTrait; let some_val: Option<u32> = Option::Some(42); let none_val: Option<u32> = Option::None; // unwrap let x = some_val.unwrap(); // panics if None let x = some_val.unwrap_or(0); // default fallback 【Array】 use core::array::ArrayTrait; let mut arr = ArrayTrait::new(); arr.append(1_u32); arr.append(2_u32); let len = arr.len(); // 2 let first = *arr.at(0); // 1 (snapshot deref) // Span (immutable view of array) let span = arr.span(); 【Dict (Felt252Dict)】 use core::dict::Felt252DictTrait; let mut dict = Default::default(); dict.insert('key', 100); let val = dict.get('key'); // 100 // ⚠️ Dict is non-squashable without explicit handling dict.squash(); // must call at end 【ByteArray (strings)】 let name: ByteArray = "Hello StarkNet"; let short: felt252 = 'hi'; // short string (≤31 chars) 【ContractAddress】 use starknet::ContractAddress; use starknet::contract_address_const; let addr: ContractAddress = contract_address_const::<0x123>(); 【Type Conversions】 let a: u8 = 10; let b: u16 = a.into(); // upcast with Into trait let c: u8 = b.try_into().unwrap(); // downcast with TryInto 📖 More skills: bytesagain.com EOF } cmd_storage() { cat <<'EOF' ═══════════════════════════════════════════════════ Cairo / StarkNet Storage Patterns ═══════════════════════════════════════════════════ 【Basic Storage Declaration】 #[storage] struct Storage { owner: ContractAddress, balance: u256, counter: u128, is_paused: bool, } 【Reading Storage】 fn get_owner(self: @ContractState) -> ContractAddress { self.owner.read() } 【Writing Storage】 fn set_owner(ref self: ContractState, new_owner: ContractAddress) { self.owner.write(new_owner); } 【Storage with Map (LegacyMap)】 #[storage] struct Storage { balances: LegacyMap::<ContractAddress, u256>, allowances: LegacyMap::<(ContractAddress, ContractAddress), u256>, } // Read/write map let bal = self.balances.read(account); self.balances.write(account, new_balance); // Nested key (tuple) let allowance = self.allowances.read((owner, spender)); 【Storage Address Computation】 // Single variable: sn_keccak(variable_name) // Map entry: h(sn_keccak(variable_name), key) // Nested map: h(h(sn_keccak(variable_name), key1), key2) // // h = pedersen hash for LegacyMap // This is how StarkNet locates storage slots 【Custom Struct in Storage】 #[derive(Drop, Serde, starknet::Store)] struct UserInfo { balance: u256, last_updated: u64, is_active: bool, } #[storage] struct Storage { users: LegacyMap::<ContractAddress, UserInfo>, } // Requires starknet::Store derive on the struct 【Storage Best Practices】 ✅ Use u256 for token amounts (ERC-20 standard) ✅ Use ContractAddress for addresses (not felt252) ✅ Pack related booleans into a single felt252 bitmask ✅ Minimize storage writes (most expensive operation) ❌ Don't store large arrays (use events for logs) ❌ Don't use felt252 for addresses in new code 【Storage Slots & Gas Cost】 • Storage read: ~100 gas units • Storage write: ~5,000 gas units (initial) • Storage write: ~2,500 gas units (update existing) • Each felt252 = 1 slot, u256 = 2 slots 📖 More skills: bytesagain.com EOF } cmd_events() { cat <<'EOF' ═══════════════════════════════════════════════════ Cairo / StarkNet Events ═══════════════════════════════════════════════════ 【Event Declaration】 #[event] #[derive(Drop, starknet::Event)] enum Event { Transfer: Transfer, Approval: Approval, OwnershipTransferred: OwnershipTransferred, } #[derive(Drop, starknet::Event)] struct Transfer { #[key] from: ContractAddress, #[key] to: ContractAddress, value: u256, } #[derive(Drop, starknet::Event)] struct Approval { #[key] owner: ContractAddress, #[key] spender: ContractAddress, value: u256, } 【Emitting Events】 #[abi(embed_v0)] impl MyContract of IMyContract<ContractState> { fn transfer(ref self: ContractState, to: ContractAddress, amount: u256) { let caller = get_caller_address(); // ... transfer logic ... self.emit(Transfer { from: caller, to: to, value: amount, }); } } 【#[key] Attribute — Indexed Fields】 // Fields marked with #[key] are indexed (like Solidity indexed) // They appear in the "keys" array of the event // Non-key fields appear in the "data" array // // Keys: searchable, filterable by indexers // Data: not directly filterable, but stored on-chain // // Max 3 keys recommended (similar to Solidity's 3 indexed limit) 【Flat Events (alternative)】 #[event] #[derive(Drop, starknet::Event)] enum Event { #[flat] OwnableEvent: ownable_component::Event, Transfer: Transfer, } // #[flat] merges component events into main event enum 【Event Patterns】 // ERC-20 standard events Transfer(from, to, value) Approval(owner, spender, value) // Access control events OwnershipTransferred(previous, new_owner) RoleGranted(role, account, sender) RoleRevoked(role, account, sender) // Lifecycle events Paused(account) Unpaused(account) Upgraded(class_hash) 【Listening to Events (off-chain)】 // Events are stored in transaction receipts // Use starknet.js, starknet.py, or Apibara for indexing // // Event key[0] = sn_keccak(event_name) // Event key[1..] = indexed fields // Event data[] = non-indexed fields 📖 More skills: bytesagain.com EOF } cmd_template() { local template="-" if [ -z "$template" ]; then cat <<'EOF' ═══════════════════════════════════════════════════ Cairo Contract Templates ═══════════════════════════════════════════════════ Available templates: erc20 ERC-20 fungible token contract ownable Ownable access control pattern counter Simple counter (good starter) erc721 ERC-721 NFT contract skeleton Usage: bash scripts/script.sh template erc20 bash scripts/script.sh template ownable 📖 More skills: bytesagain.com EOF return 0 fi case "$template" in erc20) cat <<'EOF' ═══════════════════════════════════════════════════ ERC-20 Token Contract Template ═══════════════════════════════════════════════════ use starknet::ContractAddress; #[starknet::interface] trait IERC20<TContractState> { fn name(self: @TContractState) -> ByteArray; fn symbol(self: @TContractState) -> ByteArray; fn decimals(self: @TContractState) -> u8; fn total_supply(self: @TContractState) -> u256; fn balance_of(self: @TContractState, account: ContractAddress) -> u256; fn allowance(self: @TContractState, owner: ContractAddress, spender: ContractAddress) -> u256; fn transfer(ref self: TContractState, recipient: ContractAddress, amount: u256) -> bool; fn transfer_from( ref self: TContractState, sender: ContractAddress, recipient: ContractAddress, amount: u256 ) -> bool; fn approve(ref self: TContractState, spender: ContractAddress, amount: u256) -> bool; } #[starknet::contract] mod ERC20 { use starknet::{ContractAddress, get_caller_address, contract_address_const}; use core::num::traits::Zero; #[storage] struct Storage { name: ByteArray, symbol: ByteArray, decimals: u8, total_supply: u256, balances: LegacyMap::<ContractAddress, u256>, allowances: LegacyMap::<(ContractAddress, ContractAddress), u256>, } #[event] #[derive(Drop, starknet::Event)] enum Event { Transfer: Transfer, Approval: Approval, } #[derive(Drop, starknet::Event)] struct Transfer { #[key] from: ContractAddress, #[key] to: ContractAddress, value: u256, } #[derive(Drop, starknet::Event)] struct Approval { #[key] owner: ContractAddress, #[key] spender: ContractAddress, value: u256, } #[constructor] fn constructor( ref self: ContractState, name: ByteArray, symbol: ByteArray, initial_supply: u256, recipient: ContractAddress, ) { self.name.write(name); self.symbol.write(symbol); self.decimals.write(18); self._mint(recipient, initial_supply); } #[abi(embed_v0)] impl ERC20Impl of super::IERC20<ContractState> { fn name(self: @ContractState) -> ByteArray { self.name.read() } fn symbol(self: @ContractState) -> ByteArray { self.symbol.read() } fn decimals(self: @ContractState) -> u8 { self.decimals.read() } fn total_supply(self: @ContractState) -> u256 { self.total_supply.read() } fn balance_of(self: @ContractState, account: ContractAddress) -> u256 { self.balances.read(account) } // ... (transfer, approve, transfer_from implementations) } } // Full implementation requires _mint, _burn, _transfer internal functions // See OpenZeppelin Cairo Contracts for production-ready code: // https://github.com/OpenZeppelin/cairo-contracts 📖 More skills: bytesagain.com EOF ;; ownable) cat <<'EOF' ═══════════════════════════════════════════════════ Ownable Contract Template ═══════════════════════════════════════════════════ use starknet::ContractAddress; #[starknet::interface] trait IOwnable<TContractState> { fn owner(self: @TContractState) -> ContractAddress; fn transfer_ownership(ref self: TContractState, new_owner: ContractAddress); fn renounce_ownership(ref self: TContractState); } #[starknet::contract] mod OwnableContract { use starknet::{ContractAddress, get_caller_address, contract_address_const}; use core::num::traits::Zero; #[storage] struct Storage { owner: ContractAddress, } #[event] #[derive(Drop, starknet::Event)] enum Event { OwnershipTransferred: OwnershipTransferred, } #[derive(Drop, starknet::Event)] struct OwnershipTransferred { #[key] previous_owner: ContractAddress, #[key] new_owner: ContractAddress, } #[constructor] fn constructor(ref self: ContractState, owner: ContractAddress) { self.owner.write(owner); self.emit(OwnershipTransferred { previous_owner: contract_address_const::<0>(), new_owner: owner, }); } #[abi(embed_v0)] impl OwnableImpl of super::IOwnable<ContractState> { fn owner(self: @ContractState) -> ContractAddress { self.owner.read() } fn transfer_ownership(ref self: ContractState, new_owner: ContractAddress) { self._assert_only_owner(); assert(!new_owner.is_zero(), 'New owner is zero address'); let previous = self.owner.read(); self.owner.write(new_owner); self.emit(OwnershipTransferred { previous_owner: previous, new_owner: new_owner, }); } fn renounce_ownership(ref self: ContractState) { self._assert_only_owner(); let previous = self.owner.read(); self.owner.write(contract_address_const::<0>()); self.emit(OwnershipTransferred { previous_owner: previous, new_owner: contract_address_const::<0>(), }); } } #[generate_trait] impl InternalImpl of InternalTrait { fn _assert_only_owner(self: @ContractState) { let caller = get_caller_address(); let owner = self.owner.read(); assert(caller == owner, 'Caller is not the owner'); } } } 📖 More skills: bytesagain.com EOF ;; counter) cat <<'EOF' ═══════════════════════════════════════════════════ Simple Counter Contract Template ═══════════════════════════════════════════════════ #[starknet::interface] trait ICounter<TContractState> { fn get(self: @TContractState) -> u128; fn increment(ref self: TContractState); fn decrement(ref self: TContractState); fn reset(ref self: TContractState); } #[starknet::contract] mod Counter { #[storage] struct Storage { counter: u128, } #[constructor] fn constructor(ref self: ContractState, initial_value: u128) { self.counter.write(initial_value); } #[abi(embed_v0)] impl CounterImpl of super::ICounter<ContractState> { fn get(self: @ContractState) -> u128 { self.counter.read() } fn increment(ref self: ContractState) { let current = self.counter.read(); self.counter.write(current + 1); } fn decrement(ref self: ContractState) { let current = self.counter.read(); assert(current > 0, 'Counter is already zero'); self.counter.write(current - 1); } fn reset(ref self: ContractState) { self.counter.write(0); } } } // Test: scarb test // Deploy: starkli deploy <class_hash> <initial_value> 📖 More skills: bytesagain.com EOF ;; *) echo "❌ Unknown template: $template" echo "Available: erc20, ownable, counter, erc721" echo "" echo "📖 More skills: bytesagain.com" ;; esac } cmd_help() { cat <<EOF Cairo vVERSION — StarkNet Smart Contract Reference Commands: syntax Core Cairo syntax (variables, functions, control flow) types Type system (felt252, integers, structs, enums, arrays) storage Storage patterns (variables, maps, structs, gas costs) events Event declaration, emission, and indexing template [name] Contract templates (erc20, ownable, counter) help Show this help version Show version Usage: bash scripts/script.sh syntax bash scripts/script.sh types bash scripts/script.sh template erc20 Resources: Cairo Book: https://book.cairo-lang.org StarkNet Docs: https://docs.starknet.io OpenZeppelin: https://github.com/OpenZeppelin/cairo-contracts Scarb (toolchain): https://docs.swmansion.com/scarb Related skills: clawhub install blast clawhub install solidity Browse all: bytesagain.com Powered by BytesAgain | bytesagain.com EOF } case "-help" in syntax) cmd_syntax ;; types) cmd_types ;; storage) cmd_storage ;; events) cmd_events ;; template) shift; cmd_template "$@" ;; version) echo "cairo vVERSION" ;; help|*) cmd_help ;; esac
Calculate RSI for any asset. Use when checking overbought/oversold conditions, spotting divergence signals, comparing multi-timeframe RSI, or setting trading...
--- name: "RSI — Relative Strength Index Calculator" description: "Calculate RSI for any asset. Use when checking overbought/oversold conditions, spotting divergence signals, comparing multi-timeframe RSI, or setting trading entry/exit alerts." version: "2.0.0" author: "BytesAgain" homepage: https://bytesagain.com source: https://github.com/bytesagain/ai-skills tags: ["rsi", "trading", "crypto", "stocks", "technical-analysis", "finance"] --- # RSI — Relative Strength Index Calculator Calculate and interpret RSI for any crypto or stock asset. Identify overbought/oversold zones, divergence signals, and optimal entry/exit points. ## Commands ### calculate Calculate RSI from price data. ```bash bash scripts/script.sh calculate 14 ``` ### interpret Interpret an RSI value with trading signals. ```bash bash scripts/script.sh interpret 72.5 ``` ### zones Show RSI zone definitions and trading rules. ```bash bash scripts/script.sh zones ``` ### divergence Explain RSI divergence patterns. ```bash bash scripts/script.sh divergence ``` ### strategies Common RSI trading strategies. ```bash bash scripts/script.sh strategies ``` ### help Show all commands. ```bash bash scripts/script.sh help ``` ## Output - RSI values with zone classification - Trading signals (buy/sell/hold) - Divergence pattern descriptions ## Feedback https://bytesagain.com/feedback/ Powered by BytesAgain | bytesagain.com FILE:scripts/script.sh #!/usr/bin/env bash # rsi — RSI (Relative Strength Index) Calculator & Reference # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="2.0.0" cmd_calculate() { local period="-14" cat << EOF ═══════════════════════════════════════════════════ RSI Calculator — Period: period ═══════════════════════════════════════════════════ 【RSI Formula】 RSI = 100 - (100 / (1 + RS)) RS = Average Gain / Average Loss (over period periods) 【Step-by-step Calculation】 1. Collect period periods of closing prices 2. Calculate price changes: Change = Close[i] - Close[i-1] 3. Separate gains (positive changes) and losses (negative changes) 4. Average Gain = Sum of gains / period 5. Average Loss = Sum of losses / period 6. RS = Average Gain / Average Loss 7. RSI = 100 - (100 / (1 + RS)) 【Smoothed RSI (Wilder's method, more common)】 After first period periods: Avg Gain = (Prev Avg Gain × $(( period - 1 )) + Current Gain) / period Avg Loss = (Prev Avg Loss × $(( period - 1 )) + Current Loss) / period 【Example】 14-day prices: 44, 44.34, 44.09, 43.61, 44.33, 44.83, 45.10, 45.42, 45.84, 46.08, 45.89, 46.03, 45.61, 46.28 Gains: 0.34, 0, 0, 0.72, 0.50, 0.27, 0.32, 0.42, 0.24, 0, 0.14, 0, 0.67 Losses: 0, 0.25, 0.48, 0, 0, 0, 0, 0, 0, 0.19, 0, 0.42, 0 Avg Gain = 3.62 / 14 = 0.2586 Avg Loss = 1.34 / 14 = 0.0957 RS = 0.2586 / 0.0957 = 2.7024 RSI = 100 - (100 / 3.7024) = 72.98 → RSI = 72.98 (Overbought zone) 📖 More skills: bytesagain.com EOF } cmd_interpret() { local rsi_val="-" if [ -z "$rsi_val" ]; then echo "Usage: bash scripts/script.sh interpret <rsi_value>" echo "Example: bash scripts/script.sh interpret 72.5" return 1 fi RSI_VAL="$rsi_val" python3 << 'PYEOF' import os rsi = float(os.environ["RSI_VAL"]) print("═" * 50) print(f" RSI Analysis: {rsi:.1f}") print("═" * 50) if rsi >= 80: zone = "🔴 EXTREME OVERBOUGHT" signal = "STRONG SELL" desc = "Asset severely overbought. High probability of pullback." action = "Consider taking profits. Set tight stop-loss." elif rsi >= 70: zone = "🟠 OVERBOUGHT" signal = "SELL / CAUTION" desc = "Asset overbought. Momentum may be weakening." action = "Watch for bearish divergence. Tighten stops." elif rsi >= 60: zone = "🟡 BULLISH" signal = "HOLD / ACCUMULATE" desc = "Healthy uptrend. RSI shows strong momentum." action = "Hold positions. Trail stops below support." elif rsi >= 40: zone = "⚪ NEUTRAL" signal = "WAIT" desc = "No clear direction. Market consolidating." action = "Wait for breakout above 60 or breakdown below 40." elif rsi >= 30: zone = "🟢 BEARISH" signal = "WATCH FOR ENTRY" desc = "Downtrend but not yet oversold." action = "Watch for bullish divergence near 30." elif rsi >= 20: zone = "🔵 OVERSOLD" signal = "BUY / ACCUMULATE" desc = "Asset oversold. Bounce likely." action = "Look for reversal candles. Scale in gradually." else: zone = "💎 EXTREME OVERSOLD" signal = "STRONG BUY" desc = "Asset severely oversold. High probability of bounce." action = "Strong entry zone. Use dollar-cost averaging." print(f"\n Zone: {zone}") print(f" Signal: {signal}") print(f" Note: {desc}") print(f" Action: {action}") print(f"\n ⚠️ RSI alone is not enough. Combine with price action,") print(f" volume, and support/resistance levels.") print(f"\n📖 More skills: bytesagain.com") PYEOF } cmd_zones() { cat << 'EOF' ═══════════════════════════════════════════════════ RSI Zone Definitions ═══════════════════════════════════════════════════ 【Standard Zones (Wilder's original)】 80-100 🔴 Extreme Overbought — Strong sell signal 70-80 🟠 Overbought — Sell / reduce positions 60-70 🟡 Bullish — Uptrend, hold longs 40-60 ⚪ Neutral — No clear trend 30-40 🟢 Bearish — Downtrend, watch for entry 20-30 🔵 Oversold — Buy signal 0-20 💎 Extreme Oversold — Strong buy signal 【Trending Market Adjustment】 In strong uptrends, RSI often stays 40-90: - Support at 40-50 (not 30) - Overbought only above 80 In strong downtrends, RSI often stays 10-60: - Resistance at 50-60 (not 70) - Oversold only below 20 【Common Period Settings】 Period Use Case ───────────────────────────── 7 Short-term / scalping 9 Swing trading (crypto) 14 Standard (Wilder default) ⭐ 21 Medium-term / stocks 25 Long-term / investing 【Key Rules】 • RSI > 50 = bullish bias • RSI < 50 = bearish bias • RSI crossing 50 = trend change signal • Never use RSI alone — always confirm with price action 📖 More skills: bytesagain.com EOF } cmd_divergence() { cat << 'EOF' ═══════════════════════════════════════════════════ RSI Divergence Patterns ═══════════════════════════════════════════════════ 【Bullish Divergence 🟢 (Buy signal)】 Price: Lower Low ↘ RSI: Higher Low ↗ Meaning: Selling pressure weakening despite lower prices. Action: Look for entry on next candle close above resistance. Best at: RSI below 30 (oversold zone) 【Bearish Divergence 🔴 (Sell signal)】 Price: Higher High ↗ RSI: Lower High ↘ Meaning: Buying pressure weakening despite higher prices. Action: Tighten stops. Consider taking profits. Best at: RSI above 70 (overbought zone) 【Hidden Bullish Divergence 🟢 (Trend continuation)】 Price: Higher Low ↗ RSI: Lower Low ↘ Meaning: Uptrend pullback. Buyers absorbing dip. Action: Add to long position on support. 【Hidden Bearish Divergence 🔴 (Trend continuation)】 Price: Lower High ↘ RSI: Higher High ↗ Meaning: Downtrend rally. Sellers still in control. Action: Look for short entry on resistance rejection. 【Divergence Quality Checklist】 ✅ RSI in overbought/oversold zone ✅ Clear swing highs/lows (not choppy) ✅ Divergence spans 5-20 bars (not too tight) ✅ Volume confirms (decreasing on divergence move) ❌ Ignore divergence in strong trending markets 📖 More skills: bytesagain.com EOF } cmd_strategies() { cat << 'EOF' ═══════════════════════════════════════════════════ RSI Trading Strategies ═══════════════════════════════════════════════════ 【Strategy 1: Classic Overbought/Oversold】 Entry: Buy when RSI crosses above 30 from below Exit: Sell when RSI crosses below 70 from above Stop: Below recent swing low Best: Range-bound / sideways markets Risk: Fails in strong trends (RSI stays overbought) 【Strategy 2: RSI + Moving Average Combo】 Setup: 50-period SMA on price chart Long: Price > SMA AND RSI crosses above 40 Short: Price < SMA AND RSI crosses below 60 Edge: Filters out counter-trend signals 【Strategy 3: RSI Failure Swing (Wilder's original)】 Bullish Failure Swing: 1. RSI drops below 30 2. RSI bounces above 30 3. RSI pulls back but stays above 30 4. RSI breaks above the bounce high → BUY Bearish Failure Swing: 1. RSI rises above 70 2. RSI drops below 70 3. RSI rallies but stays below 70 4. RSI breaks below the dip low → SELL 【Strategy 4: Multi-Timeframe RSI】 Weekly RSI: Determines trend direction Daily RSI: Determines entry timing If Weekly RSI > 50 (bullish trend): → Buy when Daily RSI dips to 30-40 (pullback entry) If Weekly RSI < 50 (bearish trend): → Short when Daily RSI rises to 60-70 (rally entry) 【Strategy 5: RSI Range Shift (Andrew Cardwell)】 Uptrend: RSI oscillates between 40-80 Downtrend: RSI oscillates between 20-60 Transition: Watch for RSI breaking out of its range → Signals potential trend change 📖 More skills: bytesagain.com EOF } cmd_help() { cat << EOF RSI vVERSION — Relative Strength Index Calculator Commands: calculate [period] Calculate RSI step-by-step (default: 14) interpret <value> Interpret an RSI value with trading signals zones RSI zone definitions and trading rules divergence RSI divergence patterns (bullish/bearish) strategies Common RSI trading strategies help Show this help version Show version Usage: bash scripts/script.sh calculate 14 bash scripts/script.sh interpret 72.5 bash scripts/script.sh zones Related skills: clawhub install macd clawhub install atr Browse all: bytesagain.com Powered by BytesAgain | bytesagain.com EOF } case "-help" in calculate) shift; cmd_calculate "$@" ;; interpret) shift; cmd_interpret "$@" ;; zones) cmd_zones ;; divergence) cmd_divergence ;; strategies) cmd_strategies ;; version) echo "rsi vVERSION" ;; help|*) cmd_help ;; esac
Calculate MACD from price data. Use when computing MACD/signal/histogram from a price series, spotting crossovers, reading momentum, or planning MACD-based e...
--- name: "MACD — Moving Average Convergence Divergence" description: "Calculate MACD from price data. Use when computing MACD/signal/histogram from a price series, spotting crossovers, reading momentum, or planning MACD-based entries." version: "2.0.4" author: "BytesAgain" homepage: https://bytesagain.com source: https://github.com/bytesagain/ai-skills tags: ["macd", "trading", "crypto", "stocks", "technical-analysis", "finance", "momentum"] --- # MACD — Moving Average Convergence Divergence Calculate MACD from price data. Compute EMA, MACD line, signal line, and histogram from a CSV or inline price series. ## Requirements - bash 4+ - python3 (standard library only) ## Commands ### calculate Calculate MACD from a comma-separated price series. ```bash bash scripts/script.sh calculate "170.5,171.2,172.8,171.0,173.5,174.2,175.0,174.8,176.1,175.5,177.2,178.0,176.5,177.8,179.0,178.5,180.2,179.8,181.0,180.5,182.3,181.8,183.0,182.5,184.0,183.5" ``` ### calculate-file Calculate MACD from a CSV file (one price per line or column). ```bash bash scripts/script.sh calculate-file prices.csv ``` ### interpret Interpret MACD, signal, and histogram values with trading signals. ```bash bash scripts/script.sh interpret 1.25 0.80 ``` ### crossover Explain crossover patterns and trading rules. ```bash bash scripts/script.sh crossover ``` ### histogram MACD histogram analysis and momentum reading guide. ```bash bash scripts/script.sh histogram ``` ### strategies MACD trading strategies with entry/exit rules. ```bash bash scripts/script.sh strategies ``` ### help Show all commands. ```bash bash scripts/script.sh help ``` ## Output - Computed MACD line, signal line, and histogram from real price data - EMA values at each step - Crossover and divergence signals - Trading strategy frameworks ## Feedback https://bytesagain.com/feedback/ Powered by BytesAgain | bytesagain.com FILE:scripts/script.sh #!/usr/bin/env bash # macd — MACD (Moving Average Convergence Divergence) Calculator # Requires: python3 (standard library only) # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="2.0.4" cmd_calculate() { local prices="-" local fast="-12" local slow="-26" local signal="-9" if [ -z "$prices" ]; then echo "Usage: bash scripts/script.sh calculate \"price1,price2,...\" [fast] [slow] [signal]" echo " Defaults: fast=12, slow=26, signal=9" echo "" echo "Example:" echo " bash scripts/script.sh calculate \"170.5,171.2,172.8,171.0,173.5,174.2,175.0,174.8,176.1,175.5,177.2,178.0,176.5,177.8,179.0,178.5,180.2,179.8,181.0,180.5,182.3,181.8,183.0,182.5,184.0,183.5\"" return 1 fi PRICES="$prices" FAST="$fast" SLOW="$slow" SIGNAL="$signal" python3 << 'PYEOF' import os prices_str = os.environ["PRICES"] fast = int(os.environ["FAST"]) slow = int(os.environ["SLOW"]) signal_p = int(os.environ["SIGNAL"]) prices = [float(p.strip()) for p in prices_str.split(",") if p.strip()] if len(prices) < slow + signal_p: print(f"Error: Need at least {slow + signal_p} prices, got {len(prices)}") exit(1) def calc_ema(data, period): """Calculate EMA series from price data.""" ema = [] # First EMA = SMA of first 'period' values sma = sum(data[:period]) / period ema.append(sma) mult = 2.0 / (period + 1) for i in range(period, len(data)): val = data[i] * mult + ema[-1] * (1 - mult) ema.append(val) return ema # Calculate EMAs ema_fast = calc_ema(prices, fast) ema_slow = calc_ema(prices, slow) # Align: ema_fast starts at index fast-1, ema_slow at slow-1 # MACD line starts where both exist offset = slow - fast macd_line = [] for i in range(len(ema_slow)): macd_val = ema_fast[i + offset] - ema_slow[i] macd_line.append(macd_val) # Signal line = EMA of MACD line signal_line = calc_ema(macd_line, signal_p) # Histogram hist_offset = signal_p histogram = [] for i in range(len(signal_line)): h = macd_line[i + signal_p - 1 + 1 - 1] - signal_line[i] histogram.append(h) # Recalculate aligned # ema_slow starts at index slow-1 of prices # macd_line[j] corresponds to prices index slow-1+j # signal_line starts at index signal_p-1 of macd_line # So signal_line[k] corresponds to macd_line[signal_p-1+k] print("=" * 60) print(f" MACD Calculator — ({fast}, {slow}, {signal_p})") print("=" * 60) print(f" Input: {len(prices)} prices") print(f" EMA({fast}) multiplier: {2/(fast+1):.4f}") print(f" EMA({slow}) multiplier: {2/(slow+1):.4f}") print(f" Signal multiplier: {2/(signal_p+1):.4f}") print() # Show last 10 data points with aligned indices n_show = min(10, len(signal_line)) print(f" Last {n_show} computed values:") print(f" {'Day':<6} {'Price':<10} {'EMA'+str(fast):<12} {'EMA'+str(slow):<12} {'MACD':<10} {'Signal':<10} {'Hist':<10}") print(f" {'-'*70}") for i in range(len(signal_line) - n_show, len(signal_line)): macd_idx = i + signal_p - 1 price_idx = slow - 1 + macd_idx if price_idx < len(prices) and macd_idx < len(macd_line): ema_f_idx = macd_idx + offset p = prices[price_idx] if price_idx < len(prices) else 0 ef = ema_fast[ema_f_idx] if ema_f_idx < len(ema_fast) else 0 es = ema_slow[macd_idx] if macd_idx < len(ema_slow) else 0 m = macd_line[macd_idx] s = signal_line[i] h = m - s print(f" {price_idx+1:<6} {p:<10.2f} {ef:<12.4f} {es:<12.4f} {m:<10.4f} {s:<10.4f} {h:<+10.4f}") # Current values (last) last_macd = macd_line[-1] last_signal = signal_line[-1] last_hist = last_macd - last_signal print() print(f" Current MACD: {last_macd:+.4f}") print(f" Current Signal: {last_signal:+.4f}") print(f" Current Histogram: {last_hist:+.4f}") print() # Generate signal if last_macd > last_signal: if last_hist > 0 and len(histogram) > 1 and histogram[-1] > histogram[-2]: sig = "BULLISH (MACD above signal, histogram expanding)" else: sig = "BULLISH (MACD above signal)" else: if last_hist < 0 and len(histogram) > 1 and histogram[-1] < histogram[-2]: sig = "BEARISH (MACD below signal, histogram expanding down)" else: sig = "BEARISH (MACD below signal)" if abs(last_hist) < 0.05: sig += " ⚠️ Near crossover" print(f" Signal: {sig}") print(f"\n📖 More skills: bytesagain.com") PYEOF } cmd_calculate_file() { local file="-" if [ -z "$file" ] || [ ! -f "$file" ]; then echo "Usage: bash scripts/script.sh calculate-file <prices.csv>" echo " CSV format: one price per line, or first column of CSV" return 1 fi # Extract prices from CSV (first numeric column) local prices prices=$(python3 << PYEOF import csv, sys with open("$file") as f: reader = csv.reader(f) vals = [] for row in reader: for cell in row: cell = cell.strip() try: v = float(cell) vals.append(str(v)) break except ValueError: continue print(",".join(vals)) PYEOF ) if [ -z "$prices" ]; then echo "Error: No numeric data found in $file" return 1 fi cmd_calculate "$prices" "-12" "-26" "-9" } cmd_interpret() { local macd_val="-" local signal_val="-" if [ -z "$macd_val" ] || [ -z "$signal_val" ]; then echo "Usage: bash scripts/script.sh interpret <macd_value> <signal_value>" echo "Example: bash scripts/script.sh interpret 1.25 0.80" return 1 fi MACD_VAL="$macd_val" SIG_VAL="$signal_val" python3 << 'PYEOF' import os macd = float(os.environ["MACD_VAL"]) signal = float(os.environ["SIG_VAL"]) hist = macd - signal print("=" * 55) print(f" MACD Analysis") print("=" * 55) print(f" MACD Line: {macd:+.4f}") print(f" Signal Line: {signal:+.4f}") print(f" Histogram: {hist:+.4f}") print() # Zone analysis if macd > 0 and signal > 0: zone = "ABOVE ZERO — Bullish territory" elif macd < 0 and signal < 0: zone = "BELOW ZERO — Bearish territory" else: zone = "ZERO LINE AREA — Trend transition" # Crossover if macd > signal: cross = "MACD above Signal — Bullish" if hist > 0.5: momentum = "Strong upward momentum" elif hist > 0: momentum = "Mild upward momentum" else: momentum = "Weak momentum" else: cross = "MACD below Signal — Bearish" if hist < -0.5: momentum = "Strong downward momentum" elif hist < 0: momentum = "Mild downward momentum" else: momentum = "Weak momentum" # Action if macd > signal and macd > 0: action = "Hold longs. Trail stop below support." elif macd > signal and macd <= 0: action = "Potential bottom. Watch for zero-line crossover to confirm." elif macd < signal and macd < 0: action = "Bearish. Avoid longs. Look for oversold bounce signals." else: action = "Topping signal. Consider taking profits. Tighten stops." print(f" Zone: {zone}") print(f" Cross: {cross}") print(f" Momentum: {momentum}") print(f" Action: {action}") if abs(hist) < 0.1: print(f"\n ⚠️ Histogram near zero — crossover imminent!") print(f"\n📖 More skills: bytesagain.com") PYEOF } cmd_crossover() { cat << 'EOF' ═══════════════════════════════════════════════════ MACD Crossover Patterns ═══════════════════════════════════════════════════ 【Bullish Crossover 🟢】 MACD line crosses ABOVE signal line Histogram: negative → positive Strength filters: ✅ Strong: occurs below zero line (early trend) ⚠️ Medium: occurs near zero line ❌ Weak: occurs far above zero (late, risky) Entry: Buy on close after crossover confirms Stop: Below recent swing low Target: Previous resistance or 2:1 R:R 【Bearish Crossover 🔴】 MACD line crosses BELOW signal line Histogram: positive → negative Strength filters: ✅ Strong: occurs above zero line (early trend) ⚠️ Medium: occurs near zero line ❌ Weak: occurs far below zero (late, risky) Entry: Sell/short on close after crossover confirms Stop: Above recent swing high Target: Previous support or 2:1 R:R 【Zero Line Crossover】 MACD crosses above zero = bullish trend confirmed MACD crosses below zero = bearish trend confirmed More significant than signal crossover but lags more. Use as trend filter, not entry trigger. 【False Crossover Filters】 Skip crossover if: - Histogram bar is tiny (< 0.05) - Crossover happens in choppy sideways market - Volume is declining during crossover - Price is inside a tight range Confirm with: - Volume spike on crossover bar - Price breaks key support/resistance - RSI confirms direction (> 50 bullish, < 50 bearish) 📖 More skills: bytesagain.com EOF } cmd_histogram() { cat << 'EOF' ═══════════════════════════════════════════════════ MACD Histogram Deep Dive ═══════════════════════════════════════════════════ 【What the Histogram Shows】 Histogram = MACD Line - Signal Line Positive bars: MACD above signal (bullish momentum) Negative bars: MACD below signal (bearish momentum) Bar height = momentum strength 【Alexander Elder's Histogram Rules】 1. Histogram rising = momentum increasing (don't short) 2. Histogram falling = momentum decreasing (don't buy) 3. New histogram peak > previous peak = strong trend 4. New histogram peak < previous peak = weakening trend (divergence!) 【Histogram Divergence (Most Powerful Signal)】 Bullish: Price makes lower low, histogram makes higher low → Selling exhaustion, reversal likely → Best signal when histogram is below zero Bearish: Price makes higher high, histogram makes lower high → Buying exhaustion, reversal likely → Best signal when histogram is above zero 【Reading Histogram Shape】 Expanding bars (growing taller): → Trend accelerating, stay in trade Contracting bars (getting shorter): → Trend decelerating, prepare for reversal → Tighten stops, take partial profits Bars crossing zero: → Crossover event (see crossover command) 【Common Mistakes】 ❌ Trading histogram in isolation ❌ Ignoring the actual bar height (tiny = meaningless) ❌ Fighting expanding histogram (counter-trend trading) ✅ Use histogram + price action + volume together 📖 More skills: bytesagain.com EOF } cmd_strategies() { cat << 'EOF' ═══════════════════════════════════════════════════ MACD Trading Strategies ═══════════════════════════════════════════════════ 【Strategy 1: Classic Crossover】 Entry: MACD crosses above signal → BUY MACD crosses below signal → SELL Stop: Below/above recent swing Target: 2:1 reward-to-risk minimum Filter: Only trade crossovers in direction of daily trend Best: Trending markets 【Strategy 2: Zero Line Rejection】 Setup: MACD pulls back toward zero but does not cross Long: MACD dips toward zero, bounces up → BUY Short: MACD rallies toward zero, turns down → SELL Edge: Catches trend continuation after pullback Best: Strong trending markets 【Strategy 3: Histogram Divergence】 Bullish: Price lower low + histogram higher low → BUY Bearish: Price higher high + histogram lower high → SELL Stop: Beyond the divergence swing point Note: Most reliable MACD signal (Elder) Best: Reversals at support/resistance 【Strategy 4: MACD + Moving Average Filter】 Setup: Add 200-period SMA to chart Long: Price > 200 SMA AND MACD bullish crossover → BUY Short: Price < 200 SMA AND MACD bearish crossover → SELL Edge: Filters out counter-trend signals Best: Swing trading (daily chart) 【Strategy 5: Multi-Timeframe MACD】 Weekly MACD: Determines trend direction Daily MACD: Determines entry timing If Weekly MACD > 0 (bullish): → Only take daily bullish crossovers (ignore bearish) If Weekly MACD < 0 (bearish): → Only take daily bearish crossovers (ignore bullish) Edge: Dramatically reduces false signals 【Parameter Variations】 Standard: (12, 26, 9) — most common, balanced Fast: (8, 17, 9) — more signals, more noise Slow: (21, 55, 9) — fewer signals, higher quality Crypto: (12, 26, 9) on 4H chart — best for crypto volatility 📖 More skills: bytesagain.com EOF } cmd_help() { cat << EOF MACD vVERSION — Moving Average Convergence Divergence Calculator Commands: calculate <prices> [fast] [slow] [sig] Compute MACD from comma-separated prices calculate-file <csv> Compute MACD from a CSV file interpret <macd> <sig> Interpret MACD/signal values crossover Crossover patterns and trading rules histogram Histogram analysis guide strategies MACD trading strategies help Show this help version Show version Usage: bash scripts/script.sh calculate "170.5,171.2,...,183.5" bash scripts/script.sh calculate-file prices.csv bash scripts/script.sh interpret 1.25 0.80 Requires: python3 (standard library only) Related skills: clawhub install rsi clawhub install atr Browse all: bytesagain.com Powered by BytesAgain | bytesagain.com EOF } case "-help" in calculate) shift; cmd_calculate "$@" ;; calculate-file) shift; cmd_calculate_file "$@" ;; interpret) shift; cmd_interpret "$@" ;; crossover) cmd_crossover ;; histogram) cmd_histogram ;; strategies) cmd_strategies ;; version) echo "macd vVERSION" ;; help|*) cmd_help ;; esac
Battery Management System reference — cell balancing, SOC estimation, thermal management, and protection circuits. Use when designing BMS for lithium-ion pac...
--- name: "bms" version: "1.0.0" description: "Battery Management System reference — cell balancing, SOC estimation, thermal management, and protection circuits. Use when designing BMS for lithium-ion packs, evaluating battery safety, or understanding cell monitoring." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [bms, battery, lithium-ion, cell-balancing, soc, thermal, energy-storage] category: "energy" --- # BMS — Battery Management System Reference Quick-reference skill for battery management systems, cell monitoring, and pack safety. ## When to Use - Designing a BMS for lithium-ion battery packs - Understanding cell balancing (passive vs active) - Implementing SOC/SOH estimation algorithms - Setting up thermal management and protection thresholds - Evaluating BMS ICs and architectures ## Commands ### `intro` ```bash scripts/script.sh intro ``` Overview of BMS — functions, architecture, and why every Li-ion pack needs one. ### `cellbalance` ```bash scripts/script.sh cellbalance ``` Cell balancing methods: passive (dissipative) vs active (redistributive). ### `soc` ```bash scripts/script.sh soc ``` State of Charge estimation: coulomb counting, OCV lookup, Kalman filter, impedance. ### `protection` ```bash scripts/script.sh protection ``` Protection circuits: overvoltage, undervoltage, overcurrent, short circuit, temperature. ### `thermal` ```bash scripts/script.sh thermal ``` Thermal management — air cooling, liquid cooling, phase change, heating in cold. ### `communication` ```bash scripts/script.sh communication ``` BMS communication protocols: CAN bus, SMBus, I²C, UART, and data frames. ### `topologies` ```bash scripts/script.sh topologies ``` BMS architectures: centralized, distributed, modular — and IC selection. ### `safety` ```bash scripts/script.sh safety ``` Safety standards, failure modes, and functional safety (ISO 26262, IEC 62619). ### `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 # bms — Battery Management System Reference # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="1.0.0" cmd_intro() { cat << 'EOF' === Battery Management System (BMS) === A BMS monitors, protects, and optimizes a rechargeable battery pack. Every lithium-ion pack REQUIRES a BMS — without one, cells can catch fire, explode, or degrade rapidly. Core Functions: 1. Cell Monitoring Measure voltage, current, temperature per cell 2. Protection Prevent overvoltage, undervoltage, overcurrent 3. Cell Balancing Equalize charge across cells in series 4. SOC Estimation Report remaining capacity (fuel gauge) 5. SOH Tracking Track degradation and remaining life 6. Thermal Management Control cooling/heating systems 7. Communication Report data to host system (CAN, SMBus) 8. Logging Record history for diagnostics/warranty Why Cells Need Balancing: No two cells are identical — manufacturing variance: Capacity: ±2–5% between cells in same batch Self-discharge: 2–5%/month variation Impedance: ±5–10% variation Without balancing: Weakest cell hits undervoltage first → limits pack capacity Strongest cell hits overvoltage first → limits pack charging Over time, imbalance grows → usable capacity shrinks Typical BMS Architecture: ┌─────────────────────────────────┐ │ Host / MCU │ │ SOC algo, thermal control, │ │ communication, fault logic │ └──────────┬──────────────────────┘ │ SPI/I²C ┌──────────┴──────────────────────┐ │ Analog Front End (AFE) │ │ Cell voltage ADC, current ADC │ │ Temperature ADC, balancing FET │ └──────────┬──────────────────────┘ │ sense wires ┌──────────┴──────────────────────┐ │ Battery Pack (nS × mP) │ │ Cell 1 ─ Cell 2 ─ ... ─ Cell n│ │ NTC thermistors on cells │ └─────────────────────────────────┘ Common Li-ion Cell Limits: NMC (3.6V nom): 2.5V min, 4.2V max, charge 0–45°C, discharge -20–60°C LFP (3.2V nom): 2.0V min, 3.65V max, charge 0–45°C, discharge -20–55°C NCA (3.6V nom): 2.5V min, 4.2V max, charge 0–45°C, discharge -20–60°C EOF } cmd_cellbalance() { cat << 'EOF' === Cell Balancing Methods === Passive Balancing (Dissipative): Bleed energy from high cells through a resistor → heat Simple, cheap, proven — used in 90%+ of BMS designs How it works: Cell voltage > threshold (e.g., 4.15V) → turn on bleed FET Current flows through bleed resistor → cell discharges Continue until all cells within target (e.g., ±10mV) Typical parameters: Bleed current: 50–200 mA (determines balancing speed) Resistor: 47–100Ω per cell Power dissipation: 50mA × 4.2V = 210 mW per cell Time to balance 100mAh: 100mAh / 50mA = 2 hours Limitations: Wastes energy as heat Slow for large imbalances Only works during/near end of charge Limited by thermal dissipation of resistors Active Balancing (Redistributive): Transfer energy from high cells to low cells — no waste! Capacitor Shuttle: Capacitor switches between adjacent cells Simple, moderate efficiency (80–90%) Slow if cells far apart in series string Inductor-Based: Flyback or buck-boost converter between cells Efficiency: 85–95% Fast balancing: 1–5A possible Complex, requires transformer + FETs per cell Cell-to-Pack / Pack-to-Cell: Isolated DC-DC converter Any cell ↔ pack bus Highest flexibility, fastest Most complex and expensive When to Use Active: Pack capacity > 10 kWh (EVs, grid storage) High cycle count applications Second-life battery applications (large initial imbalance) Cost justified by recovered energy Balancing Effectiveness: Passive: recovers 1–3% of pack capacity Active: recovers 3–8% of pack capacity Both: extend pack life by 10–30% EOF } cmd_soc() { cat << 'EOF' === State of Charge (SOC) Estimation === SOC = remaining charge / total usable capacity × 100% Method 1: Coulomb Counting (Current Integration) SOC(t) = SOC(t₀) - ∫ I·dt / Q_total Pros: real-time, works during charge/discharge Cons: drift over time, needs accurate initial SOC, sensor error Error sources: Current sensor accuracy: ±0.5–2% (shunt or Hall effect) ADC resolution and sampling rate Self-discharge not accounted Drift: ~1% SOC error per hour without correction Must be periodically recalibrated (at full/empty) Method 2: OCV-SOC Lookup Table Each chemistry has a voltage-SOC curve (measured offline) Measure open-circuit voltage → look up SOC Pros: simple, no drift, self-correcting Cons: needs long rest (1–4 hours for equilibrium) LFP challenge: very flat OCV curve (3.2–3.3V for 20–80% SOC) → OCV method has poor resolution for LFP NMC: more sloped OCV → better OCV-SOC mapping Method 3: Extended Kalman Filter (EKF) Combines coulomb counting + OCV + battery model Equivalent circuit model: R₀ + R₁//C₁ (+ R₂//C₂) State: SOC, voltage across RC networks Measurement: terminal voltage Correction: model prediction vs actual measurement Pros: accurate (±2% SOC), handles noise, self-correcting Cons: needs battery model parameters, computationally heavier Industry standard for EVs and premium products Method 4: Impedance / EIS AC impedance varies with SOC (especially at low frequency) Requires impedance spectroscopy hardware Used for SOH more than SOC in practice Practical SOC System: 1. EKF for continuous tracking during operation 2. OCV correction during long rest periods 3. Full charge recalibration (reset to 100%) 4. Low-voltage detection for 0% anchor 5. Capacity fade compensation (update Q_total from SOH) EOF } cmd_protection() { cat << 'EOF' === BMS Protection Circuits === Overvoltage Protection (OVP): Threshold: 4.20–4.25V per cell (NMC), 3.65V (LFP) Action: disconnect charger via high-side FET Hysteresis: 50–100mV (re-enable at 4.10V) Response time: <100ms Risk if missing: lithium plating → dendrites → internal short → fire Undervoltage Protection (UVP): Threshold: 2.5–2.8V per cell (NMC), 2.0–2.5V (LFP) Action: disconnect load via low-side FET Hysteresis: 200–500mV (re-enable at 3.0V) Risk if missing: copper dissolution → capacity loss → internal short Overcurrent Protection (OCP): Charge overcurrent: typically 1C limit (set by cell spec) Discharge overcurrent: 2–5C continuous, 10C pulse Measurement: shunt resistor (1–10mΩ) + high-side amp Response: 10–100ms for continuous, 100–500μs for short circuit Action: open discharge FETs, set fault flag Short Circuit Protection (SCP): Threshold: 2–5× overcurrent limit Response: <100μs (hardware comparator, not software!) Implementation: dedicated SCP circuit in AFE IC Must be hardware-based — software too slow for shorts Temperature Protection: Charge disable: <0°C or >45°C (lithium plating risk below 0°C!) Discharge disable: <-20°C or >60°C Thermal shutdown: >70°C (emergency disconnect) Sensors: NTC thermistors (10kΩ at 25°C typical) Placement: on cell surface, between cells, on FET heatsink Minimum: 1 per parallel group, 1 on power FETs Protection FET Sizing: RDS(on) total: <10mΩ for low losses Voltage rating: 1.5× pack voltage minimum Current rating: 2× continuous current Typical: 2 back-to-back N-channel MOSFETs One blocks charge direction One blocks discharge direction Both must be rated for full pack voltage EOF } cmd_thermal() { cat << 'EOF' === BMS Thermal Management === Why Temperature Matters: <0°C: Lithium plating during charge (permanent damage!) 0–10°C: Reduced capacity, high impedance, derate charging 15–35°C: Optimal range for performance and longevity 35–45°C: Accelerated aging (Arrhenius: 2× life loss per 10°C) >45°C: Risk of thermal runaway if combined with abuse >80°C: Separator shrinkage begins >130°C: Thermal runaway cascade in NMC Heat Sources in a Pack: Ohmic (I²R): Dominant at high C-rates Entropic: Reversible heat from entropy changes Contact resistance: Cell tabs, bus bars, connectors BMS electronics: FETs, shunt resistors Cooling Methods: Natural Air Cooling: Consumer electronics, small packs (<500Wh) Relies on pack surface area and ambient Simple, zero energy cost, limited capacity ΔT limit: ~10-15°C above ambient Forced Air Cooling: Fans push air through channels between cells Power electronics, e-bikes, small EVs Effective to ~1-2 kW of heat removal ΔT: 5-10°C above ambient with good airflow Dust/moisture ingress concern Liquid Cooling: Cold plates or cooling channels with glycol-water mix EVs, grid storage, fast-charging systems Heat removal: 5-20 kW+ depending on flow rate ΔT: 2-5°C above coolant temperature Components: pump, radiator, reservoir, cold plates, hoses Complexity: leak risk, weight, cost Phase Change Material (PCM): Paraffin-based: melting point 30-45°C Absorbs heat during melting (latent heat: 200 kJ/kg) Passive, no moving parts, buffers thermal spikes Con: finite capacity, needs regeneration time Cold Weather Heating: Resistive heaters on cell surface or coolant loop Pre-condition before charging in cold weather Typical: heat to >5°C before enabling charge Self-heating: pulse discharge (I²R) to warm cells Power: 50-200W for EV packs during pre-heating EOF } cmd_communication() { cat << 'EOF' === BMS Communication Protocols === CAN Bus (Controller Area Network): Industry standard for automotive and industrial BMS Differential pair, up to 1 Mbit/s (CAN 2.0), 5 Mbit/s (CAN FD) Typical BMS CAN Messages: 0x100: Pack voltage, current, SOC 0x101: Cell voltages 1-4 0x102: Cell voltages 5-8 0x103: Temperature readings 0x104: Fault status flags 0x105: Charge/discharge limits Frame: 11-bit ID + 0-8 bytes data + CRC SAE J1939 for heavy vehicles, CANopen for industrial SMBus / I²C (Smart Battery): Used in: laptops, power tools, medical devices Standard: SBS (Smart Battery Specification) v1.1 Key SBS Registers: 0x0D: RelativeStateOfCharge (%) 0x0F: RemainingCapacity (mAh) 0x10: FullChargeCapacity (mAh) 0x09: Voltage (mV) 0x0A: Current (mA) 0x08: Temperature (0.1K units) 0x16: BatteryStatus (flags) 0x03: BatteryMode Clock: 100 kHz (standard), 400 kHz (fast mode) Addressed: 7-bit address, typically 0x0B for battery UART / RS-485: Simple serial communication for BMS modules Common in solar/energy storage BMS Baud: 9600–115200 typical RS-485 for long distance (up to 1200m) and multi-drop Protocol: often Modbus RTU over RS-485 Daisy-Chain (Cell Monitor ICs): isoSPI (Linear/Analog Devices LTC6811/ADBMS1818) Isolated SPI between stacked ICs Each IC monitors 6–18 cells Chain: up to 100+ ICs in series 1 MHz, transformer-coupled isolation Wireless BMS (wBMS): Emerging: TI, Analog Devices wireless solutions Eliminates cell sense wires (weight, assembly cost) 2.4 GHz proprietary protocols Latency: <2ms for critical measurements Challenge: reliability, EMI, certification Data Logging: Minimum logging: voltage, current, temp, SOC every 1–10 sec Fault events: timestamped with full state snapshot Cycle counting: charge/discharge cycles, DOD histogram Storage: EEPROM, flash, or SD card (10+ years retention) EOF } cmd_topologies() { cat << 'EOF' === BMS Architectures === Centralized BMS: Single PCB with all monitoring and control Wires run from every cell to the central board Pros: simple design, low cost, single point of programming Cons: long wire harness, limited scalability, EMI risk Use: e-bikes, power tools, small ESS (4S–16S) Example ICs: BQ76920 (TI): 3-5S, I²C, integrated FET drivers BQ76940 (TI): 9-15S, I²C ISL94202 (Renesas): 3-8S, integrated balancing Distributed BMS: Slave module on each cell or module → master controller Communication via daisy-chain (isoSPI) or bus Pros: short sense wires, scalable, modular Cons: more components, complex communication Use: EVs (Tesla, BMW), large ESS Example ICs: LTC6811 (ADI): 12 cells/IC, isoSPI daisy-chain ADBMS1818 (ADI): 18 cells/IC, next-gen LTC6811 MAX17853 (Maxim): 14 cells, UART daisy-chain MC33771C (NXP): 14 cells, TPL (transformer) Modular BMS: Each battery module has its own complete BMS Modules connect to system controller via CAN/Ethernet Pros: hot-swappable, fault isolation, mix-and-match Cons: highest cost, redundant components Use: grid storage, UPS, telecom, containerized ESS Choosing an Architecture: Cells Architecture Typical IC ──── ──────────── ────────── 3-8S Centralized BQ76920, ISL94202 8-16S Centralized BQ76940, ISL94203 16-100S Distributed LTC6811, ADBMS1818 100S+ Distributed LTC6811 chain (up to 100+) Modular Modular Any + CAN master Key IC Selection Criteria: Cell count per IC: 3–18 cells Measurement accuracy: <±2mV cell voltage Current measurement: <±0.5% (coulomb counting accuracy) Balancing current: 50–200mA internal, external FET for more Communication: I²C, SPI, isoSPI, UART Functional safety: ASIL-rated for automotive Cost per channel: $0.50–$3.00 per cell EOF } cmd_safety() { cat << 'EOF' === BMS Safety Standards === Failure Modes: Cell-level: Internal short circuit → thermal runaway Lithium plating → dendrite growth → short Electrolyte decomposition → gas generation → venting Tab weld failure → high resistance → hot spot Pack-level: Propagation: one cell fails → heats neighbors → cascade Connector failure → arcing Coolant leak → electrical short BMS failure → loss of protection BMS failure modes: Voltage measurement error → over/undercharge Current sensor failure → wrong SOC FET stuck closed → no protection FET stuck open → no output Communication loss → blind operation Software bug → incorrect fault thresholds Thermal Runaway Prevention: Layer 1: BMS protection (voltage, current, temperature limits) Layer 2: Cell-level safety (CID, PTC, shutdown separator) Layer 3: Pack design (propagation barriers, venting) Layer 4: System design (enclosure, fire suppression) Standards: IEC 62619 (Stationary Storage): Cell and battery safety for industrial Tests: short circuit, overcharge, crush, thermal abuse Mandatory for grid storage in many markets UN 38.3 (Transport): MANDATORY for shipping lithium batteries 8 tests: altitude, thermal, vibration, shock, short, impact, overcharge, forced discharge Must pass before any battery can be transported UL 2580 (EV Batteries): Safety standard for EV battery packs Fire exposure, short circuit, overcharge, over-discharge Crush, impact, immersion ISO 26262 (Automotive Functional Safety): ASIL levels: A (lowest) to D (highest) BMS typically ASIL-C or ASIL-D Requires: FMEA, safety architecture, diagnostic coverage Dual-path protection: hardware + software redundancy Example: overvoltage protection Path 1: BMS software monitors voltage → opens FET Path 2: Hardware comparator → opens FET independently Both paths must work independently IEC 62133 (Portable): Consumer electronics batteries Cell and battery tests for portable applications EOF } show_help() { cat << EOF bms v$VERSION — Battery Management System Reference Usage: script.sh <command> Commands: intro BMS overview, functions, architecture cellbalance Passive vs active cell balancing methods soc State of Charge estimation algorithms protection OVP, UVP, OCP, SCP, temperature protection thermal Cooling and heating methods for battery packs communication CAN, SMBus, UART, daisy-chain protocols topologies Centralized, distributed, modular architectures safety Standards: IEC 62619, UN 38.3, ISO 26262 help Show this help version Show version Powered by BytesAgain | bytesagain.com EOF } CMD="-help" case "$CMD" in intro) cmd_intro ;; cellbalance) cmd_cellbalance ;; soc) cmd_soc ;; protection) cmd_protection ;; thermal) cmd_thermal ;; communication) cmd_communication ;; topologies) cmd_topologies ;; safety) cmd_safety ;; help|--help|-h) show_help ;; version|--version|-v) echo "bms v$VERSION — Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: script.sh help"; exit 1 ;; esac
Data trimming reference — whitespace trimming, string cleanup, data truncation, outlier trimming, and signal processing. Use when cleaning text data, removin...
--- name: "trim" version: "1.0.0" description: "Data trimming reference — whitespace trimming, string cleanup, data truncation, outlier trimming, and signal processing. Use when cleaning text data, removing noise, or preparing datasets by trimming unwanted elements." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [trim, clean, strip, whitespace, truncate, outlier, data-processing, atomic] category: "atomic" --- # Trim — Data Trimming Reference Quick-reference skill for data trimming techniques across text, numeric, and signal data. ## When to Use - Trimming whitespace from strings (leading, trailing, internal) - Cleaning and normalizing text data - Trimming outliers from statistical datasets - Truncating data to fit constraints (columns, buffers) - Signal trimming and noise removal - Database column trimming and cleanup ## Commands ### `intro` ```bash scripts/script.sh intro ``` Overview of trimming — concepts, types, and when to use each. ### `string` ```bash scripts/script.sh string ``` String trimming — whitespace, characters, patterns, normalization. ### `numeric` ```bash scripts/script.sh numeric ``` Numeric trimming — outliers, percentile clipping, winsorizing. ### `text` ```bash scripts/script.sh text ``` Text data cleaning — encoding, invisible characters, BOM removal. ### `database` ```bash scripts/script.sh database ``` Database trimming — SQL functions, column cleanup, data migration. ### `signal` ```bash scripts/script.sh signal ``` Signal and time-series trimming — noise removal, smoothing, clipping. ### `examples` ```bash scripts/script.sh examples ``` Practical trimming examples across languages and tools. ### `pitfalls` ```bash scripts/script.sh pitfalls ``` Common trimming pitfalls and best practices. ### `help` ```bash scripts/script.sh help ``` ### `version` ```bash scripts/script.sh version ``` ## Configuration | Variable | Description | |----------|-------------| | `TRIM_DIR` | Data directory (default: ~/.trim/) | --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # trim — Data Trimming Reference # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="1.0.0" cmd_intro() { cat << 'EOF' === Data Trimming — Overview === Trimming is the process of removing unwanted elements from the edges or extremes of data — whitespace from strings, outliers from datasets, noise from signals. Types of Trimming: String Trimming Remove leading/trailing whitespace or specific characters Most common: trim(), strip(), ltrim(), rtrim() Numeric Trimming Remove extreme values (outliers) from datasets Methods: percentile clipping, z-score filtering, winsorizing Text Cleaning Remove invisible characters, BOM, control characters Normalize Unicode, fix encoding issues Signal Trimming Remove noise, clip amplitude, smooth edges Window functions, moving averages, low-pass filters Data Truncation Shorten data to fit constraints (column width, buffer size) May lose information — handle carefully When to Trim: ✓ User input (always trim form inputs) ✓ CSV/Excel imports (often have trailing spaces) ✓ Database cleanup (legacy data with padding) ✓ API responses (inconsistent formatting) ✓ Statistical analysis (outlier removal) ✓ Log parsing (strip timestamps, levels) When NOT to Trim: ✗ Passwords (spaces may be intentional) ✗ Code/source files (indentation matters) ✗ Binary data (every byte counts) ✗ Pre-formatted text (markdown, ASCII art) ✗ Cryptographic data (integrity depends on exact bytes) Trim vs Strip vs Truncate: Trim Remove from both ends (usually whitespace) Strip Same as trim (Python/Ruby terminology) Truncate Cut to maximum length (lose data) Clip Limit values to range (numeric) Chomp Remove trailing newline only (Perl/Ruby) EOF } cmd_string() { cat << 'EOF' === String Trimming === Basic Whitespace Trimming: Leading: " hello" → "hello" (ltrim/lstrip) Trailing: "hello " → "hello" (rtrim/rstrip) Both: " hello " → "hello" (trim/strip) What Counts as Whitespace: Space (U+0020) Standard space Tab (U+0009) Horizontal tab Newline (U+000A) Line feed CR (U+000D) Carriage return NBSP (U+00A0) Non-breaking space (often missed!) Zero-width (U+200B) Zero-width space (invisible) Form feed (U+000C) Form feed Vertical tab (U+000B) Vertical tab Warning: Many trim functions only handle ASCII whitespace Unicode-aware trimming must handle NBSP, ideographic space, etc. Character-Specific Trimming: Remove specific characters from edges Python: "###hello###".strip("#") → "hello" Ruby: "hello\n".chomp → "hello" (newline only) SQL: TRIM(BOTH '#' FROM '###hello###') → 'hello' Internal Whitespace Normalization: Collapse multiple spaces to single: "hello world" → "hello world" Regex: s/\s+/ /g (replace multiple whitespace with single space) Python: " ".join(text.split()) Normalize line endings: \r\n → \n (Windows to Unix) \r → \n (old Mac to Unix) Null Byte Trimming: Remove NUL characters (U+0000) Common in: C strings, database imports, binary-text boundaries Important: NUL can cause truncation in some languages Trimming by Pattern: Remove prefix: "data:image/png;base64,..." → strip prefix Remove suffix: "file.txt.bak" → remove .bak Remove enclosing: "'hello'" → strip quotes Remove HTML tags: "<p>text</p>" → "text" Remove ANSI codes: "\033[31mred\033[0m" → "red" Language Quick Reference: Python: s.strip() / s.lstrip() / s.rstrip() JS: s.trim() / s.trimStart() / s.trimEnd() Java: s.trim() / s.strip() (Java 11+, Unicode-aware) C#: s.Trim() / s.TrimStart() / s.TrimEnd() Go: strings.TrimSpace(s) / strings.Trim(s, chars) Rust: s.trim() / s.trim_start() / s.trim_end() Ruby: s.strip / s.lstrip / s.rstrip / s.chomp PHP: trim($s) / ltrim($s) / rtrim($s) Bash: "space:]]*"}" (parameter expansion) EOF } cmd_numeric() { cat << 'EOF' === Numeric Trimming === Outlier Detection and Removal: Z-Score Method: Remove values more than N standard deviations from mean Typical threshold: |z| > 3 (99.7% of normal data) Formula: z = (x - μ) / σ Pros: Simple, well-understood Cons: Assumes normal distribution, sensitive to outliers themselves Python: from scipy import stats z = np.abs(stats.zscore(data)) filtered = data[z < 3] IQR Method (Interquartile Range): Q1 = 25th percentile, Q3 = 75th percentile IQR = Q3 - Q1 Lower fence = Q1 - 1.5 × IQR Upper fence = Q3 + 1.5 × IQR Remove values outside fences Pros: Robust to non-normal distributions Cons: May be too aggressive for skewed data Python: Q1 = data.quantile(0.25) Q3 = data.quantile(0.75) IQR = Q3 - Q1 filtered = data[(data >= Q1-1.5*IQR) & (data <= Q3+1.5*IQR)] Percentile Clipping: Remove top and bottom N% of values Example: Trim 1% from each tail (keep 1st-99th percentile) Python: lower = data.quantile(0.01) upper = data.quantile(0.99) trimmed = data[(data >= lower) & (data <= upper)] Winsorizing: Like clipping but REPLACE extreme values instead of removing Set extremes to the boundary value Preserves dataset size (important for some analyses) Python (scipy): from scipy.stats.mstats import winsorize result = winsorize(data, limits=[0.05, 0.05]) Trimmed Mean: Calculate mean after removing extreme values Example: 10% trimmed mean = drop top and bottom 10%, then average More robust than mean, more efficient than median Python: scipy.stats.trim_mean(data, proportiontocut=0.1) MAD Method (Median Absolute Deviation): MAD = median(|xi - median(x)|) Modified z-score = 0.6745 × (xi - median) / MAD Remove if |modified z-score| > 3.5 Most robust method (resistant to outlier influence) Best Practices: 1. Visualize before trimming (histogram, box plot) 2. Document trimming criteria and how many removed 3. Compare results with and without trimming 4. Consider: Are "outliers" actually valid data? 5. Domain knowledge > statistical rules EOF } cmd_text() { cat << 'EOF' === Text Data Cleaning === BOM (Byte Order Mark) Removal: UTF-8 BOM: EF BB BF (3 bytes at file start) UTF-16 BOM: FF FE or FE FF Problem: Appears as invisible character, breaks parsers Detection and removal: Bash: sed '1s/^\xEF\xBB\xBF//' file.txt Python: text.encode().lstrip(b'\xef\xbb\xbf').decode() Node: text.replace(/^\uFEFF/, '') Control Character Removal: ASCII 0-31 (except 9=tab, 10=LF, 13=CR): Characters 0-8, 11, 12, 14-31 are control characters Rarely meaningful in text data Remove: regex [^\x20-\x7E\x09\x0A\x0D] (keep printable + tab/newline) Common offenders: \x00 NUL Null character (C string terminator) \x01 SOH Sometimes used as field separator \x1B ESC ANSI escape sequences \x7F DEL Delete character Unicode Normalization: NFC: Composed form (é = single code point U+00E9) NFD: Decomposed form (é = e + combining accent U+0065 U+0301) NFKC: Compatibility composed (fi → fi) NFKD: Compatibility decomposed Rule: Normalize to NFC for storage and comparison Python: unicodedata.normalize('NFC', text) Why it matters: "café" (NFC) ≠ "café" (NFD) in byte comparison But they look identical to humans Invisible Character Removal: Zero-width space: U+200B Zero-width joiner: U+200D Zero-width non-joiner: U+200C Left-to-right mark: U+200E Right-to-left mark: U+200F Soft hyphen: U+00AD Word joiner: U+2060 These cause: search failures, comparison failures, display issues Often injected by: copy-paste from web, Word documents, PDFs Encoding Cleanup: Mojibake: Text displayed with wrong encoding "Café" = UTF-8 bytes displayed as Latin-1 Fix: 1. Detect actual encoding (chardet, file command) 2. Decode with correct encoding 3. Re-encode as UTF-8 Python: import chardet detected = chardet.detect(raw_bytes) text = raw_bytes.decode(detected['encoding']) HTML Entity Cleanup: & → & < → < > → > " → " ' → ' ' → ' Python: html.unescape(text) JS: Use DOMParser or textarea trick EOF } cmd_database() { cat << 'EOF' === Database Trimming === SQL TRIM Functions: Standard SQL: TRIM(string) -- both sides, spaces TRIM(LEADING FROM string) -- left side TRIM(TRAILING FROM string) -- right side TRIM(BOTH 'x' FROM string) -- specific character PostgreSQL: TRIM(string) -- whitespace BTRIM(string, chars) -- both sides, specific chars LTRIM(string, chars) -- left RTRIM(string, chars) -- right REGEXP_REPLACE(s, '^\s+|\s+$', '', 'g') -- regex trim MySQL: TRIM(string) LTRIM(string) RTRIM(string) TRIM(BOTH char FROM string) SQL Server: LTRIM(RTRIM(string)) -- both sides (pre-2017) TRIM(string) -- SQL Server 2017+ TRIM(chars FROM string) -- SQL Server 2017+ Bulk Data Cleanup: -- Trim all varchar columns in a table UPDATE customers SET name = TRIM(name), email = LOWER(TRIM(email)), phone = REGEXP_REPLACE(TRIM(phone), '[^0-9]', '', 'g'); -- Find rows with leading/trailing whitespace SELECT * FROM customers WHERE name != TRIM(name); -- Count affected rows before updating SELECT COUNT(*) FROM customers WHERE name != TRIM(name) OR email != TRIM(email); CHAR vs VARCHAR Padding: CHAR(10): 'hello ' (padded with spaces to 10) VARCHAR(10): 'hello' (no padding) Gotcha: CHAR columns always right-padded with spaces Fix: RTRIM when comparing or migrating CHAR to VARCHAR Migration: ALTER TABLE t ALTER COLUMN c TYPE VARCHAR(50); Data Type Considerations: Numbers stored as strings: TRIM then CAST SELECT CAST(TRIM(price_str) AS DECIMAL(10,2)) Dates stored as strings: TRIM then PARSE SELECT TO_DATE(TRIM(date_str), 'YYYY-MM-DD') NULLs: TRIM(NULL) returns NULL Use COALESCE: COALESCE(TRIM(name), '') Performance Tips: - Add WHERE clause to limit affected rows - Batch large updates (1000-10000 rows at a time) - Create index on trimmed value for searching - Consider computed/generated columns for trimmed values - Add CHECK constraint to prevent future whitespace ALTER TABLE t ADD CONSTRAINT chk_name CHECK (name = TRIM(name)); EOF } cmd_signal() { cat << 'EOF' === Signal & Time-Series Trimming === Amplitude Clipping: Limit signal values to a range [min, max] Values beyond range set to the boundary value Hard clipping: if x > max: x = max if x < min: x = min Soft clipping (sigmoid): Smooth transition near boundaries tanh(x) for symmetric clipping Used in audio to avoid harsh distortion numpy: np.clip(signal, -1.0, 1.0) Moving Average (Smoothing): Simple Moving Average (SMA): Average of last N values Removes high-frequency noise Lag: N/2 time steps Exponential Moving Average (EMA): Recent values weighted more heavily EMA = α × current + (1-α) × previous_EMA Less lag than SMA Weighted Moving Average (WMA): Custom weights for each position in window Noise Floor Trimming: Remove signal below a threshold (considered noise) Common in audio: - Noise gate: Mute signal below threshold - Expander: Reduce (not mute) signal below threshold Spectral: Remove frequency components below noise floor Threshold selection: - Measure noise during silence - Set threshold 6-10dB above noise floor Edge Trimming (Time-Series): Remove startup transients: First N samples may be unreliable (sensor warmup) Remove initial stabilization period Remove trailing data: After shutdown or end of experiment After quality degrades (sensor failure) Trim to analysis window: Start/end at specific timestamps Align to external events Spike Removal: Detect and remove impulse noise / glitches Methods: - Median filter: Replace each value with median of neighbors - Threshold: Remove values > N × standard deviation from local mean - Hampel filter: Uses median absolute deviation for robust detection Important: Don't remove real peaks! Use domain knowledge to distinguish spikes from valid data Decimation (Downsampling): Reduce sample rate by keeping every Nth sample Must apply anti-aliasing filter first (low-pass) Without filter → aliasing artifacts Process: 1. Low-pass filter at new_rate/2 (Nyquist) 2. Take every Nth sample 3. Verify no aliasing in frequency domain EOF } cmd_examples() { cat << 'EOF' === Practical Trimming Examples === --- Bash --- # Trim whitespace from variable trimmed=$(echo " hello " | xargs) # Trim using parameter expansion var=" hello " var="space:]]*"}" # ltrim var="space:]]"}" # rtrim # Trim BOM from file sed -i '1s/^\xEF\xBB\xBF//' file.txt # Trim blank lines from beginning/end of file sed -i '/./,$!d' file.txt # leading blank lines sed -i -e :a -e '/^\n*$/{$d;N;ba' -e '}' file.txt # trailing --- Python --- # Basic trim " hello ".strip() # 'hello' " hello ".lstrip() # 'hello ' " hello ".rstrip() # ' hello' # Trim specific characters "###hello###".strip("#") # 'hello' "hello\n\r".strip() # 'hello' # Normalize whitespace " ".join(" hello world ".split()) # 'hello world' # Trim outliers (pandas) import pandas as pd q_low = df['col'].quantile(0.01) q_high = df['col'].quantile(0.99) df_trimmed = df[(df['col'] >= q_low) & (df['col'] <= q_high)] --- JavaScript --- " hello ".trim() // 'hello' " hello ".trimStart() // 'hello ' " hello ".trimEnd() // ' hello' // Trim and normalize str.replace(/^\s+|\s+$/g, '') // trim str.replace(/\s+/g, ' ').trim() // normalize whitespace --- SQL --- -- Cleanup user input UPDATE users SET email = LOWER(TRIM(email)), name = TRIM(REGEXP_REPLACE(name, '\s+', ' ', 'g')); -- Find padded data SELECT id, name, LENGTH(name), LENGTH(TRIM(name)) FROM users WHERE name != TRIM(name); --- Data Pipeline --- # Full text cleaning pipeline import unicodedata, re, html def clean_text(text): text = text.strip() # 1. Trim whitespace text = unicodedata.normalize('NFC', text) # 2. Normalize Unicode text = html.unescape(text) # 3. Decode HTML entities text = re.sub(r'[\x00-\x08\x0b\x0c\x0e-\x1f]', '', text) # 4. Control chars text = re.sub(r'\s+', ' ', text) # 5. Normalize spaces return text EOF } cmd_pitfalls() { cat << 'EOF' === Trimming Pitfalls & Best Practices === Pitfall 1: Trimming Passwords NEVER trim user passwords! " my password " is a valid password Leading/trailing spaces are intentional Only trim: usernames, emails, search queries Pitfall 2: Non-Breaking Spaces (NBSP) Many trim() functions DON'T remove NBSP (U+00A0) Common source: copy-paste from Word, websites JavaScript trim() handles NBSP Java trim() does NOT (use strip() in Java 11+) Always test with NBSP in your data Pitfall 3: Over-Trimming Numeric Data Removing "outliers" that are actually valid Example: Removing all incomes > $1M (they're real!) Rule: Understand your data before trimming Always justify why a value is invalid, not just unusual Pitfall 4: Trimming Before Validation User enters " " (just spaces) After trim: "" (empty string) Validation passes if you don't check for empty Rule: Trim THEN validate (including empty check) Pitfall 5: Lossy Truncation Truncating UTF-8 at byte boundary → corrupted characters "Hello 世界" truncated at 8 bytes → "Hello \xe4\xb8" (broken) Always truncate at character or grapheme boundary Python: text[:max_chars] (character-safe) But emoji: "👨👩👧👦" is 1 grapheme, 7 code points, 25 bytes! Pitfall 6: Database CHAR Type Surprises CHAR(50) stores "hello" as "hello" + 45 spaces Comparing CHAR to VARCHAR may fail unexpectedly PostgreSQL: CHAR = is space-padded aware MySQL: Depends on collation settings Best practice: Use VARCHAR, not CHAR Pitfall 7: Trimming in Wrong Order Pipeline: trim → lowercase → remove punctuation Not: remove punctuation → trim (punctuation at edges gone first) Order matters for consistent results Best Practices: 1. Trim at input boundaries (forms, APIs, file imports) 2. Store clean data (don't trim at query time) 3. Validate AFTER trimming 4. Log how many values were modified by trimming 5. Use Unicode-aware trim functions 6. Test with edge cases: empty string, all whitespace, NBSP 7. Document your trimming policy (what gets trimmed where) 8. Never trim binary data or passwords EOF } show_help() { cat << EOF trim v$VERSION — Data Trimming Reference Usage: script.sh <command> Commands: intro Trimming concepts, types, and when to use string String trimming — whitespace, characters, patterns numeric Numeric trimming — outliers, clipping, winsorizing text Text cleaning — encoding, BOM, invisible characters database Database trimming — SQL functions, CHAR vs VARCHAR signal Signal trimming — noise removal, smoothing, clipping examples Practical examples across languages pitfalls Common pitfalls and best practices help Show this help version Show version Powered by BytesAgain | bytesagain.com EOF } CMD="-help" case "$CMD" in intro) cmd_intro ;; string) cmd_string ;; numeric) cmd_numeric ;; text) cmd_text ;; database) cmd_database ;; signal) cmd_signal ;; examples) cmd_examples ;; pitfalls) cmd_pitfalls ;; help|--help|-h) show_help ;; version|--version|-v) echo "trim v$VERSION — Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: script.sh help"; exit 1 ;; esac
FERPA compliance reference — student records privacy, educational rights, consent requirements, and institutional obligations under the Family Educational Ri...
--- name: "ferpa" version: "1.0.0" description: "FERPA compliance reference — student records privacy, educational rights, consent requirements, and institutional obligations under the Family Educational Rights and Privacy Act. Use when handling student data, designing education software, or advising on records disclosure." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [ferpa, education, privacy, student-records, compliance, legal] category: "legal" --- # FERPA — Student Privacy Compliance Reference Quick-reference skill for FERPA requirements, student records handling, and educational privacy compliance. ## When to Use - Determining what constitutes an "education record" - Understanding when parental vs student consent is required - Designing systems that handle student data - Handling records disclosure requests - Implementing FERPA-compliant data sharing policies ## Commands ### `intro` ```bash scripts/script.sh intro ``` Overview of FERPA — scope, history, and key definitions. ### `rights` ```bash scripts/script.sh rights ``` Student and parent rights under FERPA — access, amendment, consent, complaints. ### `records` ```bash scripts/script.sh records ``` What is (and isn't) an education record — definitions and examples. ### `directory` ```bash scripts/script.sh directory ``` Directory information — what can be disclosed without consent. ### `exceptions` ```bash scripts/script.sh exceptions ``` FERPA exceptions — when disclosure is permitted without consent. ### `technology` ```bash scripts/script.sh technology ``` FERPA and technology — cloud services, LMS, edtech vendor agreements. ### `penalties` ```bash scripts/script.sh penalties ``` FERPA enforcement, penalties, and complaint procedures. ### `checklist` ```bash scripts/script.sh checklist ``` FERPA compliance checklist for institutions and vendors. ### `help` ```bash scripts/script.sh help ``` ### `version` ```bash scripts/script.sh version ``` ## Configuration | Variable | Description | |----------|-------------| | `FERPA_DIR` | Data directory (default: ~/.ferpa/) | --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # ferpa — FERPA Compliance Reference # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="1.0.0" cmd_intro() { cat << 'EOF' === FERPA — Family Educational Rights and Privacy Act === FERPA (20 U.S.C. § 1232g) is a federal law that protects the privacy of student education records. Also known as the Buckley Amendment. Enacted: 1974 (amended multiple times since) Enforced by: U.S. Department of Education, FPCO (Family Policy Compliance Office) Who Must Comply: Any educational institution that receives federal funding Includes: public schools K-12, most colleges/universities Does NOT directly apply to: private schools without federal funds Note: nearly all colleges receive federal student aid = FERPA applies Key Definitions: Eligible Student: Student who has reached 18 years old OR attends a postsecondary institution at any age Rights transfer from parent to student at this point Education Records: Records directly related to a student AND maintained by the institution or a party acting for it Format doesn't matter: paper, digital, film, microfilm School Official: Person with a legitimate educational interest Includes: teachers, administrators, counselors, attorneys, auditors, contractors with service agreements Legitimate Educational Interest: Official needs the record to fulfill professional responsibilities This is the key test for internal access Core Principles: 1. Parents/students have the right to inspect records 2. Parents/students can request amendments 3. Institutions need written consent for most disclosures 4. Certain exceptions allow disclosure without consent 5. Institutions must notify students of their FERPA rights annually EOF } cmd_rights() { cat << 'EOF' === FERPA Rights === --- Right to Inspect and Review --- Who: Parents (K-12) or eligible students (18+ or postsecondary) What: All education records maintained by the institution When: Institution must respond within 45 days of request How: Cannot charge for copies if it would prevent access Can charge reasonable copy fees otherwise Institution must NOT: - Destroy records after a request is made - Refuse access because of outstanding fees (debatable, see case law) - Require students to explain why they want to see records --- Right to Request Amendment --- If a record is inaccurate, misleading, or violates privacy: 1. Student/parent requests amendment in writing 2. Institution decides within reasonable time 3. If denied → institution must inform of right to a hearing 4. Hearing → impartial official reviews evidence 5. If still denied → student can place a statement in the record Important limitations: - Cannot challenge a grade through FERPA amendment process - Cannot challenge substantive judgments (teacher's academic evaluation) - Only factual accuracy and relevance can be challenged --- Right to Consent --- Written consent required before disclosure, must include: - Specific records to be disclosed - Purpose of disclosure - Identity of parties receiving records - Signature and date Consent can be electronic if it: - Identifies and authenticates the person - Indicates the person's approval of the information --- Right to File Complaints --- Filed with: Family Policy Compliance Office (FPCO) Address: U.S. Department of Education 400 Maryland Avenue, SW Washington, DC 20202-5920 Deadline: within 180 days of alleged violation or within 180 days of learning about it --- Annual Notification --- Institutions must annually notify eligible students of: - Right to inspect and review records - Right to seek amendment - Right to consent to disclosures - FERPA exceptions to consent - Right to file complaints with FPCO Method: student handbook, catalog, email, website EOF } cmd_records() { cat << 'EOF' === Education Records — What Counts === --- IS an Education Record --- Transcripts and grade reports Class schedules and enrollment status Financial aid records Student account / billing records Disciplinary records Special education records (IEP, 504 plans) Admissions records (for enrolled students) Email about a student (if maintained by institution) Learning management system (LMS) data Student ID photos Disability accommodation documentation --- IS NOT an Education Record --- Sole Possession Records: Notes kept by a single school official Used only as personal memory aids Not shared with anyone else Example: teacher's private grade book notes ⚠ If shared with anyone → becomes education record Law Enforcement Records: Created by campus law enforcement unit For law enforcement purposes Maintained separately from education records Not shared with non-law enforcement school officials Employment Records: When student is employed by institution NOT related to student status ⚠ Work-study records ARE education records Medical/Treatment Records: Created by health professionals Used only for treatment purposes Shared only with professionals treating the student ⚠ If shared with non-treatment staff → education record Alumni Records: Information collected AFTER the person is no longer a student Records from when they WERE a student are still protected De-identified Records: Personally identifiable information removed No reasonable basis to identify the student Can be disclosed freely --- Gray Areas --- Student email metadata: generally yes (institutional records) CCTV footage of student: depends on context and maintenance Peer-graded assignments: not education records until recorded by teacher Letters of recommendation: student can waive access rights EOF } cmd_directory() { cat << 'EOF' === Directory Information === Directory information CAN be disclosed without consent, but only if the institution has properly notified students. --- Typical Directory Information --- Student name Address (local and permanent) Email address Phone number Date and place of birth Major field of study Enrollment status (full-time, half-time, etc.) Dates of attendance Degrees and awards received Most recent previous institution attended Participation in officially recognized activities/sports Weight and height (for athletic team members) Photograph --- NOT Directory Information --- Social Security Number (NEVER) Student ID number (unless it can't be used for access) Grades or GPA Race, ethnicity, nationality Gender (in most policies) Disability status Financial information --- Opt-Out Requirements --- Before disclosing directory information: 1. Institution must define what it considers directory information 2. Notify all students annually 3. Give students reasonable period to opt out 4. Track and honor opt-out requests If a student opts out: - NO directory information released about that student - Includes: graduation programs, dean's list, athletic rosters - Cannot even confirm the student is enrolled --- Solomon Amendment --- Federal law requiring institutions to provide directory information to military recruiters upon request Students CANNOT opt out of Solomon Amendment disclosures Information limited to: name, address, phone, age, class level, major --- Best Practices --- 1. Define directory info as narrowly as possible 2. Never include SSN or grades as directory info 3. Process opt-outs before each disclosure, not just annually 4. Use "limited directory information" — smaller subset for each purpose 5. When in doubt, get consent — it's safer than assuming directory info EOF } cmd_exceptions() { cat << 'EOF' === FERPA Exceptions — Disclosure Without Consent === FERPA allows disclosure without consent in these situations: 1. School Officials with Legitimate Educational Interest Teachers, administrators, counselors, attorneys, auditors Board members, contractors performing institutional functions Must be specified in annual notification 2. Transfer to Another School Records sent to school where student seeks to enroll Condition: institution must attempt to notify student Must provide copy of records if requested 3. Financial Aid Disclosure related to determining eligibility, amount, conditions, or enforcement of financial aid terms 4. State and Local Authorities (Juvenile Justice) Information shared with juvenile justice system Under specific state statutes 5. Accrediting Organizations For accreditation-related purposes 6. Compliance with Judicial Order or Subpoena Must make reasonable effort to notify student BEFORE disclosure Exception: if court order says not to notify (law enforcement subpoena) 7. Health or Safety Emergency To appropriate parties to protect health/safety of student or others Must be articulable and significant threat Strictest standard — not for general safety concerns Must consider: severity, need for information, time urgency 8. Directory Information Only if properly designated and notification/opt-out procedure followed 9. Victim of Crime of Violence Victim can be informed of results of disciplinary proceeding Limited to: name of student, violation, sanctions imposed 10. Drug/Alcohol Violations (Under 21) Institution may notify parents when student under 21 violates drug or alcohol laws/policies 11. Sex Offender Registration Information provided under sex offender registration programs 12. IRS for Tax Purposes Student enrollment and financial data for tax compliance 13. Studies by or for the Institution To organizations conducting studies to improve instruction Requires: written agreement, no further disclosure, data destruction plan EOF } cmd_technology() { cat << 'EOF' === FERPA and Technology === --- Cloud Services and SaaS --- Cloud vendors handling student data must be treated as "school officials" under FERPA. Required: written agreement with vendor specifying: - Vendor performs institutional function - Under direct control of institution - Only uses data for authorized purposes - Cannot re-disclose to third parties - Complies with FERPA requirements Common services requiring agreements: LMS (Canvas, Blackboard, Moodle) SIS (Student Information Systems) Email (Google Workspace for Education, Microsoft 365) Cloud storage (Google Drive, OneDrive) Anti-plagiarism (Turnitin) Video conferencing (Zoom, Teams) Analytics platforms --- Data Sharing Agreements --- Template elements: Parties involved Specific data elements shared Purpose and permitted uses Data security requirements (encryption, access controls) Prohibition on re-disclosure Data retention and destruction schedule Breach notification procedures Audit rights --- EdTech Vendor Checklist --- Before adopting a new edtech tool: [ ] Vendor agreement covers FERPA requirements [ ] Data stays in US (or complies with institution policy) [ ] Encryption in transit (TLS 1.2+) and at rest [ ] Access controls — role-based, least privilege [ ] Audit logging of access to student data [ ] Data minimization — only necessary data collected [ ] Data deletion — process after contract ends [ ] Breach notification — vendor must notify institution promptly --- Student Data in AI/ML --- Training ML models on student data raises FERPA issues: - Is the training data de-identified? (must be truly anonymous) - Can the model output identify individual students? - Who has access to the trained model? - Is the AI vendor a "school official"? - Are students notified about AI use in their education? Safe approach: - Use aggregate/de-identified data for model training - Execute student agreement for AI vendors - Clearly communicate AI use in privacy notices - Allow students to opt out of AI-driven features EOF } cmd_penalties() { cat << 'EOF' === FERPA Enforcement & Penalties === --- Enforcement Mechanism --- FERPA is enforced by the Family Policy Compliance Office (FPCO) within the U.S. Department of Education. FERPA does NOT provide a private right of action. Students CANNOT sue institutions directly under FERPA. (Gonzaga v. Doe, 2002 — Supreme Court) Students CAN: - File complaint with FPCO - Sue under state privacy laws - Sue under state FERPA-equivalent statutes - File with OCR if disability discrimination involved --- Complaint Process --- 1. Student/parent files complaint with FPCO 2. FPCO reviews complaint (may take months) 3. If violation found → FPCO notifies institution 4. Institution has opportunity to come into compliance 5. If institution refuses → hearing process 6. Ultimate penalty: loss of federal funding --- The Nuclear Penalty --- Loss of federal funding is the only FERPA penalty. This has NEVER been imposed. However, the threat is effective — institutions take compliance seriously. Federal funding at stake: Pell Grants, federal student loans, work-study Research grants (NIH, NSF, DOE) Title I, IDEA funding (K-12) Total exposure: millions to billions of dollars --- Practical Consequences --- Even without FERPA lawsuits, institutions face: State privacy law liability HIPAA violations (if health records mishandled) Contract liability (vendor agreements) Reputational damage (data breaches make news) OCR investigations (disability-related records) Accreditation risk (data governance requirements) --- Data Breach Response --- FERPA doesn't have explicit breach notification requirements BUT: state breach notification laws apply (all 50 states have them) Best practice: 1. Contain the breach immediately 2. Assess what records were exposed 3. Notify affected students per state law (typically 30-60 days) 4. Notify FPCO if systemic FERPA violation 5. Document incident and remediation 6. Review and update security controls EOF } cmd_checklist() { cat << 'EOF' === FERPA Compliance Checklist === --- Annual Requirements --- [ ] Annual FERPA rights notification sent to eligible students [ ] Directory information policy defined and published [ ] Opt-out period for directory information provided [ ] Opt-out requests collected and processed [ ] School official definition published (who has access) [ ] Legitimate educational interest criteria published --- Records Management --- [ ] Education records properly identified and classified [ ] Access limited to school officials with legitimate interest [ ] Record of each disclosure maintained (except directory info) [ ] Disclosure log includes: date, party, legitimate interest [ ] Records retention schedule defined and followed [ ] Secure destruction process for expired records --- Consent & Disclosure --- [ ] Written consent obtained before non-exempt disclosures [ ] Consent includes: records, purpose, recipient, signature, date [ ] Students can revoke consent [ ] Exception used properly documented in each case [ ] Health/safety emergency disclosures documented with rationale --- Technology & Vendors --- [ ] Written agreements with all vendors handling student data [ ] Vendor agreements include FERPA-required clauses [ ] Vendor access limited to minimum necessary data [ ] Vendor data security requirements specified [ ] Data destruction clause in vendor contracts [ ] Periodic vendor compliance review --- Training & Awareness --- [ ] Staff trained on FERPA basics (annual refresher) [ ] Faculty trained on sole possession records rules [ ] IT staff trained on data security for student records [ ] New employee orientation includes FERPA training [ ] Incident response procedures established and tested --- Data Security --- [ ] Student records encrypted in transit and at rest [ ] Role-based access controls implemented [ ] Strong authentication for systems with student data [ ] Audit logs for access to sensitive student records [ ] Regular access reviews (remove departed staff promptly) [ ] Physical security for paper records (locked cabinets) [ ] Data breach response plan documented and tested EOF } show_help() { cat << EOF ferpa v$VERSION — FERPA Compliance Reference Usage: script.sh <command> Commands: intro FERPA overview — scope, history, definitions rights Student and parent rights under FERPA records What is (and isn't) an education record directory Directory information disclosure rules exceptions When disclosure is permitted without consent technology FERPA and cloud services, edtech, AI penalties Enforcement, penalties, complaint process checklist FERPA compliance checklist for institutions help Show this help version Show version Powered by BytesAgain | bytesagain.com EOF } CMD="-help" case "$CMD" in intro) cmd_intro ;; rights) cmd_rights ;; records) cmd_records ;; directory) cmd_directory ;; exceptions) cmd_exceptions ;; technology) cmd_technology ;; penalties) cmd_penalties ;; checklist) cmd_checklist ;; help|--help|-h) show_help ;; version|--version|-v) echo "ferpa v$VERSION — Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: script.sh help"; exit 1 ;; esac
Copy operations reference — file duplication, rsync patterns, CoW, buffer strategies, and cross-platform sync. Use when duplicating files, syncing directorie...
--- name: "copy" version: "1.0.0" description: "Copy operations reference — file duplication, rsync patterns, CoW, buffer strategies, and cross-platform sync. Use when duplicating files, syncing directories, or implementing copy-on-write." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [copy, file, rsync, sync, duplicate, backup, devtools] category: "devtools" --- # Copy — File & Data Copy Operations Reference Quick-reference skill for file copy strategies, rsync patterns, copy-on-write, and cross-platform synchronization. ## When to Use - Duplicating files or directory trees with specific filters - Setting up rsync-based backups or mirrors - Understanding copy-on-write (CoW) behavior - Implementing efficient copy strategies for large datasets - Troubleshooting copy failures and permission issues ## Commands ### `intro` ```bash scripts/script.sh intro ``` Overview of copy operations — types, semantics, and platform differences. ### `rsync` ```bash scripts/script.sh rsync ``` Rsync patterns — common flags, partial transfers, and include/exclude rules. ### `cow` ```bash scripts/script.sh cow ``` Copy-on-Write (CoW) — reflinks, filesystem support, and when to use. ### `patterns` ```bash scripts/script.sh patterns ``` Common copy patterns — mirroring, incremental, differential, snapshot. ### `filters` ```bash scripts/script.sh filters ``` File filtering techniques — by extension, date, size, and gitignore integration. ### `performance` ```bash scripts/script.sh performance ``` Performance optimization — buffer sizes, parallel copy, and I/O tuning. ### `errors` ```bash scripts/script.sh errors ``` Common copy errors, permissions issues, and troubleshooting guide. ### `checklist` ```bash scripts/script.sh checklist ``` Pre-copy and post-copy verification checklist. ### `help` ```bash scripts/script.sh help ``` ### `version` ```bash scripts/script.sh version ``` ## Configuration | Variable | Description | |----------|-------------| | `COPY_DIR` | Data directory (default: ~/.copy/) | --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # copy — File & Data Copy Operations Reference # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="1.0.0" cmd_intro() { cat << 'EOF' === Copy Operations Overview === Copying is the fundamental operation of duplicating data from source to destination. Different strategies have vastly different performance and correctness characteristics. Copy Semantics: Shallow Copy Copy metadata/references only (symlinks stay as links) Deep Copy Recursively copy all data (follow and duplicate symlinks) Reflink/CoW Share data blocks until modified (instant, space-efficient) Hard Link Multiple names for same inode (no data duplication) Core Unix Commands: cp Basic file/directory copy cp -a Archive mode (preserves permissions, timestamps, symlinks) cp -r Recursive directory copy cp --reflink Copy-on-write (if filesystem supports it) rsync Incremental sync with delta transfer dd Block-level copy (raw disk/partition) tar | tar Stream-based copy (preserves everything) scp / sftp Secure remote copy over SSH pv Pipe viewer (copy with progress) Key Considerations: 1. Metadata preservation (permissions, timestamps, xattrs, ACLs) 2. Symlink handling (follow vs preserve) 3. Sparse file handling (maintain holes or fill them) 4. Cross-filesystem behavior (device boundaries) 5. Atomic operations (partial copy risk) 6. Character encoding in filenames 7. Large file support (>2GB, >4GB boundaries) Platform Differences: Linux cp -a, rsync, reflink on btrfs/xfs macOS cp -pR, ditto (preserves resource forks), rsync (no coreutils) Windows robocopy, xcopy, Copy-Item (PowerShell) FreeBSD cp -a, rsync EOF } cmd_rsync() { cat << 'EOF' === Rsync Patterns === Rsync is the gold standard for efficient file synchronization. It uses delta-transfer algorithm to send only differences. Basic Patterns: # Local sync rsync -av src/ dest/ # Remote sync (SSH) rsync -avz src/ user@host:dest/ # Mirror (delete extraneous files in dest) rsync -av --delete src/ dest/ # Dry run (preview changes) rsync -avn --delete src/ dest/ Essential Flags: -a Archive (recursive, preserves permissions/timestamps/symlinks) -v Verbose -z Compress during transfer -P Progress + partial (resume interrupted transfers) -n Dry run --delete Remove files in dest not in src --delete-after Delete after transfer (safer) --exclude='*.tmp' Skip matching files --include='*.log' Force include matching files --backup Keep backup of replaced files --backup-dir=DIR Put backups in specific directory --bwlimit=1000 Limit bandwidth (KB/s) --checksum Compare by checksum, not mod-time/size Trailing Slash Matters: rsync -av src/ dest/ Copies CONTENTS of src into dest rsync -av src dest/ Copies src DIRECTORY into dest (dest/src/...) Exclude Patterns: --exclude='*.pyc' --exclude='.git/' --exclude='node_modules/' --exclude-from='.rsyncignore' # Include only certain files --include='*.py' --exclude='*' Incremental Backup with Hard Links: rsync -av --link-dest=../prev-backup src/ backup-2024-01-15/ # Unchanged files are hard-linked to previous backup # Only changed files take new disk space Remote Rsync Tricks: # Use specific SSH key rsync -av -e "ssh -i ~/.ssh/mykey" src/ user@host:dest/ # Use non-standard port rsync -av -e "ssh -p 2222" src/ user@host:dest/ # Limit to specific interface rsync -av --address=192.168.1.10 src/ user@host:dest/ EOF } cmd_cow() { cat << 'EOF' === Copy-on-Write (CoW) === Copy-on-Write creates an instant copy that shares data blocks with the original. New blocks are allocated only when modified. How It Works: 1. Copy operation creates new metadata pointing to same blocks 2. Both files share physical storage (zero copy time) 3. When either file is modified, only changed blocks are duplicated 4. Unmodified blocks remain shared indefinitely Filesystem Support: Btrfs Full CoW support (default behavior) XFS Reflink support (mkfs.xfs -m reflink=1) APFS Native CoW on macOS (10.13+) ZFS Block-level CoW (always on) OCFS2 Reflink support ext4 Not supported NTFS Not supported (ReFS has it on Windows Server) Using Reflinks: # GNU cp with reflink cp --reflink=auto src dest # Use CoW if possible, fall back to copy cp --reflink=always src dest # Fail if CoW not available # Btrfs-specific btrfs filesystem du -s dir/ # Shows shared vs exclusive space # macOS APFS cp -c src dest # APFS clone (CoW) Benefits: - Instant copy (O(1) time regardless of file size) - Space efficient (shared blocks) - Great for snapshots, VM images, container layers - No performance penalty for reads Gotchas: - CoW fragmentation over time (Btrfs defrag needed) - Cross-filesystem copies can't use CoW - Some backup tools don't preserve CoW relationships - Quota accounting may show shared space differently - Not all tools support --reflink (check coreutils version ≥8.24) When to Use CoW: ✓ VM disk images (quick clones for testing) ✓ Container layers (overlayfs + CoW filesystem) ✓ Build systems (copy source tree for clean builds) ✓ Database snapshots (instant point-in-time copies) ✗ Files that will be completely rewritten (no benefit) ✗ Cross-device copies (not possible) EOF } cmd_patterns() { cat << 'EOF' === Copy Patterns === 1. Full Mirror rsync -av --delete src/ dest/ - Exact replica of source - Deletions propagate to destination - Use for active mirrors and CDN origin sync 2. Incremental Backup (with hard links) rsync -av --link-dest=../yesterday src/ backup-today/ - Each backup appears as full copy - Unchanged files are hard-linked (zero extra space) - Delete old backups without affecting newer ones - Used by: Time Machine, rsnapshot, borgbackup 3. Differential Copy rsync -av --compare-dest=../baseline src/ diff-output/ - Only copies files that differ from baseline - Good for creating patch/update packages 4. Append-Only Sync rsync -av --append-verify src/logs/ dest/logs/ - Only transfers new data appended to files - Perfect for growing log files - --append-verify checksums after append 5. Streaming Copy (tar pipe) tar cf - -C src . | tar xf - -C dest - Preserves all metadata including hard links - Good for moving entire directory trees - Can pipe through ssh: tar cf - . | ssh host 'tar xf - -C /dest' - Can pipe through pv for progress: tar cf - . | pv | tar xf - -C /dest 6. Atomic Copy Pattern cp src dest.tmp && mv dest.tmp dest - Never leaves dest in partial state - mv is atomic on same filesystem - Essential for config files and databases 7. Sparse-Aware Copy cp --sparse=always src dest rsync --sparse src dest - Preserves holes in sparse files - Critical for VM images and databases - Without this, a 100GB sparse file with 1GB data becomes 100GB 8. Parallel Copy find src -type f | parallel -j8 cp {} dest/{/} - Copy multiple files simultaneously - Good for many small files on SSD - For HDD: sequential is usually faster (seek overhead) EOF } cmd_filters() { cat << 'EOF' === File Filtering Techniques === By Extension: # Copy only Python files rsync -av --include='*/' --include='*.py' --exclude='*' src/ dest/ # Copy everything except compiled files rsync -av --exclude='*.pyc' --exclude='*.o' --exclude='*.class' src/ dest/ # Using find + cp find src -name '*.jpg' -exec cp --parents {} dest/ \; By Date: # Files modified in last 7 days find src -mtime -7 -exec cp --parents {} dest/ \; # Files newer than a reference file find src -newer reference.txt -exec cp --parents {} dest/ \; # rsync: skip files newer in destination rsync -av --update src/ dest/ By Size: # Files larger than 10MB find src -size +10M -exec cp --parents {} dest/ \; # Files smaller than 1KB find src -size -1k -exec cp --parents {} dest/ \; # rsync: skip files above size rsync -av --max-size=50m src/ dest/ By Pattern File: # .rsyncignore (same syntax as .gitignore) rsync -av --exclude-from='.rsyncignore' src/ dest/ # Content of .rsyncignore: # *.log # .git/ # node_modules/ # __pycache__/ # *.tmp Git-Aware Filtering: # Copy only tracked files git ls-files | rsync -av --files-from=- . dest/ # Copy only modified files git diff --name-only | rsync -av --files-from=- . dest/ # Respect .gitignore with rsync rsync -av --filter=':- .gitignore' src/ dest/ Combined Filters (order matters in rsync): rsync -av \ --include='*.py' \ --include='*.txt' \ --include='*/' \ --exclude='*' \ --exclude='__pycache__/' \ src/ dest/ # Rules are evaluated top-to-bottom, first match wins EOF } cmd_performance() { cat << 'EOF' === Copy Performance Optimization === Buffer & Block Size: # dd with optimal block size (test for your hardware) dd if=src of=dest bs=1M # 1MB blocks (good default) dd if=src of=dest bs=64K # 64KB for random I/O dd if=src of=dest bs=4M # 4MB for sequential large files # Large file copy with progress pv -s $(stat -c%s src) src > dest # rsync with custom block size rsync -av --block-size=131072 src/ dest/ Parallel Copy Tools: GNU parallel: find src -type f | parallel -j$(nproc) cp {} dest/ fpsync (part of fpart): fpsync -n 8 -f 1000 src/ dest/ # -n 8: use 8 parallel rsync workers # -f 1000: pack 1000 files per rsync job rclone (for cloud/remote): rclone copy src remote:dest --transfers=16 --checkers=8 I/O Scheduling: # Set I/O priority (Linux) ionice -c2 -n0 cp src dest # Best-effort, highest priority ionice -c3 cp src dest # Idle-only (won't impact other I/O) # Use direct I/O to bypass page cache (large files) dd if=src of=dest bs=1M iflag=direct oflag=direct Compression During Transfer: rsync -avz src/ remote:dest/ # Built-in compression rsync -av -e "ssh -C" src/ remote:dest/ # SSH compression # Don't compress already-compressed files: rsync -avz --skip-compress=gz/jpg/mp4/zip src/ remote:dest/ Network Optimization: # Increase SSH buffer rsync -av -e "ssh -o 'Compression=no' -T -c aes128-ctr" src/ remote:dest/ # Use bbcp for high-bandwidth links bbcp -P 2 -w 4m src remote:dest # Use lftp for parallel SFTP lftp -e "mirror --parallel=10 src dest" sftp://host Benchmarks (typical SSD, same machine): cp -a ~400 MB/s for large files rsync -a ~350 MB/s (overhead from checksumming) cp --reflink ~instant (CoW, no data copied) dd bs=1M ~500 MB/s (minimal overhead) tar | tar ~380 MB/s (good metadata preservation) EOF } cmd_errors() { cat << 'EOF' === Copy Errors & Troubleshooting === Permission Denied: Error: cp: cannot open 'file': Permission denied Fix: sudo cp, or fix source permissions Check: ls -la file, stat file SELinux: ls -Z file, restorecon -v file Cross-Device Link: Error: mv: cannot move across filesystems Fix: Use cp + rm instead of mv Or: rsync -av --remove-source-files src dest No Space Left on Device: Error: cp: write error: No space left on device Check: df -h dest_partition Fix: Free space, or use rsync --max-size to copy in stages Filename Too Long: Error: cp: cannot create 'path': File name too long Limits: ext4=255 bytes per component, 4096 bytes full path Fix: Shorten names, or use tar to preserve long paths Argument List Too Long: Error: /bin/cp: Argument list too long Cause: Glob expands to too many files (ARG_MAX limit) Fix: find . -name '*.log' -exec cp {} dest/ \; Or: find . -name '*.log' | xargs -I{} cp {} dest/ Or: rsync -av --include='*.log' --exclude='*' . dest/ Broken Symlinks: Error: cp: cannot stat 'link': No such file or directory Fix: cp -a (preserves symlinks without following) Or: cp --no-dereference Check: find . -xtype l (find broken symlinks) Sparse Files Expanding: Problem: 1GB sparse file becomes 100GB after copy Fix: cp --sparse=always src dest rsync --sparse src dest tar --sparse -cf - src | tar xf - -C dest Rsync Partial Transfers: Problem: Large transfer interrupted Fix: rsync -avP src dest (--partial + --progress) Re-run same command to resume --partial keeps partially transferred files Timestamp Precision: Problem: Timestamps differ after copy (FAT32 = 2s resolution) Fix: rsync --modify-window=2 src/ dest/ Or accept that FAT32/exFAT can't preserve exact times EOF } cmd_checklist() { cat << 'EOF' === Copy Verification Checklist === Pre-Copy: [ ] Verify source exists and is readable [ ] Check destination has sufficient space (df -h) [ ] Determine metadata requirements (permissions, timestamps, xattrs) [ ] Choose appropriate tool (cp, rsync, tar, reflink) [ ] Decide symlink handling (follow vs preserve) [ ] Check for sparse files that need special handling [ ] Run dry run first (rsync -avn, cp with echo) [ ] Consider bandwidth/I/O impact on production systems During Copy: [ ] Monitor progress (rsync -P, pv, or watch df) [ ] Check for errors in output (pipe stderr to log) [ ] Verify no source modifications during copy (if consistency needed) [ ] Monitor disk space on destination Post-Copy Verification: [ ] File count matches find src -type f | wc -l find dest -type f | wc -l [ ] Total size matches du -sb src/ du -sb dest/ [ ] Checksums match (for critical data) find src -type f -exec md5sum {} + | sort > src.md5 cd dest && md5sum -c ../src.md5 [ ] Permissions preserved rsync -avn src/ dest/ (should show no changes) [ ] Symlinks preserved correctly find dest -type l | head [ ] Timestamps preserved stat src/file dest/file (compare mtime) [ ] No broken symlinks introduced find dest -xtype l [ ] Sparse files maintained (if applicable) du -sh file vs ls -lh file (allocated vs apparent size) Integrity Tools: sha256sum Cryptographic verification md5sum Fast verification (not security-grade) rsync -c Checksum-based comparison diff -rq Quick directory comparison hashdeep Recursive hashing with verification EOF } show_help() { cat << EOF copy v$VERSION — File & Data Copy Operations Reference Usage: script.sh <command> Commands: intro Copy operations overview — types, tools, platforms rsync Rsync patterns — flags, excludes, incremental backup cow Copy-on-Write — reflinks, filesystem support patterns Copy patterns — mirror, incremental, atomic, parallel filters File filtering — by extension, date, size, gitignore performance Performance tuning — buffer sizes, parallel copy, I/O errors Common copy errors and troubleshooting guide checklist Pre-copy and post-copy verification checklist help Show this help version Show version Powered by BytesAgain | bytesagain.com EOF } CMD="-help" case "$CMD" in intro) cmd_intro ;; rsync) cmd_rsync ;; cow) cmd_cow ;; patterns) cmd_patterns ;; filters) cmd_filters ;; performance) cmd_performance ;; errors) cmd_errors ;; checklist) cmd_checklist ;; help|--help|-h) show_help ;; version|--version|-v) echo "copy v$VERSION — Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: script.sh help"; exit 1 ;; esac
Autonomous mobile robot fleet manager. Use when json amr tasks, csv amr tasks, checking amr status.
--- name: "amr" version: "1.0.0" description: "Autonomous mobile robot fleet manager. Use when json amr tasks, csv amr tasks, checking amr status." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [amr, industrial, cli, tool] category: "industrial" --- # amr Autonomous mobile robot fleet manager. Use when json amr tasks, csv amr tasks, checking amr status. ## Commands ### `status` ```bash scripts/script.sh status ``` Show current status ### `add` ```bash scripts/script.sh add ``` Add new entry ### `list` ```bash scripts/script.sh list ``` List all entries ### `search` ```bash scripts/script.sh search ``` Search entries ### `remove` ```bash scripts/script.sh remove ``` Remove entry by number ### `export` ```bash scripts/script.sh export ``` Export data to file ### `stats` ```bash scripts/script.sh stats ``` Show statistics ### `config` ```bash scripts/script.sh config ``` View or set config ### `help` ```bash scripts/script.sh help ``` ### `version` ```bash scripts/script.sh version ``` ## Configuration Use `scripts/script.sh config <key> <value>` to set preferences. | Variable | Description | |----------|-------------| | `AMR_DIR` | Data directory (default: ~/.amr/) | --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # amr -- Autonomous mobile robot fleet manager # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="1.0.0" DATA_DIR="-$HOME/.amr" _ensure_dirs() { mkdir -p "$DATA_DIR"; } _save_entry() { _ensure_dirs local cmd="$1" val="$2" local ts=$(date '+%Y-%m-%d %H:%M:%S') printf '{"ts":"%s","cmd":"%s","val":"%s"}\n' "$ts" "$cmd" "$val" >> "$DATA_DIR/data.jsonl" } show_help() { cat << EOF amr v$VERSION -- Autonomous mobile robot fleet manager Usage: amr <command> [args] Commands: status Show current status add Add new entry list List all entries search Search entries remove Remove entry by number export Export data to file stats Show statistics config View or set config help Show this help version Show version Data: $DATA_DIR Powered by BytesAgain | bytesagain.com EOF } cmd_status() { echo "=== amr Status ===" echo " Version: $VERSION" echo " Data dir: $DATA_DIR" local entries=$(cat "$DATA_DIR"/*.jsonl 2>/dev/null | wc -l || echo 0) echo " Entries: $entries" echo " Disk: $(du -sh "$DATA_DIR" 2>/dev/null | cut -f1 || echo empty)" } cmd_add() { local value="?Usage: amr add <entry>" shift || true _save_entry "add" "$value $*" local count=$(wc -l < "$DATA_DIR/data.jsonl" 2>/dev/null || echo 0) echo "Added: $value (entry #$count)" } cmd_list() { echo "=== Amr Entries ===" if [ -f "$DATA_DIR/data.jsonl" ]; then local count=$(wc -l < "$DATA_DIR/data.jsonl") echo "Total: $count" echo "---" tail -20 "$DATA_DIR/data.jsonl" | while IFS= read -r line; do local ts=$(echo "$line" | grep -o '"ts":"[^"]*' | cut -d'"' -f4) local cmd=$(echo "$line" | grep -o '"cmd":"[^"]*' | cut -d'"' -f4) local val=$(echo "$line" | grep -o '"val":"[^"]*' | cut -d'"' -f4) echo " [$ts] $cmd: $val" done else echo "No entries yet." fi } cmd_search() { local term="?Usage: amr search <term>" if [ -f "$DATA_DIR/data.jsonl" ]; then local matches=$(grep -ic "$term" "$DATA_DIR/data.jsonl" 2>/dev/null || echo 0) echo "Found: $matches matches" grep -i "$term" "$DATA_DIR/data.jsonl" 2>/dev/null | head -20 | while IFS= read -r line; do local val=$(echo "$line" | grep -o '"val":"[^"]*' | cut -d'"' -f4) local ts=$(echo "$line" | grep -o '"ts":"[^"]*' | cut -d'"' -f4) echo " [$ts] $val" done else echo "No data to search." fi } cmd_remove() { local num="?Usage: amr remove <line-number>" if [ -f "$DATA_DIR/data.jsonl" ]; then local total=$(wc -l < "$DATA_DIR/data.jsonl") if [ "$num" -ge 1 ] 2>/dev/null && [ "$num" -le "$total" ] 2>/dev/null; then sed -i "numd" "$DATA_DIR/data.jsonl" echo "Removed #$num ($((total-1)) remaining)" else echo "Invalid: $num (total: $total)"; fi else echo "No data."; fi } cmd_export() { local fmt="-json" local out="amr-export.$fmt" if [ ! -f "$DATA_DIR/data.jsonl" ]; then echo "No data."; return 0; fi case "$fmt" in json) cp "$DATA_DIR/data.jsonl" "$out" ;; csv) echo "timestamp,command,value" > "$out" while IFS= read -r line; do ts=$(echo "$line" | grep -o '"ts":"[^"]*' | cut -d'"' -f4) c2=$(echo "$line" | grep -o '"cmd":"[^"]*' | cut -d'"' -f4) vl=$(echo "$line" | grep -o '"val":"[^"]*' | cut -d'"' -f4) echo "$ts,$c2,$vl" >> "$out" done < "$DATA_DIR/data.jsonl" ;; *) echo "Formats: json, csv"; return 1 ;; esac echo "Exported: $out ($(wc -c < "$out") bytes)" } cmd_stats() { echo "=== Amr Stats ===" if [ -f "$DATA_DIR/data.jsonl" ]; then local total=$(wc -l < "$DATA_DIR/data.jsonl") local bytes=$(wc -c < "$DATA_DIR/data.jsonl") echo " Entries: $total" echo " Size: $bytes bytes" echo " Disk: $(du -sh "$DATA_DIR" 2>/dev/null | cut -f1)" else echo " No data yet."; fi } cmd_config() { local key="-" val="-" local cfg="$DATA_DIR/config.txt" if [ -z "$key" ]; then echo "=== Config ===" if [ -f "$cfg" ]; then while IFS="=" read -r k v; do echo " $k=$v"; done < "$cfg" else echo " (empty — use config <key> <value>)"; fi elif [ -z "$val" ]; then grep "^key=" "$cfg" 2>/dev/null | cut -d= -f2- || echo "(not set)" else if [ -f "$cfg" ] && grep -q "^key=" "$cfg" 2>/dev/null; then sed -i "s|^key=.*|key=val|" "$cfg" else echo "key=val" >> "$cfg" fi echo "Set: $key=$val" fi } CMD="-help" shift 2>/dev/null || true _ensure_dirs case "$CMD" in status) cmd_status "$@" ;; add) cmd_add "$@" ;; list) cmd_list "$@" ;; search) cmd_search "$@" ;; remove) cmd_remove "$@" ;; export) cmd_export "$@" ;; stats) cmd_stats "$@" ;; config) cmd_config "$@" ;; help|--help|-h) show_help ;; version|--version|-v) echo "amr v$VERSION -- Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: amr help"; exit 1 ;; esac
Inverter and VFD parameter calculator. Use when json inverter tasks, csv inverter tasks, checking inverter status.
--- name: "inverter" version: "1.0.0" description: "Inverter and VFD parameter calculator. Use when json inverter tasks, csv inverter tasks, checking inverter status." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [inverter, electrical, cli, tool] category: "electrical" --- # inverter Inverter and VFD parameter calculator. Use when json inverter tasks, csv inverter tasks, checking inverter status. ## Commands ### `status` ```bash scripts/script.sh status ``` Show current status ### `add` ```bash scripts/script.sh add ``` Add new entry ### `list` ```bash scripts/script.sh list ``` List all entries ### `search` ```bash scripts/script.sh search ``` Search entries ### `remove` ```bash scripts/script.sh remove ``` Remove entry by number ### `export` ```bash scripts/script.sh export ``` Export data to file ### `stats` ```bash scripts/script.sh stats ``` Show statistics ### `config` ```bash scripts/script.sh config ``` View or set config ### `help` ```bash scripts/script.sh help ``` ### `version` ```bash scripts/script.sh version ``` ## Configuration Use `scripts/script.sh config <key> <value>` to set preferences. | Variable | Description | |----------|-------------| | `INVERTER_DIR` | Data directory (default: ~/.inverter/) | --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # inverter -- Inverter and VFD parameter calculator # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="1.0.0" DATA_DIR="-$HOME/.inverter" _ensure_dirs() { mkdir -p "$DATA_DIR"; } _save_entry() { _ensure_dirs local cmd="$1" val="$2" local ts=$(date '+%Y-%m-%d %H:%M:%S') printf '{"ts":"%s","cmd":"%s","val":"%s"}\n' "$ts" "$cmd" "$val" >> "$DATA_DIR/data.jsonl" } show_help() { cat << EOF inverter v$VERSION -- Inverter and VFD parameter calculator Usage: inverter <command> [args] Commands: status Show current status add Add new entry list List all entries search Search entries remove Remove entry by number export Export data to file stats Show statistics config View or set config help Show this help version Show version Data: $DATA_DIR Powered by BytesAgain | bytesagain.com EOF } cmd_status() { echo "=== inverter Status ===" echo " Version: $VERSION" echo " Data dir: $DATA_DIR" local entries=$(cat "$DATA_DIR"/*.jsonl 2>/dev/null | wc -l || echo 0) echo " Entries: $entries" echo " Disk: $(du -sh "$DATA_DIR" 2>/dev/null | cut -f1 || echo empty)" } cmd_add() { local value="?Usage: inverter add <entry>" shift || true _save_entry "add" "$value $*" local count=$(wc -l < "$DATA_DIR/data.jsonl" 2>/dev/null || echo 0) echo "Added: $value (entry #$count)" } cmd_list() { echo "=== Inverter Entries ===" if [ -f "$DATA_DIR/data.jsonl" ]; then local count=$(wc -l < "$DATA_DIR/data.jsonl") echo "Total: $count" echo "---" tail -20 "$DATA_DIR/data.jsonl" | while IFS= read -r line; do local ts=$(echo "$line" | grep -o '"ts":"[^"]*' | cut -d'"' -f4) local cmd=$(echo "$line" | grep -o '"cmd":"[^"]*' | cut -d'"' -f4) local val=$(echo "$line" | grep -o '"val":"[^"]*' | cut -d'"' -f4) echo " [$ts] $cmd: $val" done else echo "No entries yet." fi } cmd_search() { local term="?Usage: inverter search <term>" if [ -f "$DATA_DIR/data.jsonl" ]; then local matches=$(grep -ic "$term" "$DATA_DIR/data.jsonl" 2>/dev/null || echo 0) echo "Found: $matches matches" grep -i "$term" "$DATA_DIR/data.jsonl" 2>/dev/null | head -20 | while IFS= read -r line; do local val=$(echo "$line" | grep -o '"val":"[^"]*' | cut -d'"' -f4) local ts=$(echo "$line" | grep -o '"ts":"[^"]*' | cut -d'"' -f4) echo " [$ts] $val" done else echo "No data to search." fi } cmd_remove() { local num="?Usage: inverter remove <line-number>" if [ -f "$DATA_DIR/data.jsonl" ]; then local total=$(wc -l < "$DATA_DIR/data.jsonl") if [ "$num" -ge 1 ] 2>/dev/null && [ "$num" -le "$total" ] 2>/dev/null; then sed -i "numd" "$DATA_DIR/data.jsonl" echo "Removed #$num ($((total-1)) remaining)" else echo "Invalid: $num (total: $total)"; fi else echo "No data."; fi } cmd_export() { local fmt="-json" local out="inverter-export.$fmt" if [ ! -f "$DATA_DIR/data.jsonl" ]; then echo "No data."; return 0; fi case "$fmt" in json) cp "$DATA_DIR/data.jsonl" "$out" ;; csv) echo "timestamp,command,value" > "$out" while IFS= read -r line; do ts=$(echo "$line" | grep -o '"ts":"[^"]*' | cut -d'"' -f4) c2=$(echo "$line" | grep -o '"cmd":"[^"]*' | cut -d'"' -f4) vl=$(echo "$line" | grep -o '"val":"[^"]*' | cut -d'"' -f4) echo "$ts,$c2,$vl" >> "$out" done < "$DATA_DIR/data.jsonl" ;; *) echo "Formats: json, csv"; return 1 ;; esac echo "Exported: $out ($(wc -c < "$out") bytes)" } cmd_stats() { echo "=== Inverter Stats ===" if [ -f "$DATA_DIR/data.jsonl" ]; then local total=$(wc -l < "$DATA_DIR/data.jsonl") local bytes=$(wc -c < "$DATA_DIR/data.jsonl") echo " Entries: $total" echo " Size: $bytes bytes" echo " Disk: $(du -sh "$DATA_DIR" 2>/dev/null | cut -f1)" else echo " No data yet."; fi } cmd_config() { local key="-" val="-" local cfg="$DATA_DIR/config.txt" if [ -z "$key" ]; then echo "=== Config ===" if [ -f "$cfg" ]; then while IFS="=" read -r k v; do echo " $k=$v"; done < "$cfg" else echo " (empty — use config <key> <value>)"; fi elif [ -z "$val" ]; then grep "^key=" "$cfg" 2>/dev/null | cut -d= -f2- || echo "(not set)" else if [ -f "$cfg" ] && grep -q "^key=" "$cfg" 2>/dev/null; then sed -i "s|^key=.*|key=val|" "$cfg" else echo "key=val" >> "$cfg" fi echo "Set: $key=$val" fi } CMD="-help" shift 2>/dev/null || true _ensure_dirs case "$CMD" in status) cmd_status "$@" ;; add) cmd_add "$@" ;; list) cmd_list "$@" ;; search) cmd_search "$@" ;; remove) cmd_remove "$@" ;; export) cmd_export "$@" ;; stats) cmd_stats "$@" ;; config) cmd_config "$@" ;; help|--help|-h) show_help ;; version|--version|-v) echo "inverter v$VERSION -- Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: inverter help"; exit 1 ;; esac
Computerized maintenance management system
--- name: "cmms" version: "1.0.0" description: "Computerized maintenance management system" author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [cmms, industrial, cli, tool] category: "industrial" --- # cmms Computerized maintenance management system ## Commands ### `status` ```bash scripts/script.sh status ``` Show current status ### `add` ```bash scripts/script.sh add ``` Add new entry ### `list` ```bash scripts/script.sh list ``` List all entries ### `search` ```bash scripts/script.sh search ``` Search entries ### `remove` ```bash scripts/script.sh remove ``` Remove entry by number ### `export` ```bash scripts/script.sh export ``` Export data to file ### `stats` ```bash scripts/script.sh stats ``` Show statistics ### `config` ```bash scripts/script.sh config ``` View or set config ### `help` ```bash scripts/script.sh help ``` ### `version` ```bash scripts/script.sh version ``` ## Configuration Use `scripts/script.sh config <key> <value>` to set preferences. | Variable | Required | Description | |----------|----------|-------------| | `CMMS_DIR` | No | Data directory (default: ~/.cmms/) | ## Data Storage All data stored in `~/.cmms/` using JSONL format (one JSON object per line). ## Output Structured output to stdout. Exit code 0 on success, 1 on error. --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # cmms -- Computerized maintenance management system # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="1.0.0" DATA_DIR="-$HOME/.cmms" _ensure_dirs() { mkdir -p "$DATA_DIR"; } _save_entry() { _ensure_dirs local cmd="$1" val="$2" local ts=$(date '+%Y-%m-%d %H:%M:%S') printf '{"ts":"%s","cmd":"%s","val":"%s"}\n' "$ts" "$cmd" "$val" >> "$DATA_DIR/data.jsonl" } show_help() { cat << EOF cmms v$VERSION -- Computerized maintenance management system Usage: cmms <command> [args] Commands: status Show current status add Add new entry list List all entries search Search entries remove Remove entry by number export Export data to file stats Show statistics config View or set config help Show this help version Show version Data: $DATA_DIR Powered by BytesAgain | bytesagain.com EOF } cmd_status() { echo "=== cmms Status ===" echo " Version: $VERSION" echo " Data dir: $DATA_DIR" local entries=$(cat "$DATA_DIR"/*.jsonl 2>/dev/null | wc -l || echo 0) echo " Entries: $entries" echo " Disk: $(du -sh "$DATA_DIR" 2>/dev/null | cut -f1 || echo empty)" } cmd_add() { local value="?Usage: cmms add <entry>" shift || true _save_entry "add" "$value $*" local count=$(wc -l < "$DATA_DIR/data.jsonl" 2>/dev/null || echo 0) echo "Added: $value (entry #$count)" } cmd_list() { echo "=== Cmms Entries ===" if [ -f "$DATA_DIR/data.jsonl" ]; then local count=$(wc -l < "$DATA_DIR/data.jsonl") echo "Total: $count" echo "---" tail -20 "$DATA_DIR/data.jsonl" | while IFS= read -r line; do local ts=$(echo "$line" | grep -o '"ts":"[^"]*' | cut -d'"' -f4) local cmd=$(echo "$line" | grep -o '"cmd":"[^"]*' | cut -d'"' -f4) local val=$(echo "$line" | grep -o '"val":"[^"]*' | cut -d'"' -f4) echo " [$ts] $cmd: $val" done else echo "No entries yet." fi } cmd_search() { local term="?Usage: cmms search <term>" if [ -f "$DATA_DIR/data.jsonl" ]; then local matches=$(grep -ic "$term" "$DATA_DIR/data.jsonl" 2>/dev/null || echo 0) echo "Found: $matches matches" grep -i "$term" "$DATA_DIR/data.jsonl" 2>/dev/null | head -20 | while IFS= read -r line; do local val=$(echo "$line" | grep -o '"val":"[^"]*' | cut -d'"' -f4) local ts=$(echo "$line" | grep -o '"ts":"[^"]*' | cut -d'"' -f4) echo " [$ts] $val" done else echo "No data to search." fi } cmd_remove() { local num="?Usage: cmms remove <line-number>" if [ -f "$DATA_DIR/data.jsonl" ]; then local total=$(wc -l < "$DATA_DIR/data.jsonl") if [ "$num" -ge 1 ] 2>/dev/null && [ "$num" -le "$total" ] 2>/dev/null; then sed -i "numd" "$DATA_DIR/data.jsonl" echo "Removed #$num ($((total-1)) remaining)" else echo "Invalid: $num (total: $total)"; fi else echo "No data."; fi } cmd_export() { local fmt="-json" local out="cmms-export.$fmt" if [ ! -f "$DATA_DIR/data.jsonl" ]; then echo "No data."; return 0; fi case "$fmt" in json) cp "$DATA_DIR/data.jsonl" "$out" ;; csv) echo "timestamp,command,value" > "$out" while IFS= read -r line; do ts=$(echo "$line" | grep -o '"ts":"[^"]*' | cut -d'"' -f4) c2=$(echo "$line" | grep -o '"cmd":"[^"]*' | cut -d'"' -f4) vl=$(echo "$line" | grep -o '"val":"[^"]*' | cut -d'"' -f4) echo "$ts,$c2,$vl" >> "$out" done < "$DATA_DIR/data.jsonl" ;; *) echo "Formats: json, csv"; return 1 ;; esac echo "Exported: $out ($(wc -c < "$out") bytes)" } cmd_stats() { echo "=== Cmms Stats ===" if [ -f "$DATA_DIR/data.jsonl" ]; then local total=$(wc -l < "$DATA_DIR/data.jsonl") local bytes=$(wc -c < "$DATA_DIR/data.jsonl") echo " Entries: $total" echo " Size: $bytes bytes" echo " Disk: $(du -sh "$DATA_DIR" 2>/dev/null | cut -f1)" else echo " No data yet."; fi } cmd_config() { local key="-" val="-" local cfg="$DATA_DIR/config.txt" if [ -z "$key" ]; then echo "=== Config ===" if [ -f "$cfg" ]; then while IFS="=" read -r k v; do echo " $k=$v"; done < "$cfg" else echo " (empty — use config <key> <value>)"; fi elif [ -z "$val" ]; then grep "^key=" "$cfg" 2>/dev/null | cut -d= -f2- || echo "(not set)" else if [ -f "$cfg" ] && grep -q "^key=" "$cfg" 2>/dev/null; then sed -i "s|^key=.*|key=val|" "$cfg" else echo "key=val" >> "$cfg" fi echo "Set: $key=$val" fi } CMD="-help" shift 2>/dev/null || true _ensure_dirs case "$CMD" in status) cmd_status "$@" ;; add) cmd_add "$@" ;; list) cmd_list "$@" ;; search) cmd_search "$@" ;; remove) cmd_remove "$@" ;; export) cmd_export "$@" ;; stats) cmd_stats "$@" ;; config) cmd_config "$@" ;; help|--help|-h) show_help ;; version|--version|-v) echo "cmms v$VERSION -- Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: cmms help"; exit 1 ;; esac
cad reference tool
--- name: "cad" version: "2.0.2" description: "cad reference tool" author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [cad, reference] category: "devtools" --- # Cad cad reference tool. No API keys or credentials required — outputs reference documentation only. ## Commands | Command | Description | |---------|-------------| | `intro` | intro reference | | `quickstart` | quickstart reference | | `patterns` | patterns reference | | `debugging` | debugging reference | | `performance` | performance reference | | `security` | security reference | | `migration` | migration reference | | `cheatsheet` | cheatsheet reference | ## Output Format All commands output plain-text reference documentation via heredoc. No external API calls, no credentials needed, no network access. --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # cad — Cad reference tool. Use when working with cad in devtools contexts. # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="2.0.2" show_help() { cat << 'HELPEOF' cad v$VERSION — Cad Reference Tool Usage: cad <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' # Cad — Overview ## What is Cad? Cad (cad) is a specialized tool/concept in the devtools domain. It provides essential capabilities for professionals working with cad. ## Key Concepts - Core cad principles and fundamentals - How cad fits into the broader devtools ecosystem - Essential terminology every practitioner should know ## Why Cad Matters Understanding cad 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 cad concepts 2. Learn the standard tools and interfaces 3. Practice with common scenarios 4. Review safety and compliance requirements EOF } cmd_quickstart() { cat << 'EOF' # Cad — Quick Start Guide ## Prerequisites - Basic understanding of devtools concepts - Required tools and access credentials - System meeting minimum requirements ## Installation 1. Download or clone the cad 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' # Cad — Common Patterns & Best Practices ## Design Patterns 1. **Standard Pattern**: The most common approach for cad 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' # Cad — 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' # Cad — 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' # Cad — 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' # Cad — 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' # Cad — 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 "cad v$VERSION — Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: cad help"; exit 1 ;; esac
Visual analysis and diagnostic tools to help machine learning model selection. ml-visualizer, python, anaconda, estimator, machine-learning, matplotlib.
--- version: "1.0.0" name: Yellowbrick description: "Visual analysis and diagnostic tools to help machine learning model selection. ml-visualizer, python, anaconda, estimator, machine-learning, matplotlib." --- # ML Visualizer A data toolkit for ingesting, transforming, querying, and visualizing machine learning datasets. Manage your entire data pipeline — from raw ingestion through profiling and validation — all from the command line. ## Commands | Command | Description | |---------|-------------| | `ml-visualizer ingest <input>` | Ingest raw data or record a data source entry | | `ml-visualizer transform <input>` | Log a data transformation step or operation | | `ml-visualizer query <input>` | Record a query against your dataset | | `ml-visualizer filter <input>` | Log a filter operation applied to data | | `ml-visualizer aggregate <input>` | Record an aggregation or rollup operation | | `ml-visualizer visualize <input>` | Log a visualization request or chart specification | | `ml-visualizer export <input>` | Record an export operation or export all data | | `ml-visualizer sample <input>` | Log a data sampling operation | | `ml-visualizer schema <input>` | Record or describe a data schema | | `ml-visualizer validate <input>` | Log a data validation check | | `ml-visualizer pipeline <input>` | Record a full pipeline definition or step | | `ml-visualizer profile <input>` | Log a data profiling run | | `ml-visualizer stats` | Show summary statistics across all entry types | | `ml-visualizer export <fmt>` | Export all data (formats: `json`, `csv`, `txt`) | | `ml-visualizer search <term>` | Search across all entries by keyword | | `ml-visualizer recent` | Show the 20 most recent activity log entries | | `ml-visualizer status` | Health check — version, disk usage, last activity | | `ml-visualizer help` | Show the built-in help message | | `ml-visualizer version` | Print the current version (v2.0.0) | Each data command (ingest, transform, query, etc.) works in two modes: - **Without arguments** — displays the 20 most recent entries of that type - **With arguments** — saves the input as a new timestamped entry ## Data Storage All data is stored as plain-text log files in `~/.local/share/ml-visualizer/`: - Each command type gets its own log file (e.g., `ingest.log`, `transform.log`, `visualize.log`) - Entries are stored in `timestamp|value` format for easy parsing - A unified `history.log` tracks all activity across command types - Export to JSON, CSV, or TXT at any time with the `export` command Set the `ML_VISUALIZER_DIR` environment variable to override the default data directory. ## Requirements - Bash 4.0+ (uses `set -euo pipefail`) - Standard Unix utilities: `date`, `wc`, `du`, `tail`, `grep`, `sed`, `cat` - No external dependencies or API keys required ## When to Use 1. **Building a data pipeline journal** — use `ingest`, `transform`, and `pipeline` to document each step of your ML data preparation workflow 2. **Tracking data quality** — use `validate` and `profile` to log validation checks and profiling runs, ensuring data integrity before model training 3. **Logging visualization requests** — use `visualize` to record what charts and plots you've generated for model diagnostics (confusion matrices, ROC curves, feature importance) 4. **Managing dataset schemas** — use `schema` to document the structure of your datasets, track schema changes over time, and share definitions with your team 5. **Auditing data operations** — use `search`, `recent`, and `stats` to review your complete data processing history and find specific operations ## Examples ```bash # Ingest a new data source ml-visualizer ingest "Loaded training set from s3://ml-data/train.csv — 50,000 rows, 24 features" # Record a transformation step ml-visualizer transform "Applied StandardScaler to numeric columns, one-hot encoded categoricals" # Log a visualization ml-visualizer visualize "Generated confusion matrix for RandomForest classifier — 94% accuracy" # Define a schema entry ml-visualizer schema "users table: id(int), age(int), income(float), segment(str), churn(bool)" # Search past operations ml-visualizer search "StandardScaler" ``` ## Output All commands print results to stdout. Redirect to a file if needed: ```bash ml-visualizer stats > pipeline-report.txt ml-visualizer export json ``` --- Powered by BytesAgain | bytesagain.com | [email protected] FILE:scripts/script.sh #!/usr/bin/env bash # Ml Visualizer — data tool # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail DATA_DIR="HOME/.local/share/ml-visualizer" mkdir -p "$DATA_DIR" _log() { echo "$(date '+%m-%d %H:%M') $1: $2" >> "$DATA_DIR/history.log"; } _version() { echo "ml-visualizer v2.0.0"; } _help() { echo "Ml Visualizer v2.0.0 — data toolkit" echo "" echo "Usage: ml-visualizer <command> [args]" echo "" echo "Commands:" echo " ingest Ingest" echo " transform Transform" echo " query Query" echo " filter Filter" echo " aggregate Aggregate" echo " visualize Visualize" echo " export Export" echo " sample Sample" echo " schema Schema" echo " validate Validate" echo " pipeline Pipeline" echo " profile Profile" echo " stats Summary statistics" echo " export <fmt> Export (json|csv|txt)" echo " search <term> Search entries" echo " recent Recent activity" echo " status Health check" echo " help Show this help" echo " version Show version" echo "" echo "Data: $DATA_DIR" } _stats() { echo "=== Ml Visualizer Stats ===" local total=0 for f in "$DATA_DIR"/*.log; do [ -f "$f" ] || continue local name=$(basename "$f" .log) local c=$(wc -l < "$f") total=$((total + c)) echo " $name: $c entries" done echo " ---" echo " Total: $total entries" echo " Data size: $(du -sh "$DATA_DIR" 2>/dev/null | cut -f1)" } _export() { local fmt="-json" local out="$DATA_DIR/export.$fmt" case "$fmt" in json) echo "[" > "$out" local first=1 for f in "$DATA_DIR"/*.log; do [ -f "$f" ] || continue local name=$(basename "$f" .log) while IFS='|' read -r ts val; do [ $first -eq 1 ] && first=0 || echo "," >> "$out" printf ' {"type":"%s","time":"%s","value":"%s"}' "$name" "$ts" "$val" >> "$out" done < "$f" done echo "\n]" >> "$out" ;; csv) echo "type,time,value" > "$out" for f in "$DATA_DIR"/*.log; do [ -f "$f" ] || continue local name=$(basename "$f" .log) while IFS='|' read -r ts val; do echo "$name,$ts,$val" >> "$out"; done < "$f" done ;; txt) echo "=== Ml Visualizer Export ===" > "$out" for f in "$DATA_DIR"/*.log; do [ -f "$f" ] || continue echo "--- $(basename "$f" .log) ---" >> "$out" cat "$f" >> "$out" done ;; *) echo "Formats: json, csv, txt"; return 1 ;; esac echo "Exported to $out ($(wc -c < "$out") bytes)" } _status() { echo "=== Ml Visualizer Status ===" echo " Version: v2.0.0" echo " Data dir: $DATA_DIR" echo " Entries: $(cat "$DATA_DIR"/*.log 2>/dev/null | wc -l) total" echo " Disk: $(du -sh "$DATA_DIR" 2>/dev/null | cut -f1)" echo " Last: $(tail -1 "$DATA_DIR/history.log" 2>/dev/null || echo never)" echo " Status: OK" } _search() { local term="?Usage: ml-visualizer search <term>" echo "Searching for: $term" for f in "$DATA_DIR"/*.log; do [ -f "$f" ] || continue local m=$(grep -i "$term" "$f" 2>/dev/null || true) if [ -n "$m" ]; then echo " --- $(basename "$f" .log) ---" echo "$m" | sed 's/^/ /' fi done } _recent() { echo "=== Recent Activity ===" tail -20 "$DATA_DIR/history.log" 2>/dev/null | sed 's/^/ /' || echo " No activity yet." } case "-help" in ingest) shift if [ $# -eq 0 ]; then echo "Recent ingest entries:" tail -20 "$DATA_DIR/ingest.log" 2>/dev/null || echo " No entries yet. Use: ml-visualizer ingest <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/ingest.log" local total=$(wc -l < "$DATA_DIR/ingest.log") echo " [Ml Visualizer] ingest: $input" echo " Saved. Total ingest entries: $total" _log "ingest" "$input" fi ;; transform) shift if [ $# -eq 0 ]; then echo "Recent transform entries:" tail -20 "$DATA_DIR/transform.log" 2>/dev/null || echo " No entries yet. Use: ml-visualizer transform <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/transform.log" local total=$(wc -l < "$DATA_DIR/transform.log") echo " [Ml Visualizer] transform: $input" echo " Saved. Total transform entries: $total" _log "transform" "$input" fi ;; query) shift if [ $# -eq 0 ]; then echo "Recent query entries:" tail -20 "$DATA_DIR/query.log" 2>/dev/null || echo " No entries yet. Use: ml-visualizer query <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/query.log" local total=$(wc -l < "$DATA_DIR/query.log") echo " [Ml Visualizer] query: $input" echo " Saved. Total query entries: $total" _log "query" "$input" fi ;; filter) shift if [ $# -eq 0 ]; then echo "Recent filter entries:" tail -20 "$DATA_DIR/filter.log" 2>/dev/null || echo " No entries yet. Use: ml-visualizer filter <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/filter.log" local total=$(wc -l < "$DATA_DIR/filter.log") echo " [Ml Visualizer] filter: $input" echo " Saved. Total filter entries: $total" _log "filter" "$input" fi ;; aggregate) shift if [ $# -eq 0 ]; then echo "Recent aggregate entries:" tail -20 "$DATA_DIR/aggregate.log" 2>/dev/null || echo " No entries yet. Use: ml-visualizer aggregate <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/aggregate.log" local total=$(wc -l < "$DATA_DIR/aggregate.log") echo " [Ml Visualizer] aggregate: $input" echo " Saved. Total aggregate entries: $total" _log "aggregate" "$input" fi ;; visualize) shift if [ $# -eq 0 ]; then echo "Recent visualize entries:" tail -20 "$DATA_DIR/visualize.log" 2>/dev/null || echo " No entries yet. Use: ml-visualizer visualize <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/visualize.log" local total=$(wc -l < "$DATA_DIR/visualize.log") echo " [Ml Visualizer] visualize: $input" echo " Saved. Total visualize entries: $total" _log "visualize" "$input" fi ;; export) shift if [ $# -eq 0 ]; then echo "Recent export entries:" tail -20 "$DATA_DIR/export.log" 2>/dev/null || echo " No entries yet. Use: ml-visualizer export <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/export.log" local total=$(wc -l < "$DATA_DIR/export.log") echo " [Ml Visualizer] export: $input" echo " Saved. Total export entries: $total" _log "export" "$input" fi ;; sample) shift if [ $# -eq 0 ]; then echo "Recent sample entries:" tail -20 "$DATA_DIR/sample.log" 2>/dev/null || echo " No entries yet. Use: ml-visualizer sample <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/sample.log" local total=$(wc -l < "$DATA_DIR/sample.log") echo " [Ml Visualizer] sample: $input" echo " Saved. Total sample entries: $total" _log "sample" "$input" fi ;; schema) shift if [ $# -eq 0 ]; then echo "Recent schema entries:" tail -20 "$DATA_DIR/schema.log" 2>/dev/null || echo " No entries yet. Use: ml-visualizer schema <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/schema.log" local total=$(wc -l < "$DATA_DIR/schema.log") echo " [Ml Visualizer] schema: $input" echo " Saved. Total schema entries: $total" _log "schema" "$input" fi ;; validate) shift if [ $# -eq 0 ]; then echo "Recent validate entries:" tail -20 "$DATA_DIR/validate.log" 2>/dev/null || echo " No entries yet. Use: ml-visualizer validate <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/validate.log" local total=$(wc -l < "$DATA_DIR/validate.log") echo " [Ml Visualizer] validate: $input" echo " Saved. Total validate entries: $total" _log "validate" "$input" fi ;; pipeline) shift if [ $# -eq 0 ]; then echo "Recent pipeline entries:" tail -20 "$DATA_DIR/pipeline.log" 2>/dev/null || echo " No entries yet. Use: ml-visualizer pipeline <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/pipeline.log" local total=$(wc -l < "$DATA_DIR/pipeline.log") echo " [Ml Visualizer] pipeline: $input" echo " Saved. Total pipeline entries: $total" _log "pipeline" "$input" fi ;; profile) shift if [ $# -eq 0 ]; then echo "Recent profile entries:" tail -20 "$DATA_DIR/profile.log" 2>/dev/null || echo " No entries yet. Use: ml-visualizer profile <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/profile.log" local total=$(wc -l < "$DATA_DIR/profile.log") echo " [Ml Visualizer] profile: $input" echo " Saved. Total profile entries: $total" _log "profile" "$input" fi ;; stats) _stats ;; export) shift; _export "$@" ;; search) shift; _search "$@" ;; recent) _recent ;; status) _status ;; help|--help|-h) _help ;; version|--version|-v) _version ;; *) echo "Unknown: $1 — run 'ml-visualizer help'" exit 1 ;; esac
Reference tool for devtools — covers intro, quickstart, patterns and more. Quick lookup for SSL Cert Manager concepts, best practices, and implementation pat...
--- name: "ssl-cert-manager" version: "2.0.1" description: "Reference tool for devtools — covers intro, quickstart, patterns and more. Quick lookup for SSL Cert Manager concepts, best practices, and implementation pat..." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [ssl,cert,manager, reference] category: "devtools" --- # Ssl Cert Manager Reference tool for devtools — covers intro, quickstart, patterns and more. Quick lookup for SSL Cert Manager concepts, best practices, and implementation pat... No API keys or credentials required. ## Commands | Command | Description | |---------|-------------| | `intro` | intro reference | | `quickstart` | quickstart reference | | `patterns` | patterns reference | | `debugging` | debugging reference | | `performance` | performance reference | | `security` | security reference | | `migration` | migration reference | | `cheatsheet` | cheatsheet reference | ## Output Format All commands output plain-text reference documentation via heredoc. No external API calls, no credentials needed, no network access. --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # ssl-cert-manager — Ssl Cert Manager reference tool. Use when working with ssl cert manager in devtools contexts. # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="2.0.0" show_help() { cat << 'HELPEOF' ssl-cert-manager v$VERSION — Ssl Cert Manager Reference Tool Usage: ssl-cert-manager <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' # Ssl Cert Manager — Overview ## What is Ssl Cert Manager? Ssl Cert Manager (ssl-cert-manager) is a specialized tool/concept in the devtools domain. It provides essential capabilities for professionals working with ssl cert manager. ## Key Concepts - Core ssl cert manager principles and fundamentals - How ssl cert manager fits into the broader devtools ecosystem - Essential terminology every practitioner should know ## Why Ssl Cert Manager Matters Understanding ssl cert manager 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 ssl cert manager concepts 2. Learn the standard tools and interfaces 3. Practice with common scenarios 4. Review safety and compliance requirements EOF } cmd_quickstart() { cat << 'EOF' # Ssl Cert Manager — Quick Start Guide ## Prerequisites - Basic understanding of devtools concepts - Required tools and access credentials - System meeting minimum requirements ## Installation 1. Download or clone the ssl cert manager 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' # Ssl Cert Manager — Common Patterns & Best Practices ## Design Patterns 1. **Standard Pattern**: The most common approach for ssl cert manager 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' # Ssl Cert Manager — 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' # Ssl Cert Manager — 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' # Ssl Cert Manager — 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' # Ssl Cert Manager — 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' # Ssl Cert Manager — 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 "ssl-cert-manager v$VERSION — Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: ssl-cert-manager help"; exit 1 ;; esac
Reference tool for devtools — covers intro, quickstart, patterns and more. Quick lookup for Page Builder concepts, best practices, and implementation patterns.
--- name: "page-builder" version: "2.0.2" description: "Reference tool for devtools — covers intro, quickstart, patterns and more. Quick lookup for Page Builder concepts, best practices, and implementation patterns." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [page,builder, reference] category: "devtools" --- # Page Builder Reference tool for devtools — covers intro, quickstart, patterns and more. Quick lookup for Page Builder concepts, best practices, and implementation patterns. No API keys or credentials required. ## Commands | Command | Description | |---------|-------------| | `intro` | intro reference | | `quickstart` | quickstart reference | | `patterns` | patterns reference | | `debugging` | debugging reference | | `performance` | performance reference | | `security` | security reference | | `migration` | migration reference | | `cheatsheet` | cheatsheet reference | ## Output Format All commands output plain-text reference documentation via heredoc. No external API calls, no credentials needed, no network access. --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # page-builder — Page Builder reference tool. Use when working with page builder in data contexts. # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="2.0.1" show_help() { cat << 'HELPEOF' page-builder v$VERSION — Page Builder Reference Tool Usage: page-builder <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' # Page Builder — Overview ## What is Page Builder? Page Builder (page-builder) is a specialized tool/concept in the data domain. It provides essential capabilities for professionals working with page builder. ## Key Concepts - Core page builder principles and fundamentals - How page builder fits into the broader data ecosystem - Essential terminology every practitioner should know ## Why Page Builder Matters Understanding page builder is critical for: - Improving efficiency in data workflows - Reducing errors and downtime - Meeting industry standards and compliance requirements - Enabling better decision-making with accurate data ## Getting Started 1. Understand the basic page builder concepts 2. Learn the standard tools and interfaces 3. Practice with common scenarios 4. Review safety and compliance requirements EOF } cmd_quickstart() { cat << 'EOF' # Page Builder — Quick Start Guide ## Prerequisites - Basic understanding of data concepts - Required tools and access credentials - System meeting minimum requirements ## Installation 1. Download or clone the page builder 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' # Page Builder — Common Patterns & Best Practices ## Design Patterns 1. **Standard Pattern**: The most common approach for page builder 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' # Page Builder — 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' # Page Builder — 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' # Page Builder — 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' # Page Builder — 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' # Page Builder — 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 "page-builder v$VERSION — Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: page-builder help"; exit 1 ;; esac
Reference tool for devtools — covers intro, quickstart, patterns and more. Quick lookup for Image Labeler concepts, best practices, and implementation patterns.
--- name: "image-labeler" version: "2.0.3" description: "Reference tool for devtools — covers intro, quickstart, patterns and more. Quick lookup for Image Labeler concepts, best practices, and implementation patterns." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [image,labeler, reference] category: "devtools" --- # Image Labeler Reference tool for devtools — covers intro, quickstart, patterns and more. Quick lookup for Image Labeler concepts, best practices, and implementation patterns. No API keys or credentials required. ## Commands | Command | Description | |---------|-------------| | `intro` | intro reference | | `quickstart` | quickstart reference | | `patterns` | patterns reference | | `debugging` | debugging reference | | `performance` | performance reference | | `security` | security reference | | `migration` | migration reference | | `cheatsheet` | cheatsheet reference | ## Output Format All commands output plain-text reference documentation via heredoc. No external API calls, no credentials needed, no network access. --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # image-labeler — Image Labeler reference tool. Use when working with image labeler in data contexts. # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="2.0.2" show_help() { cat << 'HELPEOF' image-labeler v$VERSION — Image Labeler Reference Tool Usage: image-labeler <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' # Image Labeler — Overview ## What is Image Labeler? Image Labeler (image-labeler) is a specialized tool/concept in the data domain. It provides essential capabilities for professionals working with image labeler. ## Key Concepts - Core image labeler principles and fundamentals - How image labeler fits into the broader data ecosystem - Essential terminology every practitioner should know ## Why Image Labeler Matters Understanding image labeler is critical for: - Improving efficiency in data workflows - Reducing errors and downtime - Meeting industry standards and compliance requirements - Enabling better decision-making with accurate data ## Getting Started 1. Understand the basic image labeler concepts 2. Learn the standard tools and interfaces 3. Practice with common scenarios 4. Review safety and compliance requirements EOF } cmd_quickstart() { cat << 'EOF' # Image Labeler — Quick Start Guide ## Prerequisites - Basic understanding of data concepts - Required tools and access credentials - System meeting minimum requirements ## Installation 1. Download or clone the image labeler 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' # Image Labeler — Common Patterns & Best Practices ## Design Patterns 1. **Standard Pattern**: The most common approach for image labeler 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' # Image Labeler — 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' # Image Labeler — 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' # Image Labeler — 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' # Image Labeler — 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' # Image Labeler — 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 "image-labeler v$VERSION — Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: image-labeler help"; exit 1 ;; esac