[{"content":"","date":null,"permalink":"https://hzqtc.github.io/categories/","section":"Categories","summary":"","title":"Categories"},{"content":"","date":null,"permalink":"https://hzqtc.github.io/tags/dashboard/","section":"Tags","summary":"","title":"Dashboard"},{"content":"","date":null,"permalink":"https://hzqtc.github.io/tags/go/","section":"Tags","summary":"","title":"Go"},{"content":"","date":null,"permalink":"https://hzqtc.github.io/tags/ipad/","section":"Tags","summary":"","title":"Ipad"},{"content":"","date":null,"permalink":"https://hzqtc.github.io/","section":"Johnny Huang","summary":"","title":"Johnny Huang"},{"content":"","date":null,"permalink":"https://hzqtc.github.io/posts/index.html","section":"Posts","summary":"","title":"Posts"},{"content":"","date":null,"permalink":"https://hzqtc.github.io/categories/projects/","section":"Categories","summary":"","title":"Projects"},{"content":"","date":null,"permalink":"https://hzqtc.github.io/tags/pwa/","section":"Tags","summary":"","title":"Pwa"},{"content":"","date":null,"permalink":"https://hzqtc.github.io/tags/self-hosted/","section":"Tags","summary":"","title":"Self-Hosted"},{"content":"","date":null,"permalink":"https://hzqtc.github.io/tags/","section":"Tags","summary":"","title":"Tags"},{"content":"If you have an old iPad sitting in a drawer, you probably know the frustration: the screen still looks great, the battery still holds a charge when plugged in, and yet the App Store won\u0026rsquo;t let you install almost anything modern because it\u0026rsquo;s stuck on an old iOS version.\nI had an iPad mini 2 stuck on iOS 12.5.7 in exactly that state. It felt wasteful to throw away a perfectly good Retina display, so I built Glance — an open-source, full-screen wall dashboard app designed specifically to run 24/7 on old iPads (and newer iPads or desktops, too). No App Store needed, no jailbreak, no API keys, no subscription — just open Safari, tap Add to Home Screen, and mount it on a stand or wall.\nWhy old iPads need a different kind of web app # You might wonder: why not just open any existing dashboard website on an old iPad?\nI tried. Most modern web apps break on iOS 12 for a few unglamorous reasons:\nOld Safari JavaScript engine: Safari 12 doesn\u0026rsquo;t understand a lot of newer JavaScript syntax and trips over modern \u0026lt;script type=\u0026quot;module\u0026quot;\u0026gt; loading quirks. Old CSS engine: Features everyone takes for granted today (like gap in flexbox) don\u0026rsquo;t work on Safari 12. Tight hardware: The iPad mini 2 has an A7 chip from 2013 and only 1 GB of RAM. Heavy frameworks, constant re-renders, or nonstop animations will either heat up the tablet or cause Safari to reload the tab. Glance is built from the ground up with those limits in mind. The frontend uses lightweight Preact compiled into a classic ES5 bundle (~127 KB gzipped) with zero module-script traps, Safari 12-safe CSS, a one-tap Static mode so the A7 stays cool all day, offline caching, and a silent 3:30 AM refresh so it can run unattended for months.\nWhat\u0026rsquo;s on the dashboard # Glance automatically rotates through six full-screen slides (you can also swipe up/down or tap the rail on the right to jump to any screen, which pauses rotation for a minute).\n1. Weather \u0026amp; World Clocks # A room-readable clock paired with current conditions, a scrollable 24-hour forecast, a 5-day outlook, air quality (US AQI), UV index, and sunrise/sunset. Along the bottom are live clocks and weather for your favorite cities around the world — tap any city card and the whole screen (including the sky) shifts to that city.\nThe background sky changes color through dawn, day, sunset, and night, and shows the actual lunar phase at night.\nWeather data is mostly fetched from Open Meteo which is free without need for an API key for personal use only.\n2. Stocks Watchlist # A clean 20-card watchlist (indices, stocks, crypto, gold, oil — whatever symbols you put in the config) with a tappable hero chart spanning 1D all the way to ALL. You can drag across the chart to inspect past prices, switch cards between $, %, and market cap, and it automatically polls faster when the market is open and slows down after hours.\nFinancial data is fetched from Yahoo Finance for personal use only.\n3. Family Calendar # A side-by-side month grid and daily agenda that pulls from your private .ics calendar links (Apple iCloud, Google Calendar, Outlook — anything with a secret .ics or webcal:// URL). It also includes US federal holidays, Chinese lunar dates (1900–2100), a \u0026ldquo;NOW\u0026rdquo; indicator on active events, and a countdown pill for your next upcoming trip.\n4. Live World Map \u0026amp; Exchange Rates # A real-time day/night world map centered on your home city, showing flight arcs to your other cities, live FX rates derived automatically from those cities, plus toggleable live layers:\nSun \u0026amp; Moon — tap either to see subsolar/sublunar coordinates, declination, sunrise/sunset, moon phase, lunar day, and tide regime. Aurora ovals — live NOAA Kp-index bands that widen and deepen in color during geomagnetic storms. ISS — real-time orbit track and visibility footprint. Earthquakes \u0026amp; Tropical Cyclones — recent M4.5+ quakes (USGS) and active hurricanes/typhoons (NHC + GDACS), all tappable for details. Data is all computed or fetched from public domains.\n5. Headlines (RSS + QR Code) # Point Glance at up to four RSS or Atom feeds and it renders them in clean columns. Since nobody wants to read long articles on a wall-mounted tablet, tapping any headline pops up a summary and a QR code you can scan with your phone. If you add a free Gemini API key, it can also generate a 2–3 sentence AI TL;DR right inside the popover.\n6. Photo Frame # Link one or more shared Google Photos albums and Glance turns your iPad into a smart digital photo frame. It automatically groups landscape and portrait shots into full-bleed collages (so vertical photos don\u0026rsquo;t get awkward black bars), overlays the date and location, and interleaves photos between your other dashboards.\nThis feature requires sharing your Google Photo albums via public URLs, so technically if you leak those URLs anyone can see your photos. Make sure to never post those URLs, add them to your .gitignore or set as secret on Vercel. Do this at your own risk.\nThe photo frame can also show seasonal holiday themes such as Christmas, Halloween, Easter; as well as traditional Chinese holidays such as Chinese New Year, Moon Festival.\nNight Ambient Mode # At night (11 PM – 7 AM by default), Glance dims down into a quiet bedside clock: a minimal analog dial with a ticking second hand, the date, current weather, and a countdown to sunrise. Background animations and polling pause behind it, and the layout gently shifts a few pixels every minute to avoid static image retention. Tap anywhere to wake the full dashboards back up.\nHow to set it up (no experience required) # Weather, Stocks, and the World map work out of the box with zero API keys. Calendar, Photos, Headlines, and AI summaries are all optional.\nYou have two ways to host Glance:\nOption A: Host for free on Vercel (easiest — no terminal needed) # If you want your iPad to work from anywhere without keeping a computer running at home, Vercel\u0026rsquo;s free tier is the simplest path.\nFork the Glance repository on GitHub. Sign in to vercel.com/new with GitHub and import your fork. Before clicking Deploy, open Environment Variables and add two security settings so your dashboard is locked behind a 4-digit PIN: GLANCE_PASSCODE — any 4-digit PIN you want (for example 1234) GLANCE_SESSION_SECRET — any random 32+ character string (you can generate one with openssl rand -hex 32 or a password generator) Click Deploy. In about a minute, Vercel gives you your own https://your-app.vercel.app link. Whenever you want to add your own cities or stock tickers later, just edit config/dashboard.config.json right on GitHub — Vercel redeploys automatically and your iPad picks up the update on its own.\nOption B: Host locally on a Mac, Linux box, or Raspberry Pi # Prefer to keep everything on your home Wi-Fi? You only need Node.js 18+ and Go 1.23+.\ngit clone https://github.com/hzqtc/glance.git cd glance npm install Then start the Go API and the Safari 12-compatible build in two terminals:\n# Terminal 1 — Go backend API (port 8080) npm run dev:api # Terminal 2 — Production build served on your local network (port 4173) npm run build \u0026amp;\u0026amp; npm run preview Open http://\u0026lt;your-computer-ip\u0026gt;:4173 on your iPad. When hosting locally without GLANCE_PASSCODE set, it skips the PIN screen so you can try it immediately.\nAdding your personal Calendar, Photos, or News # All personal links live in environment variables — never committed to Git:\nVercel: Project Settings → Environment Variables Local: a .env.local file in the glance folder Variable What it enables CALENDAR_ICS_URLS One or more private .ics / webcal:// calendar links PHOTOS_ALBUM_URLS One or more Google Photos shared-album links NEWS_FEEDS Up to 4 RSS/Atom feeds as JSON, e.g. [{\u0026quot;name\u0026quot;:\u0026quot;Hacker News\u0026quot;,\u0026quot;url\u0026quot;:\u0026quot;https://news.ycombinator.com/rss\u0026quot;}] GEMINI_API_KEY Optional free key from Google AI Studio for article TL;DRs Putting it on your old iPad # Open your Glance URL in Safari on the iPad (enter your 4-digit PIN once; it stays unlocked for a year). Tap the Share button → Add to Home Screen, then launch Glance from the Home Screen so the Safari address bar disappears. On an older iPad (like an iPad mini 2), tap the top-center Motion icon once to switch the weather sky to Static mode — it remembers your choice and keeps the device cool. Go to Settings → Display \u0026amp; Brightness → Auto-Lock → Never, plug in a charging cable, and set it on a stand. Give your old hardware a second life # An iPad that can\u0026rsquo;t run modern apps anymore still has a sharp, bright, low-power screen that is better than most dedicated smart displays you can buy. If you have one sitting in a closet, give Glance a try.\nThe full source code is open source on GitHub. Feel free to fork it, tweak config/dashboard.config.json to make it yours, or open an issue if you run into any quirks on another vintage tablet!\n","date":"26 November 2026","permalink":"https://hzqtc.github.io/2026/11/turn-an-old-ipad-into-a-wall-dashboard-with-glance.html","section":"Posts","summary":"\u003cp\u003eIf you have an old iPad sitting in a drawer, you probably know the frustration: the screen still looks great, the battery still holds a charge when\nplugged in, and yet the App Store won\u0026rsquo;t let you install almost anything modern because it\u0026rsquo;s stuck on an old iOS version.\u003c/p\u003e\n\u003cp\u003eI had an \u003cstrong\u003eiPad mini 2\u003c/strong\u003e stuck on iOS 12.5.7 in exactly that state. It felt wasteful to throw away a perfectly good Retina display, so I built\n\u003ca href=\"https://github.com/hzqtc/glance\" target=\"_blank\" rel=\"noreferrer\"\u003e\u003cstrong\u003eGlance\u003c/strong\u003e\u003c/a\u003e — an open-source, full-screen wall dashboard app designed specifically to run 24/7 on old iPads (and\nnewer iPads or desktops, too). No App Store needed, no jailbreak, no API keys, no subscription — just open Safari, tap \u003cem\u003eAdd to Home Screen\u003c/em\u003e, and mount\nit on a stand or wall.\u003c/p\u003e","title":"Turning an Old iPad into a Wall/Desktop Dashboard or Google Photo Frame"},{"content":"","date":null,"permalink":"https://hzqtc.github.io/tags/vercel/","section":"Tags","summary":"","title":"Vercel"},{"content":"","date":null,"permalink":"https://hzqtc.github.io/tags/android/","section":"Tags","summary":"","title":"Android"},{"content":"Hello, Android devs! This is my first blog about Android. We know Android SDK provides you a bunch of useful layouts: FrameLayout, LinearLayout, RelativeLayout, etc. So where is FlowLayout, which works like a multiline TextView but holding views instead of texts? Developers can just add views to a FlowLayout and each view is put to the right of the previous one and wraps to a new row when the current row is full. I\u0026rsquo;m gonna show you how you could implement your own FlowLayout with less than 100 lines of code.\nPrerequisites # To understand this tutorial, you should have some Android development experience. You should already know what views and viewgroups are. You also should have used one of the SDK builtin layouts before.\nHow it works # A layout should subclass ViewGroup and implement onMeasure() and onLayout(). onMeasure(int, int) is called when the parent of this view wants to know this view\u0026rsquo;s dimension, onLayout(boolean, int, int, int, int) is called when the parent layouts this view. Since a layout has its own children, it should also layout them in onLayout().\nSo we basically do two things, calculate the size of the layout in onMeasure() and layout the children in onLayout().\nThe code # In onMeasure(), we go through all children, measure each child and put the child to the right of previous child if there\u0026rsquo;s enough room for it. Otherwise, wrap the line and put the child to next line. At last, we know how much room the layout itself want to be to hold all its children.\n@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int childLeft = getPaddingLeft(); int childTop = getPaddingTop(); int lineHeight = 0; // 100 is a dummy number, widthMeasureSpec should always be EXACTLY for FlowLayout int myWidth = resolveSize(100, widthMeasureSpec); int wantedHeight = 0; for (int i = 0; i \u0026lt; getChildCount(); i++) { final View child = getChildAt(i); if (child.getVisibility() == View.GONE) { continue; } // let the child measure itself child.measure( getChildMeasureSpec(widthMeasureSpec, getPaddingLeft() + getPaddingRight(), child.getLayoutParams().width), getChildMeasureSpec(heightMeasureSpec, getPaddingTop() + getPaddingBottom(), child.getLayoutParams().height)); int childWidth = child.getMeasuredWidth(); int childHeight = child.getMeasuredHeight(); // lineheight is the height of current line, should be the height of the heightest view lineHeight = Math.max(childHeight, lineHeight); if (childWidth + childLeft + getPaddingRight() \u0026gt; myWidth) { // wrap this line childLeft = getPaddingLeft(); childTop += paddingVertical + lineHeight; lineHeight = childHeight; } childLeft += childWidth + paddingHorizontal; } wantedHeight += childTop + lineHeight + getPaddingBottom(); setMeasuredDimension(myWidth, resolveSize(wantedHeight, heightMeasureSpec)); } onLayout() basicly does the same thing except it layouts the children instead of calculating the dimension.\n@Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { int childLeft = getPaddingLeft(); int childTop = getPaddingTop(); int lineHeight = 0; int myWidth = right - left; for (int i = 0; i \u0026lt; getChildCount(); i++) { final View child = getChildAt(i); if (child.getVisibility() == View.GONE) { continue; } int childWidth = child.getMeasuredWidth(); int childHeight = child.getMeasuredHeight(); lineHeight = Math.max(childHeight, lineHeight); if (childWidth + childLeft + getPaddingRight() \u0026gt; myWidth) { childLeft = getPaddingLeft(); childTop += paddingVertical + lineHeight; lineHeight = childHeight; } child.layout(childLeft, childTop, childLeft + childWidth, childTop + childHeight); childLeft += childWidth + paddingHorizontal; } } To make use of our fresh new FlowLayout, put it in an activity and add some views into it.\npublic class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ViewGroup flowContainer = (ViewGroup) findViewById(R.id.flow_container); for (Locale locale : Locale.getAvailableLocales()) { String countryName = locale.getDisplayCountry(); if (!countryName.isEmpty()) { flowContainer.addView(createDummyTextView(countryName), new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); } } } private View createDummyTextView(String text) { TextView textView = new TextView(this); textView.setText(text); return textView; } } We add the country name of all locale available on this device into a FlowLayout and see how it works:\nThe full code lives on gist.\n","date":"13 December 2013","permalink":"https://hzqtc.github.io/2013/12/android-custom-layout-flowlayout.html","section":"Posts","summary":"\u003cp\u003eHello, Android devs! This is my first blog about Android. We know Android SDK provides you a bunch\nof useful layouts: \u003ccode\u003eFrameLayout\u003c/code\u003e, \u003ccode\u003eLinearLayout\u003c/code\u003e, \u003ccode\u003eRelativeLayout\u003c/code\u003e, etc. So where is \u003ccode\u003eFlowLayout\u003c/code\u003e,\nwhich works like a multiline \u003ccode\u003eTextView\u003c/code\u003e but holding views instead of texts? Developers can just add\nviews to a \u003ccode\u003eFlowLayout\u003c/code\u003e and each view is put to the right of the previous one and wraps to a new row\nwhen the current row is full. I\u0026rsquo;m gonna show you how you could implement your own \u003ccode\u003eFlowLayout\u003c/code\u003e with\nless than 100 lines of code.\u003c/p\u003e","title":"Android Custom Layout: FlowLayout"},{"content":"","date":null,"permalink":"https://hzqtc.github.io/tags/java/","section":"Tags","summary":"","title":"Java"},{"content":"","date":null,"permalink":"https://hzqtc.github.io/categories/programming/","section":"Categories","summary":"","title":"Programming"},{"content":"","date":null,"permalink":"https://hzqtc.github.io/tags/ui/","section":"Tags","summary":"","title":"Ui"},{"content":"","date":null,"permalink":"https://hzqtc.github.io/tags/image/","section":"Tags","summary":"","title":"Image"},{"content":"In my last post, I downloaded thounsands of images from Jiandan OOXX. (What a cool site!) When I was enjoying this amazing collection, I found there are many duplicate images. I don\u0026rsquo;t want my disk space wasted on duplicate images, so I need to figure out a way to deal with them.\nDetecting duplication images is totally different from detecting duplicate normal files, because two same image may be in different formats, of different dimensions, have different sizes. Hash values can\u0026rsquo;t be relied to detect image duplications, other image features should be taken into consideration.\nFirst of all, I will introduce you a simple but effective method for detecting image duplicates: Perceptual Hash Algorithm. The basic idea is computing a fingerprint for each image and then comparing the fingerprints. If two fingerprints are the same or very close, the two images are probably duplicate to each other.\nI wrote a Python script to compare two image using this method (read the reference above if you want to understand it).\n#!/usr/bin/python import sys from PIL import Image def avhash(im): if not isinstance(im, Image.Image): im = Image.open(im) im = im.resize((8, 8), Image.ANTIALIAS).convert(\u0026#39;L\u0026#39;) avg = reduce(lambda x, y: x + y, im.getdata()) / 64. return reduce(lambda x, (y, z): x | (z \u0026lt;\u0026lt; y), enumerate(map(lambda i: 0 if i \u0026lt; avg else 1, im.getdata())), 0) def hamming(h1, h2): h, d = 0, h1 ^ h2 while d: h += 1 d \u0026amp;= d - 1 return h if __name__ == \u0026#39;__main__\u0026#39;: if len(sys.argv) != 3: print \u0026#34;Usage: %s img1 img2\u0026#34; % sys.argv[0] else: img1 = sys.argv[1] img2 = sys.argv[2] hash1 = avhash(img1) hash2 = avhash(img2) dist = hamming(hash1, hash2) print \u0026#34;hash(%s) = %d\\nhash(%s) = %d\\nhamming distance = %d\\nsimilarity = %d%%\u0026#34; % (img1, hash1, img2, hash2, dist, (64 - dist) * 100 / 64) And I grab some pictures on the internet.\nThey all have different formats, sizes and their pixels are slightly different from each other, except 2.png is an identical copy of 2.jpg. The comparing results:\n$ ./imgcmp.py 1.jpg 2.jpg hash(1.jpg) = 14933407633201104831 hash(2.jpg) = 14919930918911018815 hamming distance = 7 similarity = 89% $ ./imgcmp.py 1.jpg 3.jpg hash(1.jpg) = 14933407633201104831 hash(3.jpg) = 14933407633204774719 hamming distance = 3 similarity = 95% $ ./imgcmp.py 2.jpg 3.jpg hash(2.jpg) = 14919930918911018815 hash(3.jpg) = 14933407633204774719 hamming distance = 8 similarity = 87% $ ./imgcmp.py 2.jpg 2.png hash(2.jpg) = 14919930918911018815 hash(2.png) = 14919930918911018815 hamming distance = 0 similarity = 100% Well, the results explain themselves.\nAssume you have N images, firstly scan them and compute their fingerprints. If you take 100% similarity as duplicate (which suggests duplications have identical fingerprints), we can find all duplications in O (N) time. (This gist shows a possible solution.) If you define duplication as a similarity threshold (such as 90%), finding all duplications requires O (N * N) time (if you can improve this time bound, please let me know).\nCongratulations if you read here! You definitely have a potentiality to become as ballache as me!\n","date":"19 April 2013","permalink":"https://hzqtc.github.io/2013/04/image-duplication-detection.html","section":"Posts","summary":"\u003cp\u003eIn my \u003ca href=\"/2013/04/event-based-html-parsing.html\"\u003elast post\u003c/a\u003e, I downloaded\nthounsands of images from \u003ca href=\"http://jandan.net/ooxx\" target=\"_blank\" rel=\"noreferrer\"\u003eJiandan OOXX\u003c/a\u003e. (What a cool\nsite!) When I was enjoying this amazing collection, I found there are many\nduplicate images. I don\u0026rsquo;t want my disk space wasted on duplicate images, so I\nneed to figure out a way to deal with them.\u003c/p\u003e\n\u003cp\u003eDetecting duplication images is totally different from detecting duplicate\nnormal files, because two same image may be in different formats, of different\ndimensions, have different sizes. Hash values can\u0026rsquo;t be relied to detect image\nduplications, other image features should be taken into consideration.\u003c/p\u003e","title":"Image Duplication Detection"},{"content":"","date":null,"permalink":"https://hzqtc.github.io/tags/python/","section":"Tags","summary":"","title":"Python"},{"content":"HTML parsing is a useful technique for crawlers. Three major techniques to parse HTML are regular expression, tree-model based parsing and event based parsing. Regular expression is universally applicable for all parsings, but it\u0026rsquo;s tricky and hard for other people to understand or even maintain.\nTree-model based parsing is powerful and popular, a lot of HTML/XML parsing libraries construct an in-memory tree-like model to represent the structure of the parsed HTML. The first drawback of this kind of parsing is obvious, constructing tree-models in memory requires memory for the entire HTML even if we only need a small part of it. The second problem of tree-model based parsing is the cost of CPU time. If a big HTML file is parsed and the in-memory model is huge, a lot of CPU time is cost to build the model and travel in the model.\nEvent based parsing is simple but efficient. The parser defines certain events and the users implement event handles to retrieve information during parsing. When the parsing engine encounter a start tag, a close tag and text within tags, corresponding event handles get executed. In the event handle, context information such as tag name, tag attributes and tag texts are all accessible. However, information beyond the current tag such as information of the parent tag and the children tags are not accessible.\nThe advantages of event based parsing are straightforward: only the information of current tag is resident in the memory and there is no need to construct any model.\nPython HTML Parser Performance provides detail performance benchmarks on parsing speed and memory usage of different HTML parsers of Python. The results show clearly that HTMLParser (which is a event-based parsing library for Python) has the smallest memory usage and is also the second fastest parser.\nI write a simple parser for Jiandan OOXX, which is a photo gallery contributed by users, to demonstrate how to parse HTML with event based parsers. If I want to download all photos in one of the pages, I need to parse the HTML source file and get information of the photos such as image url and image votes. By dig the HTML structure, we know that each photo corresponds to a \u0026lt;li\u0026gt; element of id=\u0026quot;comment-*\u0026quot;. The image\u0026rsquo;s URL is the src attribute of one of the \u0026lt;img\u0026gt; elements inside this \u0026lt;li\u0026gt; and the votes are the texts of \u0026lt;span\u0026gt; elements of id=\u0026quot;cos_[un]support-*\u0026quot;.\nWe only need to implement three event handles to retrieve the photos' information: handle_starttag, handle_endtag and handle_data. We also define two state variable: withinPostLi to identify whether the parsing is now inside a \u0026lt;li\u0026gt; that we are interested in; fetchData to identify whether the tag text is a support vote or an unsupport vote.\nclass JDOOXXParser(HTMLParser.HTMLParser): def __init__(self): HTMLParser.HTMLParser.__init__(self) self.withinPostLi = False self.fetchData = None self.currentImage = OOXXImage() self.imageList = [] def handle_starttag(self, tag, attrs): attrMap = dict(attrs) if self.withinPostLi == True: if tag == \u0026#34;img\u0026#34; and \u0026#34;class\u0026#34; not in attrMap and \u0026#34;src\u0026#34; in attrMap: self.currentImage.url = attrMap[\u0026#34;src\u0026#34;] elif tag == \u0026#34;span\u0026#34; and \u0026#34;id\u0026#34; in attrMap and attrMap[\u0026#34;id\u0026#34;].startswith(\u0026#34;cos_support-\u0026#34;): self.fetchData = \u0026#34;oo\u0026#34; elif tag == \u0026#34;span\u0026#34; and \u0026#34;id\u0026#34; in attrMap and attrMap[\u0026#34;id\u0026#34;].startswith(\u0026#34;cos_unsupport-\u0026#34;): self.fetchData = \u0026#34;xx\u0026#34; if tag == \u0026#34;li\u0026#34; and \u0026#34;id\u0026#34; in attrMap and attrMap[\u0026#34;id\u0026#34;].startswith(\u0026#34;comment-\u0026#34;): self.withinPostLi = True def handle_endtag(self, tag): if tag == \u0026#34;li\u0026#34; and self.withinPostLi == True: self.withinPostLi = False self.imageList.append(self.currentImage) self.currentImage = OOXXImage() def handle_data(self, data): if self.fetchData == \u0026#34;oo\u0026#34;: self.currentImage.oo = int(data) self.fetchData = None elif self.fetchData == \u0026#34;xx\u0026#34;: self.currentImage.xx = int(data) self.fetchData = None The parser takes the HTML as input and output the photos\u0026rsquo; informations. Full parser example can be found at this gist. An example run is:\n$ curl -s http://jandan.net/ooxx/page-100 | ./jdooxx.py -o 50 -x 10 oo = 51, xx = 4, http://ww1.sinaimg.cn/mw600/5c9384d0jw1dn1e8ruuf7j.jpg oo = 79, xx = 6, http://ww2.sinaimg.cn/mw600/789830acjw1dn1jt1cni0j.jpg oo = 56, xx = 5, http://27.media.tumblr.com/tumblr_ltz6opLwd01qzs0yso1_500.jpg ","date":"18 April 2013","permalink":"https://hzqtc.github.io/2013/04/event-based-html-parsing.html","section":"Posts","summary":"\u003cp\u003eHTML parsing is a useful technique for crawlers. Three major techniques to parse\nHTML are regular expression, tree-model based parsing and event based parsing.\nRegular expression is universally applicable for all parsings, but it\u0026rsquo;s tricky\nand hard for other people to understand or even maintain.\u003c/p\u003e\n\u003cp\u003eTree-model based parsing is powerful and popular, a lot of HTML/XML parsing\nlibraries construct an in-memory tree-like model to represent the structure of\nthe parsed HTML. The first drawback of this kind of parsing is obvious,\nconstructing tree-models in memory requires memory for the entire HTML even if\nwe only need a small part of it.  The second problem of tree-model based parsing\nis the cost of CPU time. If a big HTML file is parsed and the in-memory model is\nhuge, a lot of CPU time is cost to build the model and travel in the model.\u003c/p\u003e","title":"Event Based HTML Parsing with Python"},{"content":"","date":null,"permalink":"https://hzqtc.github.io/tags/html/","section":"Tags","summary":"","title":"Html"},{"content":"","date":null,"permalink":"https://hzqtc.github.io/tags/parsing/","section":"Tags","summary":"","title":"Parsing"},{"content":"","date":null,"permalink":"https://hzqtc.github.io/tags/linux/","section":"Tags","summary":"","title":"Linux"},{"content":"","date":null,"permalink":"https://hzqtc.github.io/tags/mac/","section":"Tags","summary":"","title":"Mac"},{"content":"I just got a late 2009 Macbook Air and I have been using it for a month. As an advanced Linux user, I found Mac OS X is very easy to use with the powerful unix command line tools. As a GUI user, I think Mac provide a consistent and decent user interface. I recommand all Linux users who is exhausted with the Linux desktops to give it a try. Here I want to give the Linuxers a start guide to Mac OS X.\nCommand Line Tools # I put command line tools first because Mac provides most Unix command line tools so Linux users can easily get adapted. But some tools in Mac is a little different, for example, ls support -@ switch to display extended file attributes. You may also install original GNU coreutils with Homebrew. Homebrew is just like makepkg in Archlinux: ruby scripts contain instructions on building from source code and installing packags. Hundreds of tools and libraries you are familiar with in Linux can be found in Homebrew. It\u0026rsquo;s a must-have tool for advanced users.\nSharing the POSIX standard, it\u0026rsquo;s also very easy to get you programs written for Linux to work on Mac. In most cases, you do not need to change a single line of code, just rebuild and everything works just fine. Of course, I\u0026rsquo;m referring to command line programs since Mac has a very different GUI interface from GTK or QT in Linux.\nApplications # The first thing to mention is that to install an application in Mac is as easy as draging the icon to the Application folder. The application in Mac is just a *.app directory with all files and metafiles bundled inside. To uninstall an applicaton you just simply delete it. I\u0026rsquo;m going to list some application I\u0026rsquo;m using on Mac as well as their alternatives I use in Linux.\nTerminal vs. Xfce-terminal # The Mac built-in Terminal is a full-featured terminal emulator. It also has tabs, detects unfinished jobs on closing and shows current command in title. I think it\u0026rsquo;s better than Xfce-terminal which I use in Linux.\nMacVim vs. GVim # MacVim is Vim with native Mac GUI, it\u0026rsquo;s identical to GVim in Linux. All plugins and configurations work fine.\nFinder vs. Thunar # Finder is the file browser for Mac. Finder absolutely provides a better user interface than Linux file managers such as Thunar. By the way, Finder is also the only Application that you can\u0026rsquo;t Quit.\nFirefox vs. Firefox # Nothing much to say, Firefox (with Vimperator) is my favourite browser and the only browser I use. Although Firefox uses too much memory in Mac, I would not switch to any other browsers until they got the same power as Vimperator.\nTransmission vs. Transmission-daemon # Transmission for Mac has a very elegant UI and it\u0026rsquo;s a simple but powerful BT client. I use Transmission-daemon, which only has command line interface, in Linux.\niChat vs. Pidgin # iChat is also Mac built-in. It supports less protocols than Pidgin but I wouldn\u0026rsquo;t care because I only use Gtalk (Jabber).\nMplayerx vs. Mplayer # Another identical application with native UI, works as well as in Linux.\nPreview vs. Mupdf # Another Mac built-in, full-featured image/pdf viewer. Mupdf can hardly be called as a pdf viewer, I think it\u0026rsquo;s just a pdf displayer.\nMpd vs. Mpd # iTunes sucks and I only use it to sync music to my iPod. I use Mpd on both Mac and Linux, it\u0026rsquo;s extremely resource-saving and very suited to me since my MBA has only 2GB memory. I use Homebrew to install it: brew install mpd mpc. However, I can\u0026rsquo;t find a good Mac client for Mpd. So I\u0026rsquo;m going to build one by myself.\nQuite a lot of applications are the same or just a variant, thanks for these great cross-platform applications.\nDesktop Experience # Mac OS X provide a very easy-to-use GUI. The shortcuts for all applications are consistent, for example, ⌘-W closes current window and ⌘-Q quits current application. The global menubar is also the statusbar. Mac also provide multiple workspaces, switching between them using trackpad is cool. Full-screen applications will automatically takes an individual workspace. And the scrolling in Mac is smoothed with trackpad. Trackpad is amazing.\nThe widgets are beautiful and consistent, too. As far as I can see, the same application looks far more beautiful in Mac than in Linux.\n","date":"29 October 2012","permalink":"https://hzqtc.github.io/2012/10/mac-start-guide-for-linuxers.html","section":"Posts","summary":"\u003cp\u003eI just got a late 2009 Macbook Air and I have been using it for a month. As an advanced Linux user, I found Mac OS X is very easy to use with the powerful unix command line tools. As a GUI user, I think Mac provide a consistent and decent user interface. I recommand all Linux users who is exhausted with the Linux desktops to give it a try. Here I want to give the Linuxers a start guide to Mac OS X.\u003c/p\u003e","title":"Mac Start Guide for Linuxers"},{"content":"","date":null,"permalink":"https://hzqtc.github.io/categories/workspace/","section":"Categories","summary":"","title":"Workspace"},{"content":"","date":null,"permalink":"https://hzqtc.github.io/tags/ipc/","section":"Tags","summary":"","title":"Ipc"},{"content":"Inter-Process Communication (IPC) is a set of methods for exchanging data among multiple processes. IPC is a very common mechanism in Linux and Pipe maybe one of the most widely used IPC methods. When you type cat foo | grep bar, you create a pipe to connect stdout of cat to stdin of grep. A pipe, as its name states, can be understood as a channel with two ends. Pipe is actually implemented using a piece of kernel memory. The system call pipe always create a pipe and two associated file descriptions, fd[0] for reading from the pipe and fd[1] for writing to the pipe.\nPipe is always used with fork, because using pipe within one process is meaningless. In the example, two pipes are created.\nAfter pipe and fork, both parent process and child process can read and write to both pipes. However, a pipe is unidirectional. If the parent process write the pipe1 and then read from pipe1, it will get the same data written before. And that\u0026rsquo;s why two pipes are created, pipe1 for data flow from parent to child and pipe2 for data flow from child to parent. Unneeded pipe descriptions must be closed.\nAfter that, we use dup2 to connect stdin of the child to pipe1 and stdout of the child to pipe2. The pipes are transparent for the child process, it has no idea that it\u0026rsquo;s reading from a pipe and writing to another pipe. Then the parent process can use the two pipes to communicate with the child. In the example program, the child process executes rev, which reverse each line it reads from stdin and print the result to stdout. The parent process passed everything it reads from stdin to the child and redirects everything the child prints to stdout.\n#include \u0026lt;stdio.h\u0026gt; #include \u0026lt;unistd.h\u0026gt; #include \u0026lt;sys/wait.h\u0026gt; int main() { // from parent to child, parent write, child read int pp2c[2]; // from child to parent, child write, parent read int pc2p[2]; pipe(pp2c); pipe(pc2p); switch (fork()) { // fork failed case -1: break; // child case 0: // connect pp2c to stdin close(pp2c[1]); dup2(pp2c[0], STDIN_FILENO); close(pp2c[0]); // connect pc2p to stdout close(pc2p[0]); dup2(pc2p[1], STDOUT_FILENO); close(pc2p[1]); // exec \u0026#34;rev\u0026#34; to reverse lines execlp(\u0026#34;rev\u0026#34;, \u0026#34;rev\u0026#34;, (char*) NULL); // exit with code 127 if exec fails perror(\u0026#34;exec failed\u0026#34;); exit(127); break; // parent default: // close unecessary pipes close(pp2c[0]); close(pc2p[1]); // open pipes as stream FILE *out = fdopen(pp2c[1], \u0026#34;w\u0026#34;); FILE *in = fdopen(pc2p[0], \u0026#34;r\u0026#34;); char word[1024]; // redirect input to child process while (scanf(\u0026#34;%s\u0026#34;, word) != EOF) { fprintf(out, \u0026#34;%s\\n\u0026#34;, word); } fclose(out); // read child process output while (fscanf(in, \u0026#34;%s\u0026#34;, word) != EOF) { printf(\u0026#34;%s\\n\u0026#34;, word); } fclose(in); // call wait on exited child wait(NULL); break; } return 0; } The suitable situation to use pipe is IPC among related processes (related by fork) and the communication should be simple enough to use raw binary bytes. The perfect and classic application of pipe is executing binary programs, which is the scenario behind almost every command line typed in a shell. The limitation of pipe is also straightforward: only applies to realted processes and only one-to-one communications. For more advanced IPC, consider FIFO, MessageQueue, Shared Memory and Socket.\n","date":"27 July 2012","permalink":"https://hzqtc.github.io/2012/07/linux-ipc-with-pipes.html","section":"Posts","summary":"\u003cp\u003eInter-Process Communication (IPC) is a set of methods for exchanging data among multiple processes. IPC is a very common mechanism in Linux and Pipe maybe one of the most widely used IPC methods. When you type \u003ccode\u003ecat foo | grep bar\u003c/code\u003e, you create a pipe to connect \u003cem\u003estdout\u003c/em\u003e of \u003ccode\u003ecat\u003c/code\u003e to \u003cem\u003estdin\u003c/em\u003e of \u003ccode\u003egrep\u003c/code\u003e. A pipe, as its name states, can be understood as a channel with two ends. Pipe is actually implemented using a piece of kernel memory. The system call \u003ccode\u003epipe\u003c/code\u003e always create a pipe and two associated file descriptions, \u003ccode\u003efd[0]\u003c/code\u003e for reading from the pipe and \u003ccode\u003efd[1]\u003c/code\u003e for writing to the pipe.\u003c/p\u003e","title":"Linux IPC with Pipes"},{"content":"","date":null,"permalink":"https://hzqtc.github.io/tags/pipe/","section":"Tags","summary":"","title":"Pipe"},{"content":"","date":null,"permalink":"https://hzqtc.github.io/tags/audio/","section":"Tags","summary":"","title":"Audio"},{"content":"","date":null,"permalink":"https://hzqtc.github.io/tags/libao/","section":"Tags","summary":"","title":"Libao"},{"content":"","date":null,"permalink":"https://hzqtc.github.io/tags/libmpg123/","section":"Tags","summary":"","title":"Libmpg123"},{"content":"","date":null,"permalink":"https://hzqtc.github.io/tags/mp3/","section":"Tags","summary":"","title":"Mp3"},{"content":"I\u0026rsquo;m rewriting some of my python applications using C. One of them plays online mp3 audio. I used gstreamer to play mp3 and I\u0026rsquo;m considering switching to a more lightweight solution. Finally, I choose libmpg123 and libao. Libmpg123 is used to decode mp3 and libao is then used to make the sound.\nPlay local files # Well, the coding part is rather easy. Initialize, allocate some resources, decode some bytes, play the decoded bytes, keep decoding until all done, clean up and shut down. The following sample code shows how to play a mp3 file give in commnd line arguments with libmpg123 and libao.\n#include \u0026lt;ao/ao.h\u0026gt; #include \u0026lt;mpg123.h\u0026gt; #define BITS 8 int main(int argc, char *argv[]) { mpg123_handle *mh; unsigned char *buffer; size_t buffer_size; size_t done; int err; int driver; ao_device *dev; ao_sample_format format; int channels, encoding; long rate; if(argc \u0026lt; 2) exit(0); /* initializations */ ao_initialize(); driver = ao_default_driver_id(); mpg123_init(); mh = mpg123_new(NULL, \u0026amp;err); buffer_size = mpg123_outblock(mh); buffer = (unsigned char*) malloc(buffer_size * sizeof(unsigned char)); /* open the file and get the decoding format */ mpg123_open(mh, argv[1]); mpg123_getformat(mh, \u0026amp;rate, \u0026amp;channels, \u0026amp;encoding); /* set the output format and open the output device */ format.bits = mpg123_encsize(encoding) * BITS; format.rate = rate; format.channels = channels; format.byte_format = AO_FMT_NATIVE; format.matrix = 0; dev = ao_open_live(driver, \u0026amp;format, NULL); /* decode and play */ while (mpg123_read(mh, buffer, buffer_size, \u0026amp;done) == MPG123_OK) ao_play(dev, buffer, done); /* clean up */ free(buffer); ao_close(dev); mpg123_close(mh); mpg123_delete(mh); mpg123_exit(); ao_shutdown(); return 0; } Save the code as play.c and build it. Remember you must first install libmpg123 and libao.\ngcc -O2 -o play play.c -lmpg123 -lao Run the programm with a mp3 file path in command line.\n./play /path/to/file.mp3 Play URLs # It\u0026rsquo;s a little complicated to play HTTP URLs because you can\u0026rsquo;t pass a URL directly to mpg123_open. We should use mpg123_open_feed instead. We also use libcurl to read HTTP URLs and feed the received data for decoding using mpg123_feed. Then we use mpg123_decode_frame to try to decode a audio frame. Based on the return value of mpg123_decode_frame, we are able to decide the following situations: a frame is successfuly decoded, a new decoding format is encountered or more data is required.\n#include \u0026lt;curl/curl.h\u0026gt; #include \u0026lt;mpg123.h\u0026gt; #include \u0026lt;ao/ao.h\u0026gt; #define BITS 8 mpg123_handle *mh = NULL; ao_device *dev = NULL; size_t play_stream(void *buffer, size_t size, size_t nmemb, void *userp) { int err; off_t frame_offset; unsigned char *audio; size_t done; ao_sample_format format; int channels, encoding; long rate; mpg123_feed(mh, (const unsigned char*) buffer, size * nmemb); do { err = mpg123_decode_frame(mh, \u0026amp;frame_offset, \u0026amp;audio, \u0026amp;done); switch(err) { case MPG123_NEW_FORMAT: mpg123_getformat(mh, \u0026amp;rate, \u0026amp;channels, \u0026amp;encoding); format.bits = mpg123_encsize(encoding) * BITS; format.rate = rate; format.channels = channels; format.byte_format = AO_FMT_NATIVE; format.matrix = 0; dev = ao_open_live(ao_default_driver_id(), \u0026amp;format, NULL); break; case MPG123_OK: ao_play(dev, audio, done); break; case MPG123_NEED_MORE: break; default: break; } } while(done \u0026gt; 0); return size * nmemb; } int main(int argc, char *argv[]) { if(argc \u0026lt; 2) return 0; ao_initialize(); mpg123_init(); mh = mpg123_new(NULL, NULL); mpg123_open_feed(mh); CURL *curl = curl_easy_init(); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, play_stream); curl_easy_setopt(curl, CURLOPT_URL, argv[1]); curl_easy_perform(curl); curl_easy_cleanup(curl); mpg123_close(mh); mpg123_delete(mh); mpg123_exit(); ao_close(dev); ao_shutdown(); return 0; } Save the code as playurl.c and build it. Remember you must first install libmpg123 libao and libcurl.\ngcc -O2 -o playurl playurl.c -lmpg123 -lao -lcurl Run the programm with a mp3 url in command line.\n./playurl http://url.to/file.mp3 We use libcurl to open URL and play_stream is called to process the downloaded buffer. The major difference between local file version and URL version is we use different decoding interface. Notice the do...while loop in play_stream, it can\u0026rsquo;t be omitted because a piece of downloaded buffer may contains several frames to be decoded.\n","date":"24 May 2012","permalink":"https://hzqtc.github.io/2012/05/play-mp3-with-libmpg123-and-libao.html","section":"Posts","summary":"\u003cp\u003eI\u0026rsquo;m rewriting some of my python applications using C. One of them plays online mp3 audio. I used gstreamer to play mp3 and I\u0026rsquo;m considering switching to a more lightweight solution. Finally, I choose \u003ca href=\"http://www.mpg123.de/\" target=\"_blank\" rel=\"noreferrer\"\u003elibmpg123\u003c/a\u003e and \u003ca href=\"http://xiph.org/ao/\" target=\"_blank\" rel=\"noreferrer\"\u003elibao\u003c/a\u003e. Libmpg123 is used to decode mp3 and libao is then used to make the sound.\u003c/p\u003e","title":"Play MP3 with libmpg123 and libao"},{"content":"","date":null,"permalink":"https://hzqtc.github.io/tags/mupdf/","section":"Tags","summary":"","title":"Mupdf"},{"content":"","date":null,"permalink":"https://hzqtc.github.io/tags/pdf/","section":"Tags","summary":"","title":"Pdf"},{"content":"","date":null,"permalink":"https://hzqtc.github.io/tags/poppler/","section":"Tags","summary":"","title":"Poppler"},{"content":"I\u0026rsquo;m looking for a lightweight and fast PDF viewer recently. I tried some Poppler based PDF viewers, but they are all very slow when opening large PDF documents. Then I found MuPDF. MuPDF is a lightweight PDF library and viewer. It amazed me that it\u0026rsquo;s extremly fast. I becomes interseted in finding out how faster MuPDF actually is than Poppler.\nExperiment Setup # The plan is rendering PDF pages using both libray and comparing the cost time. I use pdfdraw-mupdf which comes together with MuPDF package as the render program for MuPDF. I also wrote a small program to render PDF using Poppler. The program is slightly modified from an example in cairo document. Both programs render a range of pages in a PDF file into PNG files.\nThe PDF file used in the experiment has more than 1500 pages. And both programs are invoked to render the following page ranges: 1-100, 101-300, 301-700, 701-1500. So 100, 200, 400, 800 different pages will be rendered each time.\nExperiment Result # Render time is simply obtain by the time command and measured in seconds.\nThe result shows that MuPDF is 95% faster than Poppler at most and 78% faster at average. Poppler uses about 14 seconds to render 100 pages while MuPDF only uses about 8 seconds.\nConclusion # Poppler uses Cairo to save result to image files. I don\u0026rsquo;t know which is the bottleneck: Poppler iteself or Cairo. Also notice that MuPDF has its own graphics library Fitz. On the other hand, MuPDF is not able to render to other formats other than image. Poppler, with cairo as backend, supports more output formats. Therefore, if you just just want a lightweight and fast PDF viewer, I think you should consider MuPDF. If you want more features, it\u0026rsquo;s better to choose Poppler.\n","date":"15 April 2012","permalink":"https://hzqtc.github.io/2012/04/poppler-vs-mupdf.html","section":"Posts","summary":"\u003cp\u003eI\u0026rsquo;m looking for a lightweight and fast PDF viewer recently. I tried some \u003ca href=\"http://poppler.freedesktop.org/\" target=\"_blank\" rel=\"noreferrer\"\u003ePoppler\u003c/a\u003e based PDF viewers, but they are all very slow when opening large PDF documents. Then I found \u003ca href=\"http://mupdf.com/\" target=\"_blank\" rel=\"noreferrer\"\u003eMuPDF\u003c/a\u003e. MuPDF is a lightweight PDF library and viewer. It amazed me that it\u0026rsquo;s extremly fast. I becomes interseted in finding out how faster MuPDF actually is than Poppler.\u003c/p\u003e","title":"Poppler vs MuPDF"},{"content":"","date":null,"permalink":"https://hzqtc.github.io/tags/ghostscript/","section":"Tags","summary":"","title":"Ghostscript"},{"content":"PDF manipulations such as merging, extracting and croping are the most ordinary things in eveyday life. But people feel difficult to do such jobs because of unawareness of some exordinary PDF tools. I\u0026rsquo;m gonna to introduce you a few PDF tools.\nGhostscript # The first tool (or toolkit, more precisely) is Ghostscript. In Archlinux, simply use pacman to install it: pacman -S ghostscript.\nGhostscript is very powerful and complicated, PDF manipulation is only a small part of it. The main concept in Ghostscript toolkit is DEVICE, which instruct the output format. Fortunately, we need only know pdfwrite device to manipulate PDF.\nMerging and Extracting # The command line to merge PDF:\ngs -sDEVICE=pdfwrite -dBATCH -dNOPAUSE -dQUIET -sOutputFile=out.pdf in1.pdf in2.pdf out.pdf is the name of output PDF, and inx.pdf are input PDFs. And the command line to extract page x to page y from a PDF:\ngs -sDEVICE=pdfwrite -dBATCH -dNOPAUSE -dQUIET -dFirstPage=x -dLastPage=y -sOutputFile=out.pdf in.pdf Bounding Box # There is another interseting device in Ghostscipt: bbox. This device output the bounding box for each page in a PDF. The bounding box is the minium page size including all content in a page.\ngs -sDEVICE=bbox -dBATCH -dNOPAUSE -dQUIET -dFirstPage=x -dLastPage=y in.pdf PDFCrop # The second tool is PDFCrop, which is a perl script shipped within tex suites. It\u0026rsquo;s different from another PDFCrop. PDFCrop can cut the whitespace edge in PDF pages automatically. In default, PDFCrop use Ghostscript bbox device to determine the bounding box for each page and crop that page using the detected bounding box. However, it\u0026rsquo;s possible to specify a bounding box for all pages instead of detect it every page. You may also set different bounding box for odd and even pages or add margins to each page. For more usage information, refer to pdfcrop --help.\nCropping # To crop a PDF with PDFCrop:\npdfcrop original.pdf cropped.pdf But there is a new problem: the cropped PDF has a different pagesize compared to the original one. We should resize the cropped PDF to its original pagesize. This is easy with Ghostscript:\ngs -sDEVICE=pdfwrite -dBATCH -dNOPAUSE -dQUIET -sPAPERSIZE=a4 -dPDFFitPage -sOutputFile=resized.pdf cropped.pdf In the above example, the pagesize of original PDF is assumed to A4. And the -dPDFFitPage option make sure the cropped PDF is resized instead of expanded.\n","date":"13 April 2012","permalink":"https://hzqtc.github.io/2012/04/pdf-tools-merging-extracting-and-cropping.html","section":"Posts","summary":"\u003cp\u003ePDF manipulations such as merging, extracting and croping are the most ordinary things in eveyday life. But people feel difficult to do such jobs because of unawareness of some exordinary PDF tools. I\u0026rsquo;m gonna to introduce you a few PDF tools.\u003c/p\u003e","title":"PDF Tools: Merging, Extracting and Cropping"},{"content":"","date":null,"permalink":"https://hzqtc.github.io/tags/pdfcrop/","section":"Tags","summary":"","title":"Pdfcrop"},{"content":"","date":null,"permalink":"https://hzqtc.github.io/categories/utility/","section":"Categories","summary":"","title":"Utility"},{"content":"When I was playing with a dozen of identical VirtualMachines, I always need to repeat some commands on each of them. This is painful: open VNC (or SSH) of the VM, type some long and boring commands and repeat the same thing on another VM. Then I figure out a way to avoid repeat. Everybody hates REPEAT, right?\nFirst of all, all these VMs must be able to connected via SSH. If you have problem on SSH to VMs, you need to setup a network bridge (refer to my previous post for more detail).\nNext, copy your public key to each VM (If you don\u0026rsquo;t have a public key yet, generate it with ssh-keygen). This step is necessary to login on VMs without typing a password. Assume there are ten VMs and their IP address are 192.168.1.10 to 192.168.1.19. Run the following commands on the host:\nfor i in `seq 0 9` do ssh-copy-id user@192.168.1.1$i done You will be asked for password for each VM only once. And it\u0026rsquo;s time for a rest, let\u0026rsquo;s review SSH. I don\u0026rsquo;t know how many people know that ssh can has a optional command field. At least I didn\u0026rsquo;t know it just a moment ago.\nssh [user@]hostname [command] When command field is specified, it is executed on the remote host instead of a login shell. Repeating commands on all VMs will be as simple as write a loop. A typical example is restart httpd on all VMs and display status of httpd:\nfor i in `seq 0 9` do echo \u0026#34;Processing VM$i\u0026#34; ssh user@192.168.1.1$i \u0026#34;rc.d restart httpd; rc.d list httpd\u0026#34; done ","date":"4 March 2012","permalink":"https://hzqtc.github.io/2012/03/repeat-commands-on-a-dozen-vms-with-a-single-loop.html","section":"Posts","summary":"\u003cp\u003eWhen I was playing with a dozen of identical VirtualMachines, I always need to repeat some commands on each of them. This is painful: open VNC (or SSH) of the VM, type some long and boring commands and repeat the same thing on another VM. Then I figure out a way to avoid repeat. Everybody hates \u003cem\u003eREPEAT\u003c/em\u003e, right?\u003c/p\u003e","title":"Repeat Commands on a Dozen VMs with a Single Loop"},{"content":"","date":null,"permalink":"https://hzqtc.github.io/tags/ssh/","section":"Tags","summary":"","title":"Ssh"},{"content":"","date":null,"permalink":"https://hzqtc.github.io/tags/kvm/","section":"Tags","summary":"","title":"Kvm"},{"content":"As many other hypervisors, KVM provide several types of networking. KVM use NAT in default, in which case the guest can reach the outside world (the host and all place the host can reach) but the outside world cannot reach the guest. That means, if you don\u0026rsquo;t need to access the guest through network (SSH for example), NAT is good enough for you. However, if you want more, let me introduce you the bridging way.\nConcept # In a typical bridged network environment, all guest are connected to a virtual bridge. A host network interface is also connected to the bridge. The packets are forwarded to the guests based on their MAC address, just like any other bridges. In more detai, each guest has a corresponding tap device in the host. These tap devices are both connected to the bridge and the guest, as a network channel.\nBefore writing scripts and typing commands, install some tools we need: ip, brctl and tunctl. In ArchLinux, install the following packages:\npacman -S --need iproute2 bridge-utils uml_utilities Create a bridge # Create a bridge is not just as simple as brctl addbr br0, some extra configurations must be done.\n#!/bin/bash addr=\u0026#34;192.168.1.50/24\u0026#34; gw=\u0026#34;192.168.1.1\u0026#34; echo \u0026#34;remove ip from eth0\u0026#34; sudo ip addr del $addr dev eth0 sudo ip link set eth0 up echo \u0026#34;create br0\u0026#34; sudo brctl addbr br0 echo \u0026#34;add eth0 to br0\u0026#34; sudo brctl addif br0 eth0 echo \u0026#34;bring up br0\u0026#34; sudo ip addr add $addr dev br0 sudo ip link set br0 up echo \u0026#34;set default gateway\u0026#34; sudo ip route add default via $gw dev br0 And in contrast to creating a bridge, the opposite operation is to delete it.\n#!/bin/bash addr=\u0026#34;192.168.1.50/24\u0026#34; gw=\u0026#34;192.168.1.1\u0026#34; echo \u0026#34;shut down br0\u0026#34; sudo ip link set br0 down echo \u0026#34;remove eth0 from br0\u0026#34; sudo brctl delif br0 eth0 echo \u0026#34;remove br0\u0026#34; sudo brctl delbr br0 echo \u0026#34;bring up eth0\u0026#34; sudo ip addr add $addr dev eth0 sudo ip link set eth0 up echo \u0026#34;set default gateway\u0026#34; sudo ip route add default via $gw dev eth0 Change the addr to the host\u0026rsquo;s IP address and gw to the host\u0026rsquo;s gateway. Save the two scripts as brup and brdown.\nPrepare tap config/deconfig scripts # Creating tap device is the job of qemu, what the user need to do is provide a config script and a deconfig script. The config script qemu-ifup is called when a guest starts.\n#!/bin/bash tap=$1 echo \u0026#34;bring up $tap\u0026#34; sudo ip link set $tap up echo \u0026#34;add $tap to br0\u0026#34; sudo brctl addif br0 $tap The deconfig script qemu-ifdown is called when a guest exit.\n#!/bin/bash tap=$1 echo \u0026#34;remove $tap from br0\u0026#34; sudo brctl delif br0 $tap echo \u0026#34;shut down $tap\u0026#34; sudo ip link set $tap down Config guest network # Now everything is setup, start guest with the following parameters:\nqemu-kvm -hda /path/to/vm.img -net nic -net tap,script=/path/to/qemu-ifup,downscript=/path/to/qemu-ifdown The last thing is to setup guest\u0026rsquo;s network as the same as the host but choose a unique IP address.\n","date":"27 February 2012","permalink":"https://hzqtc.github.io/2012/02/kvm-network-bridging.html","section":"Posts","summary":"\u003cp\u003eAs many other hypervisors, KVM provide several types of networking. KVM use NAT in default, in which case the guest can reach the outside world (the host and all place the host can reach) but the outside world cannot reach the guest. That means, if you don\u0026rsquo;t need to access the guest through network (SSH for example), NAT is good enough for you. However, if you want more, let me introduce you the bridging way.\u003c/p\u003e","title":"KVM Network Bridging"},{"content":"","date":null,"permalink":"https://hzqtc.github.io/tags/network/","section":"Tags","summary":"","title":"Network"},{"content":"","date":null,"permalink":"https://hzqtc.github.io/categories/setup/","section":"Categories","summary":"","title":"Setup"}]