From 419bb73fd072e53106688d31b85879f052f15241 Mon Sep 17 00:00:00 2001 From: Nemo Date: Sat, 2 May 2020 19:08:46 +0530 Subject: [PATCH] cleanup 2020 --- ap-hotspot | 284 ------------- apt-fast | 51 --- backup | 4 - beepoff.sh | 50 --- ccg | 4 +- cct | 22 - cmus-current-track.sh | 37 -- colors-table | 36 -- cwdterm.sh | 5 +- epub.py | 369 ----------------- extract_uimage.sh | 5 +- fasd | 624 ---------------------------- github-init-repo | 8 + gkeyring | 10 - gmail.py | 60 --- gnome-keyring-dumper.py | 27 -- niceload | 882 ---------------------------------------- split-audio-by-chapters | 9 +- 18 files changed, 22 insertions(+), 2465 deletions(-) delete mode 100755 ap-hotspot delete mode 100755 apt-fast delete mode 100755 backup delete mode 100755 beepoff.sh delete mode 100755 cct delete mode 100755 cmus-current-track.sh delete mode 100755 colors-table delete mode 100755 epub.py delete mode 100755 fasd delete mode 100755 gkeyring delete mode 100755 gmail.py delete mode 100755 gnome-keyring-dumper.py delete mode 100755 niceload diff --git a/ap-hotspot b/ap-hotspot deleted file mode 100755 index f47e717..0000000 --- a/ap-hotspot +++ /dev/null @@ -1,284 +0,0 @@ -#!/bin/bash -# Script to set up a WiFi Hotspot in Ubuntu that works with -# Android and Windows Phone. -# -# Copyright (C) 2014 Alin Andrei -# Copyright (C) 2014 Satyajit sahoo -# -# This scipt is free software; you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published -# by the Free Software Foundation; either version 3 of the License, -# or (at your option) any later version. -# -# The script is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this script. If not, see . - -# Global variables -logfile="/tmp/hostapd.log" -pidfile="/tmp/hotspot.pid" -hotspotconfig="/etc/ap-hotspot.conf" -dnsmasqconfig="/etc/dnsmasq.d/ap-hotspot.rules" -user=$(who | awk '{print $1}' | sed '/^root$/d' | uniq) -WMPID=$(ps -u $user | tail -n 1 | awk '{print $1}') -DBUS=$(egrep -z 'DBUS_SESSION_BUS_ADDRESS|DISPLAY' /proc/${WMPID}/environ | sed -r -e 's/(.)DBUS_/\1 DBUS_/' -e 's/(.)DISPLAY/\1 DISPLAY/') - -show_msg() { -echo -e "$@" -} - -show_info() { -echo -e "\033[1;34m$@\033[0m" -} - -show_warn() { -echo -e "\033[1;33m$@\033[0m" -} - -show_err() { -echo -e "\033[1;31m$@\033[0m" 1>&2 -} - -show_debug() { -while read input; do - [[ "$debug" == "true" ]] && echo -e "$input" -done -} - -show_notify() { -su $user -s /bin/bash -c "${DBUS} notify-send -h int:transient:1 -i \"network-wireless\" \"$@\"" -} - -check_root() { -# Check if user is root -if [[ ! $(whoami) = "root" ]]; then - show_err "Please run the script as root" - exit 1 -fi -} - -check_supported() { -# Check if the wireless card supports Access Point mode. This script won't work if it doesn't support it -if [[ ! $(iw list 2>&1 | grep -A6 "Supported interface modes" | grep AP$) ]]; then - show_err "Your wireless card or driver does not support Access Point mode" - exit 1 -fi -} - -check_network() { -# Check if Wireless is disabled -if [[ $(iwconfig "$INTERFACE_WLAN" 2>&1 | grep "Tx-Power=off") ]]; then - show_err "WiFi is disabled, please enable WiFi before running this script" - exit 1 -# Check if Wireless is enabled, but connected to a network -elif [[ ! $(iwconfig "$INTERFACE_WLAN" 2>&1 | grep "ESSID:off/any") && $(iwconfig "$INTERFACE_WLAN" 2>&1 | grep "ESSID:") ]]; then - show_err "Please disconnect WiFi before proceeding" - exit 1 -fi -} - -check_connected() { -# Monitor logfile for connected devices -lines_con="0" -lines_dis="0" -while [[ -f "$logfile" ]]; do - if [[ "$lines_con" < $(grep -c "AP-STA-CONNECTED" "$logfile") ]]; then - show_notify "New device connected to Hotspot" - (( lines_con++ )) - elif [[ "$lines_dis" < $(grep -c "AP-STA-DISCONNECTED" "$logfile") ]]; then - show_notify "Device disconnected from Hotspot" - (( lines_dis++ )) - fi - sleep 5 -done -} - -configure() { -# Check root -check_root -# Check supported -check_supported -# Reset config -rm -f "$hotspotconfig" -rm -f "$dnsmasqconfig" -# Detect configuration -show_msg "Detecting configuration..." -INTERFACE_NET=$(route | grep -iw "default" | awk '{printf "%s ", $NF}' | sed -s 's/ $//') -INTERFACE_WLAN=$(iwconfig 2>&1 | grep "^wlan" | sed -e 's/ .*//g' | tail -n 1) -SSID="myhotspot" -WPAPASS="qwerty0987" -# Network interface connected to the Internet -if [[ ! $INTERFACE_NET ]]; then - show_warn "Failed to detect the network interface connected to the Internet. Please enter your network interface (e.g.- eth1):" -else - show_msg "Detected $INTERFACE_NET as the network interface connected to the Internet. Press ENTER if this is correct or enter the desired interface below (e.g.- eth0, ppp0 etc.):" -fi -read interface_net -[[ "$interface_net" ]] && INTERFACE_NET="$interface_net" -# WiFi interface -if [[ ! $INTERFACE_WLAN ]]; then - show_warn "Failed to detect the WiFi interface. Please enter your WiFi interface (e.g.- wlan0):" -else - show_msg "Detected $INTERFACE_WLAN as your WiFi interface. Press ENTER if this is correct or enter the desired interface (e.g.- wlan1):" -fi -read interface_wlan -[[ "$interface_wlan" ]] && INTERFACE_WLAN="$interface_wlan" -# Hotspot SSID -show_msg "Enter the desired Access Point name or press ENTER to use the default one ($SSID):" -read ssid -[[ "$ssid" ]] && SSID="$ssid" -# WPA Passphrase -show_msg "Enter the desired WPA Passphrase below or press ENTER to use the default one ($WPAPASS):" -read wpapass -[[ "$wpapass" ]] && WPAPASS="$wpapass" -# Write the hostapd config file -cat < /dev/null 2>&1 -# WiFi Hotspot -interface=$INTERFACE_WLAN -driver=nl80211 -#Access Point -ssid=$SSID -hw_mode=g -# WiFi Channel: -channel=1 -macaddr_acl=0 -auth_algs=1 -ignore_broadcast_ssid=0 -wpa=2 -wpa_passphrase=$WPAPASS -wpa_key_mgmt=WPA-PSK -wpa_pairwise=TKIP -rsn_pairwise=CCMP -EOF -# Add the required bits to the dnsmasq config file -if [[ ! $(grep "Bind to only one interface" "$dnsmasqconfig" > /dev/null 2>&1) ]]; then -cat < /dev/null 2>&1 -# Bind to only one interface -bind-interfaces -# Choose interface for binding -interface=$INTERFACE_WLAN -# Specify range of IP addresses for DHCP leasses -dhcp-range=192.168.150.2,192.168.150.10,12h -#INTERFACE_NET=$INTERFACE_NET -EOF -chmod +x "$dnsmasqconfig" -fi -} - -get_vars() { -# Run Configuration Wizard if config files don't exist -[[ ! -f "$hotspotconfig" || ! -f "$dnsmasqconfig" ]] && configure -# Get $INTERFACE_NET and $INTERFACE_WLAN from the config files -INTERFACE_WLAN=$(grep "interface" "$hotspotconfig" | sed -e 's/interface=//g') -INTERFACE_NET=$(grep "INTERFACE_NET" "$dnsmasqconfig" | sed -e 's/#INTERFACE_NET=//g') -} - -start() { -# Check previous process -if [[ -f "$pidfile" ]]; then - show_err "Another process is already running" - exit 1 -fi -# Check root -check_root -# Check supported -check_supported -# Get variables -get_vars -# Check network -check_network -# Write the PID to a file -echo "$$" > "$pidfile" -show_info "Starting Wireless Hotspot..." -# Set up the services -service hostapd stop 2>&1 | show_debug -service dnsmasq stop 2>&1 | show_debug -update-rc.d hostapd disable 2>&1 | show_debug -update-rc.d dnsmasq disable 2>&1 | show_debug -# Configure IP address for WLAN -ifconfig "$INTERFACE_WLAN" 192.168.150.1 2>&1 | show_debug -# Start DHCP/DNS server -service dnsmasq restart 2>&1 | show_debug -# Enable routing -sysctl net.ipv4.ip_forward=1 2>&1 | show_debug -# Enable NAT -iptables -t nat -A POSTROUTING -o "$INTERFACE_NET" -j MASQUERADE 2>&1 | show_debug -# Run access point daemon -if [[ $(hostapd --help 2>&1 | grep "\-f") ]]; then - rm -f "$logfile" - touch "$logfile" - hostapd -B "$hotspotconfig" -f "$logfile" - while : - do - [[ $(grep "Using interface" "$logfile") ]] && show_info "Wireless Hotspot active" && show_notify "Wireless Hotspot active" && break - sleep 5 - done - check_connected 2>&1 & - disown -else - hostapd -B "$hotspotconfig" 2>&1 | show_debug - show_info "Wireless Hotspot active" -fi -} - -stop() { -# Check root -check_root -# Get variables -get_vars -# Kill process -show_info "Stopping Wireless Hotspot..." -if [[ -f "$pidfile" ]]; then - pid=$(cat "$pidfile") - rm -f "$pidfile" - [[ $(grep -s "ap-hotspot" "/proc/$pid/cmdline") ]] && kill -9 "$pid" -fi -# Delete log -rm -f "$logfile" -# Disable NAT -iptables -D POSTROUTING -t nat -o "$INTERFACE_NET" -j MASQUERADE 2>&1 | show_debug -# Disable routing -sysctl net.ipv4.ip_forward=0 2>&1 | show_debug -# Set up the services -service hostapd stop 2>&1 | show_debug -service dnsmasq stop 2>&1 | show_debug -# Restart WiFi and disable newly created mon.WLAN network -if [[ ! -z $(ifconfig | grep "mon.$INTERFACE_WLAN") ]]; then -# Check if the hotspot is active - ifconfig "mon.$INTERFACE_WLAN" down -fi -ifconfig "$INTERFACE_WLAN" down -ifconfig "$INTERFACE_WLAN" up -} - -restart() { -show_info "Restarting Wireless Hotspot..." -stop -start -} - -case "$1" in - start) - start;; - stop) - stop;; - restart) - restart;; - configure) - configure;; - debug) - debug="true" - start;; - *) - args=( "start" "stop" "restart" "configure" "debug" ) - desc=( "start wireless hotspot" "stop wireless hotspot" "restart wireless hotspot" "configure hotspot" "start with detailed messages" ) - echo -e "Usage:\tap-hotspot [argument]\n" - for ((i=0; i < ${#args[@]}; i++)); do - printf "\t%-15s%-s\n" "${args[i]}" "${desc[i]}" - done - exit;; -esac diff --git a/apt-fast b/apt-fast deleted file mode 100755 index bcb432a..0000000 --- a/apt-fast +++ /dev/null @@ -1,51 +0,0 @@ -# !/bin/sh -# apt-fast v0.03 by Matt Parnell http://www.mattparnell.com, this thing is fully open-source -# if you do anything cool with it, let me know so I can publish or host it for you -# contact me at admin@mattparnell.com - -# Special thanks -# Travis/travisn000 - support for complex apt-get commands -# Allan Hoffmeister - aria2c support -# Abhishek Sharma - aria2c with proxy support -# Richard Klien - Autocompletion, Download Size Checking (made for on ubuntu, untested on other distros) -# Patrick Kramer Ruiz - suggestions - see Suggestions.txt -# Sergio Silva - test to see if axel is installed, root detection/sudo autorun - -# Use this just like apt-get for faster package downloading. - -# Check for proper priveliges -[ "`whoami`" = root ] || exec sudo "$0" "$@" - -# Test if the axel is installed -if [ ! -x /usr/local/bin/axel ] -then echo "axel is not installed, perform this?(y/n)" - read ops - case $ops in - y) if apt-get install axel -y --force-yes - then echo "axel installed" - else echo "unable to install the axel. you are using sudo?" ; exit - fi ;; - n) echo "not possible usage apt-fast" ; exit ;; - esac -fi - -# If the user entered arguments contain upgrade, install, or dist-upgrade -if echo "$@" | grep -q "upgrade\|install\|dist-upgrade"; then - echo "Working..."; - - # Go into the directory apt-get normally puts downloaded packages - cd /var/cache/apt/archives/; - - # Have apt-get print the information, including the URI's to the packages - # Strip out the URI's, and download the packages with Axel for speediness - # I found this regex elsewhere, showing how to manually strip package URI's you may need...thanks to whoever wrote it - apt-get -y --print-uris $@ | egrep -o -e "(ht|f)tp://[^\']+" > apt-fast.list && cat apt-fast.list | xargs -l1 axel -a - - # Perform the user's requested action via apt-get - apt-get $@; - - echo -e "\nDone! Verify that all packages were installed successfully. If errors are found, run apt-get clean as root and try again using apt-get directly.\n"; - -else - apt-get $@; -fi diff --git a/backup b/backup deleted file mode 100755 index beea203..0000000 --- a/backup +++ /dev/null @@ -1,4 +0,0 @@ -#!/bin/bash -cd ~ -shopt -s dotglob -rsync --links --exclude-from ~/.rsync-exclude.txt -avz --progress ./ /media/nemo/Nemo_Backup/ diff --git a/beepoff.sh b/beepoff.sh deleted file mode 100755 index ef0830e..0000000 --- a/beepoff.sh +++ /dev/null @@ -1,50 +0,0 @@ -#!/bin/bash -# Shell script to disable (almost) all beeps on Crunchbang Linux -# @author: Akshay Dandekar -# @version: 0 (there will be no other) -# This script is free - do whatever you want with it etc… -# and I am not responsible for the outcome -# Blacklist pcspkr -if [ $(grep -c 'blacklist\ pcspkr' /etc/modprobe.d/pcspkr.conf) -eq 0 ] - then - echo 'blacklist pcspkr' | tee -a /etc/modprobe.d/pcspkr.conf - rmmod pcspkr - else - echo "blacklist pcspkr in pcspkr configuration” -fi -#set PC speaker and PC Beep to mute on amixer -amixer set 'PC speaker' 0% mute -amixer set 'PC Beep' 0% mute -# remove gtk application beeps -if [ $(grep -c 'gtk-error-bell\ \=\ 0' /home/$1/.gtkrc-2.0.mine) -eq 0 ] - then - echo "gtk-error-bell = 0" >> /home/$1/.gtkrc-2.0.mine - chmod 755 /home/$1/.gtkrc-2.0.mine - else - echo "gtk-error-bell already set to zero” -fi -# remove console beeps in X -if [ $(grep -c 'xset\ b\ off' /home/$1/.config/openbox/autostart.sh) -eq 0 ] - then - echo "\n - # remove console beeps in X –Added by $1 \nxset b off &” >> /home/$1/.config/openbox/autostart.sh - else - echo "console beeps already off in autostart script” -fi -# remove bash beeps -sed -i 's/^#\ set\ bell\-style\ none/set\ bell\-style\ none/g' /etc/inputrc -# remove console beeps from the system console -if [ $(grep -c 'setterm\ -blength\ 0' /etc/profile) -eq 0 ] - then - echo "setterm -blength 0" >> /etc/profile - echo "setterm -bfreq 0" >> /etc/profile - else - echo "console beeps already off in /etc/profile” -fi -# remove login sound from gdm -if [ $(grep -c 'SoundOnLogin=False' /etc/gdm/gdm.conf) -eq 0 ] - then - sed -i 's/\[greeter\]/\[greeter\]\nSoundOnLogin\=False/' /etc/gdm/gdm.conf - else - echo "login sound already off from gdm” -fi diff --git a/ccg b/ccg index a77c9b7..d56ffc7 100755 --- a/ccg +++ b/ccg @@ -1,5 +1,7 @@ #!/usr/bin/env php $CODE.OUT` -diff $CODE.OUT $CODE.OUT diff --git a/cmus-current-track.sh b/cmus-current-track.sh deleted file mode 100755 index 38bcd09..0000000 --- a/cmus-current-track.sh +++ /dev/null @@ -1,37 +0,0 @@ -#!/usr/bin/env bash - -current_song="$HOME/.cmus/now-playing.txt" -stat="stopped" - -while [[ -n "$1" ]]; do - case "$1" in - title) title="$2" ;; - album) album="$2" ;; - artist) artist="$2" ;; - status) stat="$2" ;; - file) file="$2" ;; - url) url="$2" ;; - *) ;; - esac - shift; shift -done - -msg="" -if [[ "$stat" == "stopped" ]]; then - msg="stopped" -else - if [[ -n "$title" ]]; then - msg="$title" - else - if [[ -n "$file" ]]; then - msg=$(basename "$file") - else - msg="" - fi - fi - - [[ -n "$artist" ]] && msg="$artist / $msg" - [[ "$stat" == "paused" ]] && msg="$msg [paused]" -fi - -echo "$msg" > "$current_song" \ No newline at end of file diff --git a/colors-table b/colors-table deleted file mode 100755 index f57a4c0..0000000 --- a/colors-table +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/zsh -# Display all available color combinations -# (bold/non-bold foreground on backgrounds) - -autoload -U colors && colors - -local -a bgs -if [[ $1 != "" ]]; then - bgs=($1) -else - # bgs=(${(k)bg}) - bgs=("-" 0 1 2 3 4 5 6 7) -fi - - -for b in $bgs; do - if (( $#bgs > 1 )); then - echo "bg: $b" - fi - for c in {0..7}; do - [[ $b != "-" ]] && tput setab $b - print -n "\x1b[$((c+30))m" ${(l.$((COLUMNS/2-1)).):-"$c:${color[$((c+30))]}"} - print -n "\x1b[$((c+30));1m" ${(r.$((COLUMNS/2-1)).):-"$((c+8)):${color[$((c+30))]}"} - print -P %{${reset_color}%} - done - - echo "== EXTENDED (base16) ==" - for c in {16..18}; do - [[ $b != "-" ]] && tput setab $b - tput setaf $c - print -n " ${(l.$((COLUMNS/2-1)).):-"$c:base16-$c"} " - tput setaf $((c+3)) - print -n ${(r.$((COLUMNS/2-1)).):-"$((c+3)):base16-$((c+3))"} - print -P %{${reset_color}%} - done -done \ No newline at end of file diff --git a/cwdterm.sh b/cwdterm.sh index 2437030..78fec1f 100755 --- a/cwdterm.sh +++ b/cwdterm.sh @@ -1,8 +1,11 @@ #!/bin/bash -CMD=urxvtc +CMD=alacritty CWD='' +$CMD +exit + # Get window ID ID=$(xdpyinfo | grep focus | cut -f4 -d " ") diff --git a/epub.py b/epub.py deleted file mode 100755 index 8633cb1..0000000 --- a/epub.py +++ /dev/null @@ -1,369 +0,0 @@ -#!/usr/bin/env python -''' -python/curses epub reader. Requires BeautifulSoup - -Keyboard commands: - Esc/q - quit - Tab/Left/Right - toggle between TOC and chapter views - TOC view: - Up - up a line - Down - down a line - PgUp - up a page - PgDown - down a page - Chapter view: - Up - up a page - Down - down a page - PgUp - up a line - PgDown - down a line - i - open images on page in web browser -''' - -import curses.wrapper, curses.ascii -import formatter, htmllib, locale, os, StringIO, re, readline, tempfile, zipfile -import base64, webbrowser - -from BeautifulSoup import BeautifulSoup - -try: - from fabulous import image - import PIL -except ImportError: - images = False -else: - images = True - -locale.setlocale(locale.LC_ALL, 'en_US.utf-8') - -basedir = '' - -def run(screen, program, *args): - curses.nocbreak() - screen.keypad(0) - curses.echo() - pid = os.fork() - if not pid: - os.execvp(program, (program,) + args) - os.wait()[0] - curses.noecho() - screen.keypad(1) - curses.cbreak() - -def open_image(screen, name, s): - ''' show images with PIL and fabulous ''' - if not images: - screen.addstr(0, 0, "missing PIL or fabulous", curses.A_REVERSE) - return - - ext = os.path.splitext(name)[1] - - screen.erase() - screen.refresh() - curses.setsyx(0, 0) - image_file = tempfile.NamedTemporaryFile(suffix=ext, delete=False) - image_file.write(s) - image_file.close() - try: - print image.Image(image_file.name) - except: - print image_file.name - finally: - os.unlink(image_file.name) - -def textify(html_snippet, img_size=(80, 45), maxcol=72): - ''' text dump of html ''' - class Parser(htmllib.HTMLParser): - def anchor_end(self): - self.anchor = None - def handle_image(self, source, alt, ismap, alight, width, height): - global basedir - self.handle_data( - '[img="{0}{1}" "{2}"]'.format(basedir, source, alt) - ) - - class Formatter(formatter.AbstractFormatter): - pass - - class Writer(formatter.DumbWriter): - def __init__(self, fl, maxcol=72): - formatter.DumbWriter.__init__(self, fl) - self.maxcol = maxcol - def send_label_data(self, data): - self.send_flowing_data(data) - self.send_flowing_data(' ') - - o = StringIO.StringIO() - p = Parser(Formatter(Writer(o, maxcol))) - p.feed(html_snippet) - p.close() - - return o.getvalue() - -def table_of_contents(fl): - global basedir - - # find opf file - soup = BeautifulSoup(fl.read('META-INF/container.xml')) - opf = dict(soup.find('rootfile').attrs)['full-path'] - - basedir = os.path.dirname(opf) - if basedir: - basedir = '{0}/'.format(basedir) - - soup = BeautifulSoup(fl.read(opf)) - - # title - yield (soup.find('dc:title').text, None) - - # all files, not in order - x, ncx = {}, None - for item in soup.find('manifest').findAll('item'): - d = dict(item.attrs) - x[d['id']] = '{0}{1}'.format(basedir, d['href']) - if d['media-type'] == 'application/x-dtbncx+xml': - ncx = '{0}{1}'.format(basedir, d['href']) - - # reading order, not all files - y = [] - for item in soup.find('spine').findAll('itemref'): - y.append(x[dict(item.attrs)['idref']]) - - z = {} - if ncx: - # get titles from the toc - soup = BeautifulSoup(fl.read(ncx)) - - for navpoint in soup('navpoint'): - k = navpoint.content.get('src', None) - # strip off any anchor text - k = k.split('#')[0] - if k: - z[k] = navpoint.navlabel.text - - # output - for section in y: - if section in z: - yield (z[section].encode('utf-8'), section.encode('utf-8')) - else: - yield (u'', section.encode('utf-8').strip()) - -def list_chaps(screen, chaps, start, length): - for i, (title, src) in enumerate(chaps[start:start+length]): - try: - if start == 0: - screen.addstr(i, 0, ' {0}'.format(title), curses.A_BOLD) - else: - screen.addstr(i, 0, '{0:-5} {1}'.format(start, title)) - except: - pass - start += 1 - screen.refresh() - return i - -def check_epub(fl): - if os.path.isfile(fl) and os.path.splitext(fl)[1].lower() == '.epub': - return True - -def dump_epub(fl, maxcol=float("+inf")): - if not check_epub(fl): - return - fl = zipfile.ZipFile(fl, 'r') - chaps = [i for i in table_of_contents(fl)] - for title, src in chaps: - print title - print '-' * len(title) - if src: - soup = BeautifulSoup(fl.read(src)) - print textify( - unicode(soup.find('body')).encode('utf-8'), - maxcol=maxcol, - ) - print '\n' - -def curses_epub(screen, fl): - if not check_epub(fl): - return - - #curses.mousemask(curses.BUTTON1_CLICKED) - - fl = zipfile.ZipFile(fl, 'r') - chaps = [i for i in table_of_contents(fl)] - chaps_pos = [0 for i in chaps] - start = 0 - cursor_row = 0 - - # toc - while True: - curses.curs_set(1) - maxy, maxx = screen.getmaxyx() - - if cursor_row >= maxy: - cursor_row = maxy - 1 - - len_chaps = list_chaps(screen, chaps, start, maxy) - screen.move(cursor_row, 0) - ch = screen.getch() - - # quit - if ch == curses.ascii.ESC: - return - try: - if chr(ch) == 'q': - return - except: - pass - - # up/down line - if ch in [curses.KEY_DOWN]: - if start < len(chaps) - maxy: - start += 1 - screen.clear() - elif cursor_row < maxy - 1 and cursor_row < len_chaps: - cursor_row += 1 - elif ch in [curses.KEY_UP]: - if start > 0: - start -= 1 - screen.clear() - elif cursor_row > 0: - cursor_row -= 1 - - # up/down page - elif ch in [curses.KEY_NPAGE]: - if start + maxy - 1 < len(chaps): - start += maxy - 1 - if len_chaps < maxy: - start = len(chaps) - maxy - screen.clear() - elif ch in [curses.KEY_PPAGE]: - if start > 0: - start -= maxy - 1 - if start < 0: - start = 0 - screen.clear() - - # to chapter - elif ch in [curses.ascii.HT, curses.KEY_RIGHT, curses.KEY_LEFT]: - if chaps[start + cursor_row][1]: - html = fl.read(chaps[start + cursor_row][1]) - soup = BeautifulSoup(html) - chap = textify( - unicode(soup.find('body')).encode('utf-8'), - img_size=screen.getmaxyx(), - maxcol=screen.getmaxyx()[1] - ).split('\n') - else: - chap = '' - screen.clear() - curses.curs_set(0) - - # chapter - while True: - maxy, maxx = screen.getmaxyx() - images = [] - for i, line in enumerate(chap[ - chaps_pos[start + cursor_row]: - chaps_pos[start + cursor_row] + maxy - ]): - try: - screen.addstr(i, 0, line) - mch = re.search('\[img="([^"]+)" "([^"]*)"\]', line) - if mch: - images.append(mch.group(1)) - except: - pass - screen.refresh() - ch = screen.getch() - - # quit - if ch == curses.ascii.ESC: - return - try: - if chr(ch) == 'q': - return - except: - pass - - # to TOC - if ch in [curses.ascii.HT, curses.KEY_RIGHT, curses.KEY_LEFT]: - screen.clear() - break - - # up/down page - elif ch in [curses.KEY_DOWN]: - if chaps_pos[start + cursor_row] + maxy - 1 < len(chap): - chaps_pos[start + cursor_row] += maxy - 1 - screen.clear() - elif ch in [curses.KEY_UP]: - if chaps_pos[start + cursor_row] > 0: - chaps_pos[start + cursor_row] -= maxy - 1 - if chaps_pos[start + cursor_row] < 0: - chaps_pos[start + cursor_row] = 0 - screen.clear() - - # up/down line - elif ch in [curses.KEY_NPAGE]: - if chaps_pos[start + cursor_row] + maxy - 1 < len(chap): - chaps_pos[start + cursor_row] += 1 - screen.clear() - elif ch in [curses.KEY_PPAGE]: - if chaps_pos[start + cursor_row] > 0: - chaps_pos[start + cursor_row] -= 1 - screen.clear() - - #elif ch in [curses.KEY_MOUSE]: - # id, x, y, z, bstate = curses.getmouse() - # line = screen.instr(y, 0) - # mch = re.search('\[img="([^"]+)" "([^"]*)"\]', line) - # if mch: - # img_fl = mch.group(1) - - else: - try: - if chr(ch) == 'i': - for img in images: - err = open_image(screen, img, fl.read(img)) - if err: - screen.addstr(0, 0, err, curses.A_REVERSE) - - # edit html - elif chr(ch) == 'e': - - tmpfl = tempfile.NamedTemporaryFile(delete=False) - tmpfl.write(html) - tmpfl.close() - run(screen, 'vim', tmpfl.name) - with open(tmpfl.name) as changed: - new_html = changed.read() - os.unlink(tmpfl.name) - if new_html != html: - pass - # write to zipfile? - - # go back to TOC - screen.clear() - break - - except (ValueError, IndexError): - pass - -if __name__ == '__main__': - import argparse - - parser = argparse.ArgumentParser( - formatter_class=argparse.RawDescriptionHelpFormatter, - description=__doc__, - ) - parser.add_argument('-d', '--dump', action='store_true', - help='dump EPUB to text') - parser.add_argument('-c', '--cols', action='store', type=int, default=float("+inf"), - help='Number of columns to wrap; default is no wrapping.') - parser.add_argument('EPUB', help='view EPUB') - args = parser.parse_args() - - if args.EPUB: - if args.dump: - dump_epub(args.EPUB, args.cols) - else: - try: - curses.wrapper(curses_epub, args.EPUB) - except KeyboardInterrupt: - pass diff --git a/extract_uimage.sh b/extract_uimage.sh index 17157af..324ded8 100755 --- a/extract_uimage.sh +++ b/extract_uimage.sh @@ -2,6 +2,7 @@ # # Copyright (C) 2010 Matthias Buecher (http://www.maddes.net/) +# Source: https://github.com/mpoullet/shell_examples/blob/master/extract_uImage.sh # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -66,6 +67,6 @@ MAGIC=`dd if="${DATAFILE}" ibs=4 skip=9 count=1 | hexdump -v -e '1/1 "%02X"'` echo "zImage recognized with start 0x${START}, end 0x${END} and size ${SIZE}." TMPFILE='zImage' } -mv "${DATAFILE}" "${TMPFILE}" +mv "${DATAFILE}" "${TMPFILE}" -echo ">>> ${UIMAGE} extracted to ${TMPFILE}" \ No newline at end of file +echo ">>> ${UIMAGE} extracted to ${TMPFILE}" diff --git a/fasd b/fasd deleted file mode 100755 index b1e64f4..0000000 --- a/fasd +++ /dev/null @@ -1,624 +0,0 @@ -#!/usr/bin/env sh - -# Fasd (this file) can be sourced or executed by any POSIX compatible shell. - -# Fasd is originally written based on code from z (https://github.com/rupa/z) -# by rupa deadwyler under the WTFPL license. Most if not all of the code has -# been rewritten. - -# Copyright (C) 2011, 2012 by Wei Dai. All rights reserved. -# -# Permission is hereby granted, free of charge, to any person obtaining -# a copy of this software and associated documentation files (the -# "Software"), to deal in the Software without restriction, including -# without limitation the rights to use, copy, modify, merge, publish, -# distribute, sublicense, and/or sell copies of the Software, and to -# permit persons to whom the Software is furnished to do so, subject to -# the following conditions: -# -# The above copyright notice and this permission notice shall be included -# in all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - -fasd() { - - # make zsh do word splitting inside this function - [ "$ZSH_VERSION" ] && emulate sh && setopt localoptions - - case $1 in - --init) shift - while [ "$1" ]; do - case $1 in - env) - { # source rc files if present - [ -s "/etc/fasdrc" ] && . "/etc/fasdrc" - [ -s "$HOME/.fasdrc" ] && . "$HOME/.fasdrc" - - # set default options - [ -z "$_FASD_DATA" ] && _FASD_DATA="$HOME/.fasd" - [ -z "$_FASD_BLACKLIST" ] && _FASD_BLACKLIST="--help" - [ -z "$_FASD_SHIFT" ] && _FASD_SHIFT="sudo busybox" - [ -z "$_FASD_IGNORE" ] && _FASD_IGNORE="fasd ls echo" - [ -z "$_FASD_SINK" ] && _FASD_SINK=/dev/null - [ -z "$_FASD_TRACK_PWD" ] && _FASD_TRACK_PWD=1 - [ -z "$_FASD_MAX" ] && _FASD_MAX=2000 - [ -z "$_FASD_BACKENDS" ] && _FASD_BACKENDS=native - [ -z "$_FASD_FUZZY" ] && _FASD_FUZZY=2 - [ -z "$_FASD_VIMINFO" ] && _FASD_VIMINFO="$HOME/.viminfo" - [ -z "$_FASD_RECENTLY_USED_XBEL" ] && \ - _FASD_RECENTLY_USED_XBEL="$HOME/.local/share/recently-used.xbel" - - if [ -z "$_FASD_AWK" ]; then - # awk preferences - local awk; for awk in mawk gawk original-awk nawk awk; do - $awk "" && _FASD_AWK=$awk && break - done - fi - } >> "${_FASD_SINK:-/dev/null}" 2>&1 - ;; - - auto) cat <> "$_FASD_SINK" 2>&1 - -EOS - ;; - - posix-alias) cat <& /dev/null || fasd -d'; -EOS - ;; - - zsh-hook) cat <> "$_FASD_SINK" 2>&1 -} -autoload -Uz add-zsh-hook -add-zsh-hook preexec _fasd_preexec - -EOS - ;; - - bash-hook) cat <> "$_FASD_SINK" 2>&1 -} - -# add bash hook -case \$PROMPT_COMMAND in - *_fasd_prompt_func*) ;; - *) PROMPT_COMMAND="_fasd_prompt_func;\$PROMPT_COMMAND";; -esac - -EOS - ;; - - posix-hook) cat <> "$_FASD_SINK" 2>&1 -} -case \$PS1 in - *_fasd_ps1_func*) ;; - *) export PS1="\\\$(_fasd_ps1_func)\$PS1";; -esac - -EOS - ;; - - tcsh-hook) cat <& /dev/null'; -EOS - - ;; - - zsh-ccomp) cat <> "$_FASD_SINK" | \\ - sort -nr | sed 's/^[^ ]*[ ]*//' | while read -r line; do - compadd -U -V fasd "\$line" - done - compstate[insert]=menu # no expand - } - _fasd_zsh_word_complete_f() { _fasd_zsh_word_complete f ; } - _fasd_zsh_word_complete_d() { _fasd_zsh_word_complete d ; } - _fasd_zsh_word_complete_trigger() { - local _fasd_cur="\${words[CURRENT]}" - eval \$(fasd --word-complete-trigger _fasd_zsh_word_complete \$_fasd_cur) - } - # define zle widgets - zle -C fasd-complete complete-word _generic - zstyle ':completion:fasd-complete:*' completer _fasd_zsh_word_complete - zstyle ':completion:fasd-complete:*' menu-select - - zle -C fasd-complete-f complete-word _generic - zstyle ':completion:fasd-complete-f:*' completer _fasd_zsh_word_complete_f - zstyle ':completion:fasd-complete-f:*' menu-select - - zle -C fasd-complete-d complete-word _generic - zstyle ':completion:fasd-complete-d:*' completer _fasd_zsh_word_complete_d - zstyle ':completion:fasd-complete-d:*' menu-select -} - -EOS - ;; - - zsh-ccomp-install) cat <> "$_FASD_SINK" | sed -n "\\\$s/^.*'\\\\(.*\\\\)'/\\\\1/p") - \${COMP_LINE#* }" | while read -r line; do - quote_readline "\$line" 2>/dev/null || \\ - printf %q "\$line" 2>/dev/null && \\ - printf \\\\n - done) - local IFS=\$'\\n'; COMPREPLY=( \$RESULT ) -} -_fasd_bash_hook_cmd_complete() { - for cmd in \$*; do - complete -F _fasd_bash_cmd_complete \$cmd - done -} - -EOS - ;; - - bash-ccomp-install) cat <$`{}]\{1,\}/\1 /g' - ;; - - --proc) shift # process commands - # stop if we don't own $_FASD_DATA or $_FASD_RO is set - [ -f "$_FASD_DATA" -a ! -O "$_FASD_DATA" ] || [ "$_FASD_RO" ] && return - - # blacklists - local each; for each in $_FASD_BLACKLIST; do - case " $* " in *\ $each\ *) return;; esac - done - - # shifts - while true; do - case " $_FASD_SHIFT " in - *\ $1\ *) shift;; - *) break;; - esac - done - - # ignores - case " $_FASD_IGNORE " in - *\ $1\ *) return;; - esac - - shift; fasd --add "$@" # add all arguments except command - ;; - - --add|-A) shift # add entries - # stop if we don't own $_FASD_DATA or $_FASD_RO is set - [ -f "$_FASD_DATA" -a ! -O "$_FASD_DATA" ] || [ "$_FASD_RO" ] && return - - # find all valid path arguments, convert them to simplest absolute form - local paths="$(while [ "$1" ]; do - [ -e "$1" ] && printf %s\\n "$1"; shift - done | sed '/^[^/]/s@^@'"$PWD"'/@ - s@/\.\.$@/../@;s@/\(\./\)\{1,\}@/@g;:0 - s@[^/][^/]*//*\.\./@/@;t 0 - s@^/*\.\./@/@;s@//*@/@g;s@/\.\{0,1\}$@@;s@^$@/@' 2>> "$_FASD_SINK" \ - | tr '\n' '|')" - - # add current pwd if the option is set - [ "$_FASD_TRACK_PWD" = "1" -a "$PWD" != "$HOME" ] && paths="$paths|$PWD" - - [ -z "${paths##\|}" ] && return # stop if we have nothing to add - - # maintain the file - local tempfile - tempfile="$(mktemp "$_FASD_DATA".XXXXXX)" || return - $_FASD_AWK -v list="$paths" -v now="$(date +%s)" -v max="$_FASD_MAX" -F"|" ' - BEGIN { - split(list, files, "|") - for(i in files) { - path = files[i] - if(path == "") continue - paths[path] = path # array for checking - rank[path] = 1 - time[path] = now - } - } - $2 >= 1 { - if($1 in paths) { - rank[$1] = $2 + 1 / $2 - time[$1] = now - } else { - rank[$1] = $2 - time[$1] = $3 - } - count += $2 - } - END { - if(count > max) - for(i in rank) print i "|" 0.9*rank[i] "|" time[i] # aging - else - for(i in rank) print i "|" rank[i] "|" time[i] - }' "$_FASD_DATA" 2>> "$_FASD_SINK" >| "$tempfile" - if [ $? -ne 0 -a -f "$_FASD_DATA" ]; then - env rm -f "$tempfile" - else - env mv -f "$tempfile" "$_FASD_DATA" - fi - ;; - - --delete|-D) shift # delete entries - # stop if we don't own $_FASD_DATA or $_FASD_RO is set - [ -f "$_FASD_DATA" -a ! -O "$_FASD_DATA" ] || [ "$_FASD_RO" ] && return - - # turn valid arguments into entry-deleting sed commands - local sed_cmd="$(while [ "$1" ]; do printf %s\\n "$1"; shift; done | \ - sed '/^[^/]/s@^@'"$PWD"'/@;s@/\.\.$@/../@;s@/\(\./\)\{1,\}@/@g;:0 - s@[^/][^/]*//*\.\./@/@;t 0 - s@^/*\.\./@/@;s@//*@/@g;s@/\.\{0,1\}$@@ - s@^$@/@;s@\([.[\/*^$]\)@\\\1@g;s@^\(.*\)$@/^\1|/d@' 2>> "$_FASD_SINK")" - - # maintain the file - local tempfile - tempfile="$(mktemp "$_FASD_DATA".XXXXXX)" || return - - sed "$sed_cmd" "$_FASD_DATA" 2>> "$_FASD_SINK" >| "$tempfile" - - if [ $? -ne 0 -a -f "$_FASD_DATA" ]; then - env rm -f "$tempfile" - else - env mv -f "$tempfile" "$_FASD_DATA" - fi - ;; - - --query) shift # query the db, --query [$typ ["$fnd" [$mode]]] - [ -f "$_FASD_DATA" ] || return # no db yet - [ "$1" ] && local typ="$1" - [ "$2" ] && local fnd="$2" - [ "$3" ] && local mode="$3" - - # cat all backends - local each _fasd_data; for each in $_FASD_BACKENDS; do - _fasd_data="$_fasd_data -$(fasd --backend $each)" - done - [ "$_fasd_data" ] || _fasd_data="$(cat "$_FASD_DATA")" - - # set mode specific code for calculating the prior - case $mode in - rank) local prior='times[i]';; - recent) local prior='sqrt(100000/(1+t-la[i]))';; - *) local prior='times[i] * frecent(la[i])';; - esac - - if [ "$fnd" ]; then # dafault matching - local bre="$(printf %s\\n "$fnd" | sed 's/\([*\.\\\[]\)/\\\1/g - s@ @[^|]*@g;s/\$$/|/')" - bre='^[^|]*'"$bre"'[^|/]*|' - local _ret="$(printf %s\\n "$_fasd_data" | grep "$bre")" - [ "$_ret" ] && _ret="$(printf %s\\n "$_ret" | while read -r line; do - [ -${typ:-e} "${line%%\|*}" ] && printf %s\\n "$line" - done)" - if [ "$_ret" ]; then - _fasd_data="$_ret" - else # no case mathcing - _ret="$(printf %s\\n "$_fasd_data" | grep -i "$bre")" - [ "$_ret" ] && _ret="$(printf %s\\n "$_ret" | while read -r line; do - [ -${typ:-e} "${line%%\|*}" ] && printf %s\\n "$line" - done)" - if [ "$_ret" ]; then - _fasd_data="$_ret" - elif [ "${_FASD_FUZZY:-0}" -gt 0 ]; then # fuzzy matching - local fuzzy_bre="$(printf %s\\n "$fnd" | \ - sed 's/\([*\.\\\[]\)/\\\1/g;s/\$$/|/ - s@\(\\\{0,1\}[^ ]\)@\1[^|/]\\{0,'"$_FASD_FUZZY"'\\}@g - s@ @[^|]*@g')" - fuzzy_bre='^[^|]*'"$fuzzy_bre"'[^|/]*|' - _ret="$(printf %s\\n "$_fasd_data" | grep -i "$fuzzy_bre")" - [ "$_ret" ] && _ret="$(printf %s\\n "$_ret" | while read -r line; do - [ -${typ:-e} "${line%%\|*}" ] && printf %s\\n "$line" - done)" - [ "$_ret" ] && _fasd_data="$_ret" || _fasd_data= - fi - fi - else # no query arugments - _fasd_data="$(printf %s\\n "$_fasd_data" | while read -r line; do - [ -${typ:-e} "${line%%\|*}" ] && printf %s\\n "$line" - done)" - fi - - # query the database - [ "$_fasd_data" ] && printf %s\\n "$_fasd_data" | \ - $_FASD_AWK -v t="$(date +%s)" -F"|" ' - function frecent(time) { - dx = t-time - if( dx < 3600 ) return 6 - if( dx < 86400 ) return 4 - if( dx < 604800 ) return 2 - return 1 - } - { - if(!paths[$1]) { - times[$1] = $2 - la[$1] = $3 - paths[$1] = 1 - } else { - times[$1] += $2 - if($3 > la[$1]) la[$1] = $3 - } - } - END { - for(i in paths) printf "%-10s %s\n", '"$prior"', i - }' - 2>> "$_FASD_SINK" - ;; - - --backend) - case $2 in - native) cat "$_FASD_DATA";; - viminfo) - < "$_FASD_VIMINFO" sed -n '/^>/{s@~@'"$HOME"'@ - s/^..// - p - }' | $_FASD_AWK -v t="$(date +%s)" '{ - t -= 60 - print $0 "|1|" t - }' - ;; - recently-used) - local nl="$(printf '\\\nX')"; nl="${nl%X}" # slash newline for sed - tr -d '\n' < "$_FASD_RECENTLY_USED_XBEL" | \ - sed 's@file:/@'"$nl"'@g;s@count="@'"$nl"'@g' | sed '1d;s/".*$//' | \ - tr '\n' '|' | sed 's@|/@'"$nl"'@g' | $_FASD_AWK -F'|' '{ - sum = 0 - for( i=2; i<=NF; i++ ) sum += $i - print $1 "|" sum - }' - ;; - *) eval "$2";; - esac - ;; - - *) # parsing logic and processing - local fnd= last= _FASD_BACKENDS="$_FASD_BACKENDS" _fasd_data= comp= exec= - while [ "$1" ]; do case $1 in - --complete) [ "$2" = "--" ] && shift; set -- $2; local lst=1 r=r comp=1;; - --query|--add|--delete|-A|-D) fasd "$@"; return $?;; - --version) [ -z "$comp" ] && echo "1.0.1" && return;; - --) while [ "$2" ]; do shift; fnd="$fnd $1"; last="$1"; done;; - -*) local o="${1#-}"; while [ "$o" ]; do case $o in - s*) local show=1;; - l*) local lst=1;; - i*) [ -z "$comp" ] && local interactive=1 show=1;; - r*) local mode=rank;; - t*) local mode=recent;; - e*) o="${o#?}"; if [ "$o" ]; then # there are characters after "-e" - local exec="$o" # anything after "-e" - else # use the next argument - local exec="${2:?"-e: Argument needed "}" - shift - fi; break;; - b*) o="${o#?}"; if [ "$o" ]; then - _FASD_BACKENDS="$o" - else - _FASD_BACKENDS="${2:?"-b: Argument needed"}" - shift - fi; break;; - B*) o="${o#?}"; if [ "$o" ]; then - _FASD_BACKENDS="$_FASD_BACKENDS $o" - else - _FASD_BACKENDS="$_FASD_BACKENDS ${2:?"-B: Argument needed"}" - shift - fi; break;; - a*) local typ=e;; - d*) local typ=d;; - f*) local typ=f;; - R*) local r=r;; - [0-9]*) local _fasd_i="$o"; break;; - h*) [ -z "$comp" ] && echo "fasd [options] [query ...] -[f|a|s|d|z] [options] [query ...] - options: - -s list paths with scores - -l list paths without scores - -i interactive mode - -e set command to execute on the result file - -b only use backend - -B add additional backend - -a match files and directories - -d match directories only - -f match files only - -r match by rank only - -t match by recent access only - -R reverse listing order - -h show a brief help message - -[0-9] select the nth entry - -fasd [-A|-D] [paths ...] - -A add paths - -D delete paths" >&2 && return;; - esac; o="${o#?}"; done;; - *) fnd="$fnd $1"; last="$1";; - esac; shift; done - - # guess whether the last query is selected from tab completion - case $last in - /?*) if [ -z "$show$lst" -a -${typ:-e} "$last" -a "$exec" ]; then - $exec "$last" - return - fi;; - esac - - local R; [ -z "$r" ] && R=r || R= # let $R be the opposite of $r - fnd="${fnd# }" - - local res - res="$(fasd --query 2>> "$_FASD_SINK")" # query the database - [ $? -gt 0 ] && return - if [ 0 -lt ${_fasd_i:-0} ] 2>> "$_FASD_SINK"; then - res="$(printf %s\\n "$res" | sort -n${R} | \ - sed -n "$_fasd_i"'s/^[^ ]*[ ]*//p')" - elif [ "$interactive" ] || [ "$exec" -a -z "$fnd$lst$show" -a -t 1 ]; then - if [ "$(printf %s "$res" | sed -n '$=')" -gt 1 ]; then - res="$(printf %s\\n "$res" | sort -n${R})" - printf %s\\n "$res" | sed = | sed 'N;s/\n/ /' | sort -nr >&2 - printf "> " >&2 - local i; read i; [ 0 -lt "${i:-0}" ] 2>> "$_FASD_SINK" || return 1 - fi - res="$(printf %s\\n "$res" | sed -n "${i:-1}"'s/^[^ ]*[ ]*//p')" - elif [ "$lst" ]; then - [ "$res" ] && printf %s\\n "$res" | sort -n${r} | sed 's/^[^ ]*[ ]*//' - return - elif [ "$show" ]; then - [ "$res" ] && printf %s\\n "$res" | sort -n${r} - return - elif [ "$fnd" ] && [ "$exec" -o ! -t 1 ]; then # exec or subshell - res="$(printf %s\\n "$res" | sort -n | sed -n '$s/^[^ ]*[ ]*//p')" - else # no args, show - [ "$res" ] && printf %s\\n "$res" | sort -n${r} - return - fi - if [ "$res" ]; then - fasd --add "$res" - [ -z "$exec" ] && exec='printf %s\n' - $exec "$res" - fi - ;; - esac -} - -fasd --init env - -case $- in - *i*) ;; # assume being sourced, do nothing - *) # assume being executed as an executable - if [ -x "$_FASD_SHELL" -a -z "$_FASD_SET" ]; then - _FASD_SET=1 exec $_FASD_SHELL "$0" "$@" - else - fasd "$@" - fi;; -esac - diff --git a/github-init-repo b/github-init-repo index 04aac82..49d3920 100755 --- a/github-init-repo +++ b/github-init-repo @@ -1,9 +1,17 @@ #!/bin/bash + +if [[ "$1"=="" || "$2"=="" ]]; then + echo "Run as gitub-init-repo org repo" + exit 1 +fi + + ORG=$1 REPO=$2 mkdir $REPO pushd $REPO touch README.md +hub create -p $ORG/$REPO git init git add README.md git commit -m "first commit" diff --git a/gkeyring b/gkeyring deleted file mode 100755 index 8b9b8a8..0000000 --- a/gkeyring +++ /dev/null @@ -1,10 +0,0 @@ -#!/usr/bin/python -# EASY-INSTALL-ENTRY-SCRIPT: 'gkeyring==0.3','console_scripts','gkeyring' -__requires__ = 'gkeyring==0.3' -import sys -from pkg_resources import load_entry_point - -if __name__ == '__main__': - sys.exit( - load_entry_point('gkeyring==0.3', 'console_scripts', 'gkeyring')() - ) diff --git a/gmail.py b/gmail.py deleted file mode 100755 index 466b72d..0000000 --- a/gmail.py +++ /dev/null @@ -1,60 +0,0 @@ -import mechanize -import cookielib -from BeautifulSoup import BeautifulSoup -import html2text - -# Browser -br = mechanize.Browser() - -# Cookie Jar -cj = cookielib.LWPCookieJar() -br.set_cookiejar(cj) - -# Browser options -br.set_handle_equiv(True) -br.set_handle_gzip(True) -br.set_handle_redirect(True) -br.set_handle_referer(True) -br.set_handle_robots(False) - -# Follows refresh 0 but not hangs on refresh > 0 -br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1) - -# User-Agent (this is cheating, ok?) -br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')] - -# The site we will navigate into, handling it's session -br.open('http://gmail.com') - -# Select the first (index zero) form -br.select_form(nr=0) - -# User credentials -br.form['Email'] = 'captn3m0' -br.form['Passwd'] = 'bot_add_ct Shark' - -# Login -br.submit() - -# Filter all links to mail messages in the inbox -all_msg_links = [l for l in br.links(url_regex='\?v=c&th=')] -# Select the first 3 messages -for msg_link in all_msg_links[0:3]: - print msg_link - # Open each message - br.follow_link(msg_link) - html = br.response().read() - soup = BeautifulSoup(html) - # Filter html to only show the message content - msg = str(soup.findAll('div', attrs={'class': 'msg'})[0]) - # Show raw message content - print msg - # Convert html to text, easier to read but can fail if you have intl - # chars -# print html2text.html2text(msg) - print - # Go back to the Inbox - br.follow_link(text='Inbox') - -# Logout -br.follow_link(text='Sign out') diff --git a/gnome-keyring-dumper.py b/gnome-keyring-dumper.py deleted file mode 100755 index 0b78bb6..0000000 --- a/gnome-keyring-dumper.py +++ /dev/null @@ -1,27 +0,0 @@ -#! /usr/bin/env python - -# this is inspired by https://bitbucket.org/kang/python-keyring-lib/issue/151/how-is-it-possible-to-list-keyrings-keys - -import secretstorage - -def hackng(): - bus = secretstorage.dbus_init() - for keyring in secretstorage.get_all_collections(bus): - for item in keyring.get_all_items(): - attr = item.get_attributes() - if attr and 'username_value' in attr: - print('[%s] %s: %s = %s' % ( - keyring.get_label(), - item.get_label(), - attr['username_value'], - item.get_secret() - )) - else: - print('[%s] %s = %s' % ( - keyring.get_label(), - item.get_label(), - item.get_secret() - )) - -if __name__ == '__main__': - hackng() \ No newline at end of file diff --git a/niceload b/niceload deleted file mode 100755 index ba7af53..0000000 --- a/niceload +++ /dev/null @@ -1,882 +0,0 @@ -#!/usr/bin/perl -w - -# Copyright (C) 2004,2005,2006,2006,2008,2009,2010 Ole Tange, -# http://ole.tange.dk -# -# Copyright (C) 2010,2011,2012,2013,2014,2015 Ole Tange, -# http://ole.tange.dk and Free Software Foundation, Inc. -# -# This program is free software; you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation; either version 3 of the License, or -# (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, see -# or write to the Free Software Foundation, Inc., 51 Franklin St, -# Fifth Floor, Boston, MA 02110-1301 USA - -use strict; -use Getopt::Long; -$Global::progname="niceload"; -$Global::version = 20150522; -Getopt::Long::Configure("bundling","require_order"); -get_options_from_array(\@ARGV) || die_usage(); -if($opt::version) { - version(); - exit 0; -} -if($opt::help) { - help(); - exit 0; -} -if($opt::factor and $opt::suspend) { - # You cannot have --suspend and --factor - help(); - exit; -} - -if(not (defined $opt::start_io or defined $opt::run_io - or defined $opt::start_load or defined $opt::run_load - or defined $opt::start_mem or defined $opt::run_mem - or defined $opt::start_noswap or defined $opt::run_noswap - or defined $opt::io or defined $opt::load - or defined $opt::mem or defined $opt::noswap)) { - # Default is --runload=1 - $opt::run_load = 1; -} - -if(not defined $opt::start_io) { $opt::start_io = $opt::io; } -if(not defined $opt::run_io) { $opt::run_io = $opt::io; } -if(not defined $opt::start_load) { $opt::start_load = $opt::load; } -if(not defined $opt::run_load) { $opt::run_load = $opt::load; } -if(not defined $opt::start_mem) { $opt::start_mem = $opt::mem; } -if(not defined $opt::run_mem) { $opt::run_mem = $opt::mem; } -if(not defined $opt::start_noswap) { $opt::start_noswap = $opt::noswap; } -if(not defined $opt::run_noswap) { $opt::run_noswap = $opt::noswap; } - -if(defined $opt::load) { multiply_binary_prefix($opt::load); } - -my $limit = Limit->new(); -my $process = Process->new($opt::nice,@ARGV); -$::exitstatus = 0; -if(@opt::prg) { - # Find all pids of prg - my $out = `pidof -x @opt::prg`; - $process->set_pid(split /\s+/,$out); - $::resume_process = $process; - $SIG{TERM} = $SIG{INT} = \&resume; -} elsif(@opt::pid) { - $process->set_pid(@opt::pid); - $::resume_process = $process; - $SIG{TERM} = $SIG{INT} = \&resume; -} elsif (@ARGV) { - # Wait until limit is below start_limit and run_limit - while($limit->over_start_limit() - or - ($limit->hard() and $limit->over_run_limit())) { - $limit->sleep_for_recheck(); - } - $process->start(); -} - -while($process->is_alive()) { - if($limit->over_run_limit()) { - $process->suspend(); - $limit->sleep_for_recheck(); - if(not $limit->hard()) { - $process->resume(); - $limit->sleep_while_running(); - } - } else { - $process->resume(); - $limit->sleep_while_running(); - } -} - -exit($::exitstatus); - -sub resume { - $::resume_process->resume(); - exit(0); -} - -sub uniq { - # Remove duplicates and return unique values - return keys %{{ map { $_ => 1 } @_ }}; -} - -sub multiply_binary_prefix { - # Evalualte numbers with binary prefix - # k=10^3, m=10^6, g=10^9, t=10^12, p=10^15, e=10^18, z=10^21, y=10^24 - # K=2^10, M=2^20, G=2^30, T=2^40, P=2^50, E=2^70, Z=2^80, Y=2^80 - # Ki=2^10, Mi=2^20, Gi=2^30, Ti=2^40, Pi=2^50, Ei=2^70, Zi=2^80, Yi=2^80 - # ki=2^10, mi=2^20, gi=2^30, ti=2^40, pi=2^50, ei=2^70, zi=2^80, yi=2^80 - # 13G = 13*1024*1024*1024 = 13958643712 - my $s = shift; - $s =~ s/k/*1000/g; - $s =~ s/M/*1000*1000/g; - $s =~ s/G/*1000*1000*1000/g; - $s =~ s/T/*1000*1000*1000*1000/g; - $s =~ s/P/*1000*1000*1000*1000*1000/g; - $s =~ s/E/*1000*1000*1000*1000*1000*1000/g; - $s =~ s/Z/*1000*1000*1000*1000*1000*1000*1000/g; - $s =~ s/Y/*1000*1000*1000*1000*1000*1000*1000*1000/g; - $s =~ s/X/*1000*1000*1000*1000*1000*1000*1000*1000*1000/g; - - $s =~ s/Ki?/*1024/gi; - $s =~ s/Mi?/*1024*1024/gi; - $s =~ s/Gi?/*1024*1024*1024/gi; - $s =~ s/Ti?/*1024*1024*1024*1024/gi; - $s =~ s/Pi?/*1024*1024*1024*1024*1024/gi; - $s =~ s/Ei?/*1024*1024*1024*1024*1024*1024/gi; - $s =~ s/Zi?/*1024*1024*1024*1024*1024*1024*1024/gi; - $s =~ s/Yi?/*1024*1024*1024*1024*1024*1024*1024*1024/gi; - $s =~ s/Xi?/*1024*1024*1024*1024*1024*1024*1024*1024*1024/gi; - $s = eval $s; - return $s; -} - -sub get_options_from_array { - # Run GetOptions on @array - # Returns: - # true if parsing worked - # false if parsing failed - # @array is changed - my $array_ref = shift; - # A bit of shuffling of @ARGV needed as GetOptionsFromArray is not - # supported everywhere - my @save_argv; - my $this_is_ARGV = (\@::ARGV == $array_ref); - if(not $this_is_ARGV) { - @save_argv = @::ARGV; - @::ARGV = @{$array_ref}; - } - my @retval = GetOptions - ("debug|D" => \$opt::debug, - "factor|f=s" => \$opt::factor, - "hard|H" => \$opt::hard, - "soft|S" => \$opt::soft, - "sensor=s" => \$opt::sensor, - - "si|sio|startio|start-io=s" => \$opt::start_io, - "ri|rio|runio|run-io=s" => \$opt::run_io, - "io|I=s" => \$opt::io, - - "sl|startload|start-load=s" => \$opt::start_load, - "rl|runload|run-load=s" => \$opt::run_load, - "load|L|l=s" => \$opt::load, - - "sm|startmem|start-mem=s" => \$opt::start_mem, - "rm|runmem|run-mem=s" => \$opt::run_mem, - "mem|M=s" => \$opt::mem, - - "sn|startnoswap|start-noswap|start-no-swap" => \$opt::start_noswap, - "rn|runnoswap|run-noswap|run-no-swap" => \$opt::run_noswap, - "noswap|N" => \$opt::noswap, - - # niceload -l -1 --sensor 'cat /sys/class/power_supply/BAT0/status /proc/acpi/battery/BAT0/state 2>/dev/null |grep -i -q discharging; echo $?' - "battery|B" => \$opt::battery, - - "nice|n=i" => \$opt::nice, - "program|prg=s" => \@opt::prg, - "process|pid|p=s" => \@opt::pid, - "suspend|s=s" => \$opt::suspend, - "recheck|t=s" => \$opt::recheck, - "quote|q" => \$opt::quote, - "help|h" => \$opt::help, - "verbose|v" => \$opt::verbose, - "version|V" => \$opt::version, - ); - if(not $this_is_ARGV) { - @{$array_ref} = @::ARGV; - @::ARGV = @save_argv; - } - return @retval; -} - - -sub die_usage { - help(); - exit 1; -} - - -sub help { - print q{ -Usage: - niceload [-v] [-n niceness] [-L loadavg] [-I io] [-N] [-M mem] - [-s suspend_sec|-f factor] [-H] [-S] - command or -p pid -}; -} - - -sub die_bug { - my $bugid = shift; - print STDERR - ("$Global::progname: This should not happen. You have found a bug.\n", - "Please contact and include:\n", - "* The version number: $Global::version\n", - "* The bugid: $bugid\n", - "* The command line being run\n", - "* The files being read (put the files on a webserver if they are big)\n", - "\n", - "If you get the error on smaller/fewer files, please include those instead.\n"); - exit(255); -} - - -sub usleep { - # Sleep this many milliseconds. - my $secs = shift; - ::debug("Sleeping ",$secs," millisecs\n"); - select(undef, undef, undef, $secs/1000); -} - - -sub debug { - if($opt::debug) { - print STDERR @_; - } -} - - -sub my_dump { - # Returns: - # ascii expression of object if Data::Dump(er) is installed - # error code otherwise - my @dump_this = (@_); - eval "use Data::Dump qw(dump);"; - if ($@) { - # Data::Dump not installed - eval "use Data::Dumper;"; - if ($@) { - my $err = "Neither Data::Dump nor Data::Dumper is installed\n". - "Not dumping output\n"; - print STDERR $err; - return $err; - } else { - return Dumper(@dump_this); - } - } else { - eval "use Data::Dump qw(dump);"; - return (Data::Dump::dump(@dump_this)); - } -} - - -sub version { - # Returns: N/A - print join("\n", - "GNU $Global::progname $Global::version", - "Copyright (C) 2004,2005,2006,2007,2008,2009 Ole Tange", - "Copyright (C) 2010,2011 Ole Tange and Free Software Foundation, Inc.", - "License GPLv3+: GNU GPL version 3 or later ", - "This is free software: you are free to change and redistribute it.", - "GNU $Global::progname comes with no warranty.", - "", - "Web site: http://www.gnu.org/software/parallel\n" - ); -} - - -sub max { - # Returns: - # Maximum value of array - my $max; - for (@_) { - # Skip undefs - defined $_ or next; - defined $max or do { $max = $_; next; }; # Set $_ to the first non-undef - $max = ($max > $_) ? $max : $_; - } - return $max; -} - -sub min { - # Returns: - # Minimum value of array - my $min; - for (@_) { - # Skip undefs - defined $_ or next; - defined $min or do { $min = $_; next; }; # Set $_ to the first non-undef - $min = ($min < $_) ? $min : $_; - } - return $min; -} - - -package Process; - -sub new { - my $class = shift; - my $nice = shift; - my @ARGV = @_; - if($nice) { - unshift(@ARGV, "nice", "-n", $nice); - } - return bless { - 'running' => 0, # Is the process running now? - 'command' => [@ARGV], - }, ref($class) || $class; -} - -sub pgrp { - my $self = shift; - my @pgrp; - if(not $self->{'pgrp'}) { - for(@{$self->{'pids'}}) { - push @pgrp,-getpgrp($_); - } - @pgrp = ::uniq(@pgrp); - @{$self->{'pgrp'}} = @pgrp; - } - return @{$self->{'pgrp'}}; -} - -sub set_pid { - my $self = shift; - push(@{$self->{'pids'}},@_); - $self->{'running'} = 1; - $::exitstatus = 0; -} - -sub start { - # Start the program - my $self = shift; - ::debug("Starting @{$self->{'command'}}\n"); - $self->{'running'} = 1; - if($self->{'pid'} = fork) { - # set signal handler to kill children if parent is killed - push @{$self->{'pids'}}, $self->{'pid'}; - $Global::process = $self; - $SIG{CHLD} = \&REAPER; - $SIG{INT}=\&kill_child_INT; - $SIG{TSTP}=\&kill_child_TSTP; - $SIG{CONT}=\&kill_child_CONT; - sleep 1; # Give child time to setpgrp(0,0); - } else { - setpgrp(0,0); - ::debug("Child pid: $$, pgrp: ",getpgrp $$,"\n"); - ::debug("@{$self->{'command'}}\n"); - if($opt::quote) { - system(@{$self->{'command'}}); - } else { - system("@{$self->{'command'}}"); - } - $::exitstatus = $? >> 8; - $::exitsignal = $? & 127; - ::debug("Child exit $::exitstatus\n"); - exit($::exitstatus); - } -} - -use POSIX ":sys_wait_h"; -use POSIX qw(:sys_wait_h); - -sub REAPER { - my $stiff; - while (($stiff = waitpid(-1, &WNOHANG)) > 0) { - # do something with $stiff if you want - $::exitstatus = $? >> 8; - $::exitsignal = $? & 127; - } - $SIG{CHLD} = \&REAPER; # install *after* calling waitpid -} - - -sub kill_child_CONT { - my $self = $Global::process; - ::debug("SIGCONT received. Killing @{$self->{'pgrp'}}\n"); - kill CONT => $self->pgrp(); -} - - -sub kill_child_TSTP { - my $self = $Global::process; - ::debug("SIGTSTP received. Killing $self->{'pid'} and self ($$)\n"); - kill TSTP => $self->pgrp(); - kill STOP => -$$; - kill STOP => $$; -} - - -sub kill_child_INT { - my $self = $Global::process; - ::debug("SIGINT received.\n"); - if(not @opt::pid) { - ::debug("Killing $self->{'pid'} Exit\n"); - kill INT => $self->pgrp(); - } else { - ::debug("Continue pids $self->{'pid'} Exit\n"); - kill CONT => $self->pgrp(); - } - exit; -} - - -sub resume { - my $self = shift; - ::debug("Resume @{$self->{'pids'}}\n"); - if(not $self->{'running'}) { - # - = PID group - map { kill "CONT", -$_ } @{$self->{'pids'}}; - # If using -p it is not in a group - map { kill "CONT", $_ } @{$self->{'pids'}}; - $self->{'running'} = 1; - } -} - - -sub suspend { - my $self = shift; - ::debug("Suspend @{$self->{'pids'}}\n"); - if($self->{'running'}) { - # - = PID group - map { kill "STOP", -$_ } @{$self->{'pids'}}; - # If using -p it is not in a group - map { kill "STOP", $_ } @{$self->{'pids'}}; - $self->{'running'} = 0; - } -} - - -sub is_alive { - # The process is dead if none of the pids exist - my $self = shift; - my ($exists) = 0; - for my $pid (@{$self->{'pids'}}) { - if(kill 0 => $pid) { $exists++ } - } - ::debug("is_alive: $exists\n"); - return $exists; -} - - -package Limit; - -sub new { - my $class = shift; - my %limits = @_; - my $hard = $opt::soft ? 0 : $opt::hard; - my $runio = $opt::run_io ? ::multiply_binary_prefix($opt::run_io) : 0; - my $startio = $opt::start_io ? ::multiply_binary_prefix($opt::start_io) : 0; - my $runload = $opt::run_load ? ::multiply_binary_prefix($opt::run_load) : 0; - my $startload = $opt::start_load ? ::multiply_binary_prefix($opt::start_load) : 0; - my $runmem = $opt::run_mem ? ::multiply_binary_prefix($opt::run_mem) : 0; - my $startmem = $opt::start_mem ? ::multiply_binary_prefix($opt::start_mem) : 0; - my $runnoswap = $opt::run_noswap ? ::multiply_binary_prefix($opt::run_noswap) : 0; - my $startnoswap = $opt::start_noswap ? ::multiply_binary_prefix($opt::start_noswap) : 0; - my $recheck = $opt::recheck ? ::multiply_binary_prefix($opt::recheck) : 1; # Default - my $runtime = $opt::suspend ? ::multiply_binary_prefix($opt::suspend) : 1; # Default - - return bless { - 'hard' => $hard, - 'recheck' => $recheck, - 'runio' => $runio, - 'startio' => $startio, - 'runload' => $runload, - 'startload' => $startload, - 'runmem' => $runmem, - 'startmem' => $startmem, - 'runnoswap' => $runnoswap, - 'startnoswap' => $startnoswap, - 'factor' => $opt::factor || 1, - 'recheck' => $recheck, - 'runtime' => $runtime, - 'over_run_limit' => 1, - 'over_start_limit' => 1, - 'verbose' => $opt::verbose, - }, ref($class) || $class; -} - - -sub over_run_limit { - my $self = shift; - my $status = 0; - if($self->{'runmem'}) { - # mem should be between 0-10ish - # 100% available => 0 (1-1) - # 50% available => 1 (2-1) - # 10% available => 9 (10-1) - my $mem = $self->mem_status(); - ::debug("Run memory: $self->{'runmem'}/$mem\n"); - $status += (::max(1,$self->{'runmem'}/$mem)-1); - } - if($self->{'runload'}) { - # If used with other limits load should be between 0-10ish - no warnings 'numeric'; - my $load = $self->load_status(); - if($self->{'runload'} > 0) { - # Stop if the load is above the limit - $status += ::max(0,$load - $self->{'runload'}); - } else { - # Stop if the load is below the limit (for sensor) - $status += ::max(0,-$load - $self->{'runload'}); - } - } - if($self->{'runnoswap'}) { - # swap should be between 0-10ish - # swap in or swap out or no swap = 0 - # else log(swapin*swapout) - my $swap = $self->swap_status(); - $status += log(::max(1, $swap - $self->{'runnoswap'})); - } - if($self->{'runio'}) { - my $io = $self->io_status(); - $status += ::max(0,$io - $self->{'runio'}); - } - $self->{'over_run_limit'} = $status; - if(not $opt::recheck) { - $self->{'recheck'} = $self->{'factor'} * $self->{'over_run_limit'}; - } - ::debug("over_run_limit: $status\n"); - return $self->{'over_run_limit'}; -} - -sub over_start_limit { - my $self = shift; - my $status = 0; - if($self->{'startmem'}) { - # mem should be between 0-10ish - # 100% available => 0 (1-1) - # 50% available => 1 (2-1) - # 10% available => 9 (10-1) - my $mem = $self->mem_status(); - ::debug("Start memory: $self->{'startmem'}/$mem\n"); - $status += (::max(1,$self->{'startmem'}/$mem)-1); - } - if($self->{'startload'}) { - # load should be between 0-10ish - # 0 load => 0 - no warnings 'numeric'; - my $load = $self->load_status(); - if($self->{'startload'} > 0) { - # Stop if the load is above the limit - $status += ::max(0,$load - $self->{'startload'}); - } else { - # Stop if the load is below the limit (for sensor) - $status += ::max(0,-$load - $self->{'startload'}); - } - } - if($self->{'startnoswap'}) { - # swap should be between 0-10ish - # swap in or swap out or no swap = 0 - # else log(swapin*swapout) - my $swap = $self->swap_status(); - $status += log(::max(1, $swap - $self->{'startnoswap'})); - } - if($self->{'startio'}) { - my $io = $self->io_status(); - $status += ::max(0,$io - $self->{'startio'}); - } - $self->{'over_start_limit'} = $status; - if(not $opt::recheck) { - $self->{'recheck'} = $self->{'factor'} * $self->{'over_start_limit'}; - } - ::debug("over_start_limit: $status\n"); - return $self->{'over_start_limit'}; -} - - -sub hard { - my $self = shift; - return $self->{'hard'}; -} - - -sub verbose { - my $self = shift; - return $self->{'verbose'}; -} - - -sub sleep_for_recheck { - my $self = shift; - if($self->{'recheck'} < 0.5) { - # Never sleep less than 0.5 sec - $self->{'recheck'} = 0.5; - } - if($self->verbose()) { - $self->{'recheck'} = int($self->{'recheck'}*100)/100; - print STDERR "Sleeping $self->{'recheck'}s\n"; - } - ::debug("recheck in $self->{'recheck'}s\n"); - ::usleep(1000*$self->{'recheck'}); -} - - -sub sleep_while_running { - my $self = shift; - ::debug("check in $self->{'runtime'}s\n"); - if($self->verbose()) { - $self->{'runtime'} = int($self->{'runtime'}*100)/100; - print STDERR "Running $self->{'runtime'}s\n"; - } - ::usleep(1000*$self->{'runtime'}); -} - - -sub nonblockGetLines { - # An non-blocking filehandle read that returns an array of lines read - # Returns: ($eof,@lines) - # Example: --sensor 'vmstat 1 | perl -ane '\''$|=1; 4..0 and print $F[8],"\n"'\' - my ($fh,$timeout) = @_; - - $timeout = 0 unless defined $timeout; - my $rfd = ''; - $::nonblockGetLines_last{$fh} = '' - unless defined $::nonblockGetLines_last{$fh}; - - vec($rfd,fileno($fh),1) = 1; - return unless select($rfd, undef, undef, $timeout)>=0; - # I'm not sure the following is necessary? - return unless vec($rfd,fileno($fh),1); - my $buf = ''; - my $n = sysread($fh,$buf,1024*1024); - - my $eof = eof($fh); - # If we're done, make sure to send the last unfinished line - return ($eof,$::nonblockGetLines_last{$fh}) unless $n; - # Prepend the last unfinished line - $buf = $::nonblockGetLines_last{$fh}.$buf; - # And save any newly unfinished lines - $::nonblockGetLines_last{$fh} = - (substr($buf,-1) !~ /[\r\n]/ && $buf =~ s/([^\r\n]*)$//) - ? $1 : ''; - $buf ? ($eof,split(/\n/,$buf)) : ($eof); -} - -sub read_sensor { - my $self = shift; - ::debug("read_sensor"); - my $fh = $self->{'sensor_fh'}; - if(not $fh) { - # Start the sensor - open($fh, "-|", $opt::sensor) || ::die_bug("Cannot open: $opt::sensor"); - $self->{'sensor_fh'} = $fh; - } - # Read as much as we can (non_block) - my ($eof,@lines) = nonblockGetLines($fh); - - # new load = last full line - foreach my $line (@lines) { - if(defined $line) { - ::debug("Pipe saw: $eof [$line]\n"); - $Global::last_sensor_reading = $line; - } - } - if($eof) { - # End of file => Restart the sensor - close $fh; - open($fh, "-|", $opt::sensor) || ::die_bug("Cannot open: $opt::sensor"); - $self->{'sensor_fh'} = $fh; - } - - return $Global::last_sensor_reading; -} - -sub load_status { - # Returns: - # loadavg or sensor measurement - my $self = shift; - - if($opt::sensor) { - if(not defined $self->{'load_status'} or - $self->{'load_status_cache_time'} + $self->{'recheck'} < time) { - $self->{'load_status'} = $self->read_sensor(); - while (not defined $self->{'load_status'}) { - sleep 1; - $self->{'load_status'} = $self->read_sensor(); - } - $self->{'load_status_cache_time'} = time - 0.001; - } - } else { - # Normal load avg - # Cache for some seconds - if(not defined $self->{'load_status'} or - $self->{'load_status_cache_time'} + $self->{'recheck'} < time) { - $self->{'load_status'} = load_status_linux() if $^O ne 'darwin'; - $self->{'load_status'} = load_status_darwin() if $^O eq 'darwin'; - $self->{'load_status_cache_time'} = time; - } - } - ::debug("load_status: ".$self->{'load_status'}."\n"); - return $self->{'load_status'}; -} - -sub undef_as_zero { - my $a = shift; - return $a ? $a : 0; -} - - -sub load_status_linux { - my ($loadavg); - if(open(IN,"/proc/loadavg")) { - # Linux specific (but fast) - my $upString = ; - if($upString =~ m/^(\d+\.\d+)/) { - $loadavg = $1; - } else { - ::die_bug("proc_loadavg"); - } - close IN; - } elsif (open(IN,"uptime|")) { - my $upString = ; - if($upString =~ m/averages?.\s*(\d+\.\d+)/) { - $loadavg = $1; - } else { - ::die_bug("uptime"); - } - close IN; - } - return $loadavg; -} - -sub load_status_darwin { - my $loadavg = `sysctl vm.loadavg`; - if($loadavg =~ /vm\.loadavg: { ([0-9.]+) ([0-9.]+) ([0-9.]+) }/) { - $loadavg = $1; - } elsif (open(IN,"LANG=C uptime|")) { - my $upString = ; - if($upString =~ m/averages?.\s*(\d+\.\d+)/) { - $loadavg = $1; - } else { - ::die_bug("uptime"); - } - close IN; - } - return $loadavg; -} - - -sub swap_status { - # Returns: - # (swap in)*(swap out) kb - my $self = shift; - my $status; - # Cache for some seconds - if(not defined $self->{'swap_status'} or - $self->{'swap_status_cache_time'}+$self->{'recheck'} < time) { - $status = swap_status_linux() if $^O ne 'darwin'; - $status = swap_status_darwin() if $^O eq 'darwin'; - $self->{'swap_status'} = ::max($status,0); - $self->{'swap_status_cache_time'} = time; - } - ::debug("swap_status: $self->{'swap_status'}\n"); - return $self->{'swap_status'}; -} - - -sub swap_status_linux { - my $swap_activity; - $swap_activity = "vmstat 1 2 | tail -n1 | awk '{print \$7*\$8}'"; - # Run swap_activity measuring. - return qx{ $swap_activity }; -} - -sub swap_status_darwin { - # Mach Virtual Memory Statistics: (page size of 4096 bytes, cache hits 0%) - # free active spec inactive wire faults copy 0fill reactive pageins pageout - # 298987 251463 162637 69437 265724 29730558 299022 2308237 1 110058 0 - # 298991 251479 162637 69437 265726 43 4 16 0 0 0 - my ($pagesize, $pageins, $pageouts); - my @vm_stat = `vm_stat 1 | head -n4`; - $pagesize = $1 if $vm_stat[0] =~ m/page size of (\d+) bytes/; - $pageins = (split(/\s+/,$vm_stat[3]))[9]; - $pageouts = (split(/\s+/,$vm_stat[3]))[10]; - return ($pageins*$pageouts*$pagesize)/1024; -} - - -sub mem_status { - # Returns: - # number of bytes (free+cache) - my $self = shift; - # Cache for one second - if(not defined $self->{'mem_status'} or - $self->{'mem_status_cache_time'}+$self->{'recheck'} < time) { - $self->{'mem_status'} = mem_status_linux() if $^O ne 'darwin'; - $self->{'mem_status'} = mem_status_darwin() if $^O eq 'darwin'; - $self->{'mem_status_cache_time'} = time; - } - ::debug("mem_status: $self->{'mem_status'}\n"); - return $self->{'mem_status'}; -} - - -sub mem_status_linux { - # total used free shared buffers cached - # Mem: 3366496 2901664 464832 0 179228 1850692 - # -/+ buffers/cache: 871744 2494752 - # Swap: 6445476 1396860 5048616 - my @free = `free`; - my $free = (split(/\s+/,$free[2]))[3]; - return $free*1024; -} - -sub mem_status_darwin { - # Mach Virtual Memory Statistics: (page size of 4096 bytes, cache hits 0%) - # free active spec inactive wire faults copy 0fill reactive pageins pageout - # 298987 251463 162637 69437 265724 29730558 299022 2308237 1 110058 0 - # 298991 251479 162637 69437 265726 43 4 16 0 0 0 - my ($pagesize, $pages_free, $pages_speculative); - my @vm_stat = `vm_stat 1 | head -n4`; - $pagesize = $1 if $vm_stat[0] =~ m/page size of (\d+) bytes/; - $pages_free = (split(/\s+/,$vm_stat[3]))[0]; - $pages_speculative = (split(/\s+/,$vm_stat[3]))[2]; - return ($pages_free+$pages_speculative)*$pagesize; -} - - -sub io_status { - # Returns: - # max percent for all devices - my $self = shift; - # Cache for one second - if(not defined $self->{'io_status'} or - $self->{'io_status_cache_time'}+$self->{'recheck'} < time) { - $self->{'io_status'} = io_status_linux() if $^O ne 'darwin'; - $self->{'io_status'} = io_status_darwin() if $^O eq 'darwin'; - $self->{'io_status_cache_time'} = time; - } - ::debug("io_status: $self->{'io_status'}\n"); - return $self->{'io_status'}; -} - - -sub io_status_linux { - # Device: rrqm/s wrqm/s r/s w/s rkB/s wkB/s avgrq-sz avgqu-sz await r_await w_await svctm %util - # sda 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 - my @iostat_out = `LANG=C iostat -x 1 2`; - # throw away all execpt the last Device:-section - my @iostat; - for(reverse @iostat_out) { - /Device:/ and last; - push @iostat, (split(/\s+/,$_))[13]; - } - my $io = ::max(@iostat); - return undef_as_zero($io)/10; -} - -sub io_status_darwin { - # disk0 disk1 disk2 - # KB/t tps MB/s KB/t tps MB/s KB/t tps MB/s - # 14.95 15 0.22 11.18 35 0.38 2.00 0 0.00 - # 0.00 0 0.00 0.00 0 0.00 0.00 0 0.00 - my @iostat_out = `LANG=C iostat -d -w 1 -c 2`; - # return the MB/s of the last second (not the %util) - my @iostat = split(/\s+/, $iostat_out[3]); - my $io = $iostat[3] + $iostat[6] + $iostat[9]; - return ::min($io, 10); -} - -$::exitsignal = $::exitstatus = $opt::battery = 0; # Dummy diff --git a/split-audio-by-chapters b/split-audio-by-chapters index 0d3332a..e474ac9 100755 --- a/split-audio-by-chapters +++ b/split-audio-by-chapters @@ -15,7 +15,7 @@ trim() { # remove leading whitespace characters var="${var#"${var%%[![:space:]]*}"}" # remove trailing whitespace characters - var="${var%"${var##*[![:space:]]}"}" + var="${var%"${var##*[![:space:]]}"}" echo -n "$var" } @@ -26,7 +26,6 @@ if [ -f "$2" ]; then echo "Reading chapters from $2" readarray CHAPTERS < "$2" IFS=$'\n\r' - CHAPTERS_TITLES_LENGTH=${#CHAPTERS[@]} IFS=$'\n\t' else CHAPTERS_FILE_PASSED=0 @@ -37,8 +36,8 @@ ffmpeg -i "$1" 2> /tmp/ffmpeg.txt while read -r first _ _ start _ end; do unset IFS if [[ "$first" = "Chapter" ]]; then - read - read _ _ CHAPTER_TITLE + read -r + read -r _ _ CHAPTER_TITLE REAL_CHAPTER_INDEX=$((CHAPTER_INDEX+1)) CHAPTER_INDEX_PADDED=$(printf "%03d" "${REAL_CHAPTER_INDEX}") @@ -61,4 +60,4 @@ while read -r first _ _ start _ end; do ((CHAPTER_INDEX++)) fi -done