Tuesday, December 29, 2015

Infinite Scroll Any Website via Xdotool! =)

#!/bin/bash 

### Copyrighted +A.M.Danischewski (c)2015+  
### You may reuse this software without limit provided this notice 
### remain in tact. 
###
### File: scroll_me.bsh  
###  Description: This software can be used to automatically infinite 
###  scroll, a webpage on tumblr and any other infinite scroll website.
###
###  _-=  Enjoy!  _-=  

declare    PROGTITLE="${1:-Untitled}" ## Name of window (in title bar)
declare    ITERATIONS=${2:-10}        ## 10 is a bunch, change as needed
declare    SLEEP_PAGERELOAD=${3:-3}   ## Sleep time for new data to load

[[ "${1}" =~ ^- ]] && echo " Usage: ${0##*/} \"<prog title frag>\" [<itertations> [<sleep between reloads>]]" && exit 0

for a in $(eval echo {1..${ITERATIONS}}); do 
 xdotool search "${PROGTITLE}" key End
 sleep ${SLEEP_PAGERELOAD}
done 

exit 0 

Friday, December 25, 2015

Html INFO pages - using info2html

<?php
//---------------------------------------------------------
//                      routing.php
//---------------------------------------------------------
//
// PURPOSE
//  This php script routes calls to the info2html scripts, infocat and 
//  info2html for the PHP built-in webserver (like a PHP mod_rewrite). 
//
// DESCRIPTION 
// How to use: 
//  * Start the php webserver, wherever this file is found, or provide full path: 
//     $> php -S localhost:8000 -t / routing.php 
//  * Start browsing! Visit: 
//     http://localhost:8000/info2html?(coreutil)Top
// Note: Before you use this, edit the following variable to point to the 
//       info2html Perl script. 
//       Also make sure that your info share directory is listed in the 
//       info2html.conf file (mine wasn't I had to add /usr/share/info). 
//
// AUTHORS 
//    2015.12.25        +A.M.Danischewski <adam_ lastname@not gamil.com>
// 
// ORIGINAL AUTHOR
//    2015.12.25        +A.M.Danischewski <adam_ lastname@not gamil.com>
// 
// HISTORY
//    2015.12.25  V2.1  Initial version     
//                      +A.M.Danischewski <adam_ lastname@not gamil.com>
//
// Copyrighted by A.M.Danischewski 2015+ (c)
// You may reuse this code without limit, provided this notice remain in tact. 
// 
$info2html_basepath=realpath(dirname(__FILE__)); 
$page=""; 
if (preg_match('/info2html/', $_SERVER["REQUEST_URI"])) {
 if (isset($_SERVER['QUERY_STRING'])) $page=$_SERVER["QUERY_STRING"]; else print_r($_SERVER);     
  // Calls info2html, same as if info2html were called from the commmand line.
  System($info2html_basepath."/info2html \"".$page."\""); 
} else if (preg_match('/infocat/', $_SERVER["REQUEST_URI"])) {
  // Calls infocat, same as if info2html were called from the commmand line.
  System($info2html_basepath."/infocat"); 
} 
else {  
 return FALSE; 
}
?>
On Linux, with Php/Perl/firefox installed it should require no further configuration than:

Pulling the latest code:
$> git clone "https://github.com/AdamDanischewski/info2html.git"

Move the info2html directory to where you want it to live.
Review, edit, run configure.bsh.
After running configure.bsh you should find an alias file in the scripts directory,
add the alias to your .bashrc file.

Done!!

You can now run the alias i2h as follows:
$> i2h coreutils wc invocation
~ or ~ to view the whole info catalog, i2h alone
$> i2h

If you don't have git a working edited version can be found here: info2html-2.1

Tuesday, December 22, 2015

Simple Message Scheduler -- w/Zenity

#!/usr/bin/env bash 

### Copyrighted by +A.M.Danischewski  2015+ (c)
### This program may be reutilized without limits, provided this 
### notice remain intact. 

 ## Any valid date format will do  
 ##  E.g. "+ 10 minutes", "+ 2 hours", "23:00:00", "@1450829119"
declare     MSG_FMTSTRING=${1:-"20:00:00"} 
declare     MSG_SCHEDULE
declare     PROG_NAME="${0##*/}"
declare -r  SEND_MSG=${2:-"Check up on Marina"}
declare -ir SLEEP_CYCLE=2 
declare -ir ZENITY_WIDTH=400 
declare -ir ZENITY_HEIGHT=200 
declare -r  ZENITY_MSG_TITLE="Important Reminder" 

function usage() { 
 echo -en "\n Usage: ${0##*/} <date format str> <\"message\">\n" 
 echo -en "  E.g. date formats =>> \"+ 10 minutes\", \"+ 2 hours\", \"23:00:00\", \"@1450829119\"\n\n"
 exit 0  
}  

function list_sched_msgs() { 
local cmd_pid
local cmd_line
local cmd_sched
local start_time 
local end_time
while IFS= read a; do 
 cmd_pid=$(awk "{print \$1}" <<< "${a}") 
 cmd_line=$(sed "s/^.*${cmd_pid} *//" <<< "${a}" | cut -d' ' -f3-)
 cmd_sched=$(awk "{print \$4}" <<< "${a}") 
   ## If its not a normal time (20:00:00) then presume its an offset (+ 5 Seconds). 
 ! grep -Eq "@|:" <<< "${cmd_sched}" && cmd_sched=$(grep -iEo '^.*(hour[s]*|minute[s]*|second[s]*)' <<< "${cmd_line}" | tr '[[:upper:]]' '[[:lower:]]') 
 start_time=$(date -d"$(ps -o lstart= -p${cmd_pid})")
 end_time=$(date -d"${start_time} ${cmd_sched}" 2>/dev/random)
  ### If end_time had an error (for the simple "+ 1 hour" type cases, then calculate off the 
  ### start time of the process. 
 (($?)) && end_time=$(date -d"@$(($(date -d"${start_time}" +%s)+$(($(date -d"${cmd_sched}" +%s)-$(date -d"${start_time}" +%s)))))")
 printf "Sched msg: %-35.35s.. Pid:%6.6s  Ends: %-.35s\n" "${cmd_line##*/}" "${cmd_pid}" "${end_time}"  
done < <(ps -eo pid,cmd | grep "[${PROG_NAME:0:1}]${PROG_NAME:1}" | grep -v "[${PROG_NAME:0:1}]${PROG_NAME:1} -l") 
exit 0 
}

function kill_msgs() { 
 kill $(ps -eo pid,cmd | grep "[${PROG_NAME:0:1}]${PROG_NAME:1}" | grep -Ev "[${PROG_NAME:0:1}]${PROG_NAME:1} -(k|l)" | awk '{printf $1" "}')
 exit 0 
} 

function sanity_checks() {
[[ "${MSG_FMTSTRING}" =~ ^-l ]] && list_sched_msgs
[[ "${MSG_FMTSTRING}" =~ ^-k ]] && kill_msgs
[[ "${MSG_FMTSTRING}" =~ ^-	]] && usage 
MSG_SCHEDULE=$(date --date="${MSG_FMTSTRING}" +%s 2>/dev/random)
if (($?)); then 
 echo -en "\nImproperly formatted date string (${MSG_FMTSTRING}) valid strings include: \n"
 echo -en "\t\"+ 10 minutes\", \"+ 2 hours\", \"23:00:00\", \"@1450829119\"\n\n"
 exit 0 
fi 
}
   
function main() { 
sanity_checks	
while :; do 
 if (($(date +%s) > ${MSG_SCHEDULE})); then 
   paplay "/usr/share/sounds/freedesktop/stereo/complete.oga"       
   zenity --width=${ZENITY_WIDTH} --height=${ZENITY_HEIGHT} --text-info \
          --title "${ZENITY_MSG_TITLE}" <<< "${SEND_MSG}"
   break; 
 else 
   sleep ${SLEEP_CYCLE}; 
 fi 
done & ## Background our dear process.  
} 

main 
exit 0 
 
alias msg='msg_sched.bsh' 
alias lsmsgs='msg_sched.bsh -l' 
alias killmsgs='msg_sched.bsh -k' 
alias wakeups='_(){ INTERVALMIN=$((${1}*60)); MSGCNT=${2}; CURRTIME=$(($(date +%s)+${INTERVALMIN})); for a in $(eval echo {${CURRTIME}..$((${CURRTIME}+$((${INTERVALMIN}*${MSGCNT}))))..${INTERVALMIN}}); do msg_sched.bsh "@${a}" "Wake up its $(date -d"@${a}")"; done; lsmsgs; }; _' 

Friday, December 18, 2015

ELF64 NASM - Change case - simple example!

section     .text
global      _start                 ; Entry point for linker (ld)
 
  ; Linker entry point                                
_start:                                                         
    mov     rcx,len                ; Place length of message into rcx
    mov     rbp,msg                ; Place address of our msg into rbp    
    dec     rbp                    ; Adjust count to offset
    
  ; Go through the buffer and convert lowercase to uppercase characters:
upperScan:
    cmp byte [rbp+rcx],0x41        ; Test input char against uppercase 'A'                 
    jb lowerScan                   ; Not uppercase Ascii < 0x41 ('A') - jump below
    cmp byte [rbp+rcx],0x5A        ; Test input char against uppercase 'Z' 
    ja lowerScan                   ; Not uppercase Ascii > 0x5A ('Z') - jump above  
     ; At this point, we have a uppercase character
    add byte [rbp+rcx],0x20        ; Add 0x20 to get the uppercase Ascii value
    jmp Next                       ; Done, jump to next
        
lowerScan:
    cmp byte [rbp+rcx],0x61        ; Test input char against lowercase                 
    jb Next                        ; Not lowercase Ascii < 0x61 ('a') - jump below
    cmp byte [rbp+rcx],0x7A        ; Test input char against lowercase 'z'
    ja Next                        ; Not lowercase Ascii > 0x7A ('z') - jump below  
     ; At this point, we have a lowercase char
    sub byte [rbp+rcx],0x20        ; Subtract 0x20 to get the lowercase Ascii value
     ; Fall through to next        
     
Next:   
    dec rcx                        ; Decrement counter
    jnz upperScan                  ; If characters remain, loop back
        
  ; Write the buffer full of processed text to stdout:
Write:        
    mov     rbx,1                  ; File descriptor 1 (stdout)    
    mov     rax,4                  ; System call number (sys_write)
    mov     rcx,msg                ; Message to write        
    mov     rdx,len                ; Length of message to write
    int     0x80                   ; Call kernel interrupt
    mov     rax,1                  ; System call number (sys_exit)
    int     0x80                   ; Call kernel

section     .data

msg     db  'hELLO, wwwoRLD!',0xa  ; Our dear string
len     equ $ - msg                ; Length of our dear string

Quick Nasm/Assembly Tutorial One-liner! =)

alias quickasm64='_() { cd /tmp; outfile="helloworld.asm"; echo "Writing ${outfile} ..."; echo -en "section     .text\nglobal      _start                              ;must be declared for linker (ld)\n\n_start:                                         ;tell linker entry point\n\n    mov     rdx,len                             ;message length\n    mov     rcx,msg                             ;message to write\n    mov     rbx,1                               ;file descriptor (stdout)\n    mov     rax,4                               ;system call number (sys_write)\n    int     0x80                                ;call kernel\n\n    mov     rax,1                               ;system call number (sys_exit)\n    int     0x80                                ;call kernel\n\nsection     .data\n\nmsg     db  \x27Hello, world\x21\x27,0xa                 ;our dear string\nlen     equ \$ - msg                             ;length of our dear string\n\n" > "${outfile}"; echo "Compiling assembler: nasm -felf64 \"${outfile}\"..."; nasm -felf64 "${outfile}"; echo "Linking object helloworld.o: ld -melf_x86_64 -o helloworld helloworld.o ..."; ld -melf_x86_64 -o helloworld helloworld.o; echo "Displaying ${outfile} asm source: "; cat "${outfile}"; echo "Executing linked helloworld executable! ./helloworld | figlet .."; ./helloworld | figlet; file ./helloworld;}; _' 
alias quickasm='_() { cd /tmp; outfile="helloworld.asm"; echo "Writing ${outfile} ..."; echo -en "section     .text\nglobal      _start                              ;must be declared for linker (ld)\n\n_start:                                         ;tell linker entry point\n\n    mov     edx,len                             ;message length\n    mov     ecx,msg                             ;message to write\n    mov     ebx,1                               ;file descriptor (stdout)\n    mov     eax,4                               ;system call number (sys_write)\n    int     0x80                                ;call kernel\n\n    mov     eax,1                               ;system call number (sys_exit)\n    int     0x80                                ;call kernel\n\nsection     .data\n\nmsg     db  \x27Hello, world\x21\x27,0xa                 ;our dear string\nlen     equ \$ - msg                             ;length of our dear string\n\n" > "${outfile}"; echo "Compiling assembler: nasm -felf \"${outfile}\"..."; nasm -felf "${outfile}"; echo "Linking object helloworld.o: ld -melf_i386 -o helloworld helloworld.o ..."; ld -melf_i386 -o helloworld helloworld.o; echo "Displaying ${outfile} asm source: "; cat "${outfile}"; echo "Executing linked helloworld executable! ./helloworld | figlet .."; ./helloworld | figlet; file ./helloworld;}; _' 

Wednesday, December 16, 2015

Create Animated CSS HTML from Video!

#!/usr/bin/env bash
####################################################################
### Copyrighted by +AMD / Adam Michael Danischewski 2015+ 
### Free for all non-commercial uses, provided this notice remain intact.  
### File: video2css.bsh  Version: v.1.0 
### This script converts a video clip into a CSS animation! =) 
### 
### Make a sandbox directory for the video and its files, then cd to it 
### and run this script with a valid YOUTUBE url as an argument. 
### 
### Requires: avconv, youtube-dl, jp2a, firefox (if you want it to auto 
###           preview w/out failing). 
### Have fun hacking! =)  
#####################################################################

(($#<1)) || [[ "${1}" =~ ^- ]] && echo "Usage: ${0##*/} <\"http://youtube url\"|\"local video file\"> <frames> <step>" && exit 0 

declare    YOUTUBE_URL="${1}"
declare    VIDEO_FILENAME="${1}"
declare -i CSSMOVIE_MAXFRAMES=${2:-320} ## Limit on how many converted frames, its only a preview.
declare -i CSSMOVIE_STEPFRAMES=${3:-5} ## Skip every 5 frames, sensible on my mach. 
declare    CSSMOVIE_STARTTIME="" 
declare    CSSMOVIE_PATHPREFIX=""
declare    CSSMOVIE_HTML="" 
declare -i EXTRACT_DURATION=40 
declare    VIDEO_JPEG_SIZE="200x100"
declare    EXTRACT_STARTTIME="00:00:01.00"

function get_video() { 
 if [[ "${YOUTUBE_URL}" =~ ^http ]]; then 
  VIDEO_FILENAME=$(youtube-dl --get-filename "${YOUTUBE_URL}" 2>/dev/random)
  youtube-dl -f best --no-cache-dir "${YOUTUBE_URL}"
 fi  
 CSSMOVIE_PATHPREFIX="${VIDEO_FILENAME%.*}"
 CSSMOVIE_HTML="${CSSMOVIE_PATHPREFIX}.html" 
} 

function extract_jpegs() { 
 avconv -i "${VIDEO_FILENAME}" -s "${VIDEO_JPEG_SIZE}" -t ${EXTRACT_DURATION} -ss "${EXTRACT_STARTTIME}" "${CSSMOVIE_PATHPREFIX}-%d.jpeg"
} 

function jpeg2css() { 
 local outname=""; 
 for a in "${CSSMOVIE_PATHPREFIX}"*.jpeg; do 
  outname="${a%%.*}" 
  outname="${outname}.html" 
  jp2a --colors --chars="  " --fill --html-fontsize=4 --html-raw "$a" > "${outname}" 
 done 
} 

function print_html_array() { 
 local -i i=1;
 local fcontents=""; 
 while ((${i} < ${CSSMOVIE_MAXFRAMES})); do 
  fcontents=$(< "${CSSMOVIE_PATHPREFIX}-${i}.html")
  echo "imgArr.push(\"${fcontents}\");"
  i+=${CSSMOVIE_STEPFRAMES}
 done
}

function print_html_file() { 
cat<<EOF 
<html>
<body>
<div id="cssMovie"></div>
<script>
var imgArr = new Array($((${CSSMOVIE_MAXFRAMES}/${CSSMOVIE_STEPFRAMES}))); 
EOF
print_html_array
cat <<EOF 
var loopTimer;
function frameLooper() {
 if(imgArr.length > 0) {
  document.getElementById("cssMovie").innerHTML = imgArr.shift(); 
 } else {
  clearTimeout(loopTimer); 
    return false;
 }
 loopTimer = setTimeout('frameLooper()',10);
}
frameLooper();
</script>
</body>
</html>
EOF
}

get_video
extract_jpegs
jpeg2css
print_html_file > "${CSSMOVIE_HTML}" 
firefox "${CSSMOVIE_HTML}"
exit 0 

Friday, December 11, 2015

Get Pid of a Process Backgrounded within a Subshell

You can use the ppid of the parent by echoing out the BASHPID of the parent when you first enter
the shell,then you background the process and can look up the pid via ppid using the parent pid. E.g. To get the pid of a sleep 555 command backgrounded within a subshell: (echo "$BASHPID" > /tmp/_tmp_pid_ && sleep 555 &) && ps -ho pid --ppid=$(< /tmp/_tmp_pid_)

Move X Window by Pid

 ## Arg 1 - Pid of window to move.
 ## Arg 2 - X-Coord.
 ## Arg 3 - Y-Coord. 
function move_win() { 
 xdotool windowmove $(wmctrl -lp | grep ${1} | cut -d' ' -f1) ${2} ${3}
} 

E.g. $> move_win $(pidof zenity) 0 0 

Tuesday, December 8, 2015

Find out when a sleep command will exit

alias endofsleep='_() { while IFS= read a; do cmd_pid=$(awk "{print \$1}" <<< "${a}"); cmd_line=$(sed "s/^${cmd_pid} *//" <<< "${a}"); echo "Command:${cmd_line}, Pid:${cmd_pid}, Ends:$(date -d "@$(($(date -d"$(ps -o lstart= -p${cmd_pid})" +%s)+${1}))")"; done< <(ps -eo pid,cmd | grep "[s]leep ${1}$"); }; _' 

Monday, December 7, 2015

URL Scraping/Extraction w/Sed

alias lsurls='_(){ sed "s/http/\nhttp/g" "${1}" | sed -n "s/\(^http[s]*:[a-Z0-9/.?=_-]*\)\(.*\)/\1/p"; }; _' 
E.g. lsurls <(curl http://www.cnn.com)

Friday, December 4, 2015

Ls symbolically linked directories - w/find

alias lslnd='find . -printf "%l\0" | xargs -0 -I {} bash -c "[[ -d \"{}\" ]] && echo \"{}\""' 

Wednesday, December 2, 2015

Execute arbitrary lines in files

alias execln='_() { if (($#<2)) || [[ ! $1 =~ p ]]; then echo "Usage: execln <sed line range [e.g. 1p or \"1p;3p;2p;4,5p\"]> <file>"; else eval "$(sed -n "${1}" "${2}")"; fi; }; _' 

Tuesday, December 1, 2015

Mpd Song Report Daemon w/Notify-Send - Simple!

alias songd='while :; do notify-send --urgency=low -i "audio-headphones" "$(mpc current --wait)"; done &'