You are not logged in.

#1201 2010-07-28 04:50:57

diegonc
Member
Registered: 2008-12-13
Posts: 42

Re: Post your handy self made command line utilities

ggarm wrote:
Bushman wrote:

Here's a .bashrc/.zshrc function I wrote, similar to the makescript function, but used for quickly compiling single-file source code.
(...)

Hey

I believe you can achieve the same result by just doing:
    make foo.c
    make foo.cpp
    etc...

Yes, default rules work without a makefile smile

I recently added this to my bash_profile:

clean_history()
{
        set -- "$1" "`mktemp`"
        { awk '{ print NR "\t" $0; }' \
                | sort -uk 2  \
                | sort -n -k 1,1 \
                | cut -f2-
        } < "$1" > "$2"
        mv "$2" "$1"
}

clean_history "${HISTFILE:-~/.bash_history}"

it removes duplicates preserving the usual temporal order.

Offline

#1202 2010-07-28 12:46:23

steve___
Member
Registered: 2008-02-24
Posts: 452

Re: Post your handy self made command line utilities

@diegonc
I use this in .bashrc

export HISTCONTROL=ignoredups
alias h='history | grep'

Last edited by steve___ (2010-07-28 12:46:53)

Offline

#1203 2010-07-28 20:03:00

markp1989
Member
Registered: 2008-10-05
Posts: 431

Re: Post your handy self made command line utilities

just made a few changes to the virt-viewer script.  now it makes each vm on its own web page, and an index page with links to all of them.

when i had them all on the same page, i would get ssh password prompts for each vm, and it was annoying me

##user set variables. 
server=192.168.1.x
user=username

##counts the ammout of virtual machines, and cleans up the out put abit 
quantity=$(virsh list --all | cut -c5-20 | grep -vE 'clone|srv' | wc -l )
cutno=$(( $quantity - 2 ))

##cleans up the files from last runs to avoid getting any duplicates 
rm /var/www/virtview/*.html

##makes the top part of the html page 
echo "<html><body><h1>Virtual machines viewer!</h1></br>select the name of the virtual machine to view</br></br>" >> /var/www/virtview/index.html

##make a new .html file for each virtual machine, and creates a link in the index.html. 
    for i in $(virsh list --all |  cut -c5-20 | grep -vE 'clone|srv' | tail -n $cutno)

    do

        echo "<a href="$i.html">$i</a></br>" >> /var/www/virtview/index.html

        echo "$i:</br><embed type="application/x-virt-viewer"
        width="800"
        height="600"
        uri="qemu+ssh://$user@$server/system" name="$i">
        </embed> </br><br><a href="index.html">back</a></br>" >> /var/www/virtview/$i.html


    done

##Ends the html file. 
echo "</body></html>" >> /var/www/virtview/index.html

http://marko1989.no-ip.org/pics/screens … enshot.jpg

http://marko1989.no-ip.org/pics/screens … shot-1.jpg

Last edited by markp1989 (2010-08-03 13:46:19)


Desktop: E8400@4ghz - DFI Lanparty JR P45-T2RS - 4gb ddr2 800 - 30gb OCZ Vertex - Geforce 8800 GTS - 2*19" LCD
Server/Media Zotac GeForce 9300-ITX I-E - E5200 - 4gb Ram - 2* ecogreen F2 1.5tb - 1* wd green 500gb - PicoPSU 150xt - rtorrent - xbmc - ipazzport remote - 42" LCD

Offline

#1204 2010-07-30 16:02:29

Stebalien
Member
Registered: 2010-04-27
Posts: 1,237
Website

Re: Post your handy self made command line utilities

This script will ssh to a server with the same name as the script and start/attach to tmux on the server. You can also pass commands to the server by defining them in the case switch.

#!/bin/bash

srv="$(basename $0)"
cmd="$1"

do_cmd() {
    exec ssh -t $srv "{ tmux has-session && tmux new-window -n \"$1\" \"$2\"; } || tmux new-session -d -s $srv -n \"$1\" \"$2\"; tmux attach-session"
}
case $1 in 
    u|uu|update)
        do_cmd 'Update' 'pacman -Syu'
        ;;
    r|reboot|restart)
        do_cmd 'Reboot' 'shutdown -r now'
        ;;
    t|top)
        do_cmd 'Top' 'top'
        ;;
    *)
        exec ssh -t $srv "tmux attach || tmux new-session -n Shell -s $srv"
        ;;
esac
echo "Usage: $0 [command]"

Steven [ web : git ]
GPG:  327B 20CE 21EA 68CF A7748675 7C92 3221 5899 410C
Do not email: honeypot@stebalien.com

Offline

#1205 2010-07-30 17:47:49

markp1989
Member
Registered: 2008-10-05
Posts: 431

Re: Post your handy self made command line utilities

just made this quick script.

i store my esniper item files in a folder called esniper

all this does it run an instant of esniper in a detached screen for each file in the esniper folder.

#!/bin/bash

screen -ls > esniper.tmp

for item in /home/mark/esniper/*; do
  i=${item##*/}

        if grep -qw "esniper-$i" esniper.tmp; then
                echo esniper is already running for $i
        else
                echo starting esniper screen session for $i 
                /usr/bin/screen -mSd esniper-$i /usr/bin/esniper /home/mark/esniper/$i

        fi 
done

i set this to run every boot with cron, so that if for any reason my computer has to reboot then esniper will run again.

@reboot ~/scripts/esniperstart.sh


its only small, but it does what i need it to.

edit: just threw in a quick if statement to make sure that it only runs 1 version of esniper per item file.

Last edited by markp1989 (2010-07-30 22:29:11)


Desktop: E8400@4ghz - DFI Lanparty JR P45-T2RS - 4gb ddr2 800 - 30gb OCZ Vertex - Geforce 8800 GTS - 2*19" LCD
Server/Media Zotac GeForce 9300-ITX I-E - E5200 - 4gb Ram - 2* ecogreen F2 1.5tb - 1* wd green 500gb - PicoPSU 150xt - rtorrent - xbmc - ipazzport remote - 42" LCD

Offline

#1206 2010-07-30 18:14:35

falconindy
Developer
From: New York, USA
Registered: 2009-10-22
Posts: 4,111
Website

Re: Post your handy self made command line utilities

markp1989 wrote:

just made this quick script.
-snip-

Please don't iterate over the output of ls.

for item in /home/mark/esniper/*; do
  i=${item##*/}
  ...
done

Offline

#1207 2010-07-30 18:45:51

markp1989
Member
Registered: 2008-10-05
Posts: 431

Re: Post your handy self made command line utilities

falconindy wrote:
markp1989 wrote:

just made this quick script.
-snip-

Please don't iterate over the output of ls.

for item in /home/mark/esniper/*; do
  i=${item##*/}
  ...
done

thanks for the tip, would you be able to tell me whats wrong with using the out put of ls?

thanks, mark


Desktop: E8400@4ghz - DFI Lanparty JR P45-T2RS - 4gb ddr2 800 - 30gb OCZ Vertex - Geforce 8800 GTS - 2*19" LCD
Server/Media Zotac GeForce 9300-ITX I-E - E5200 - 4gb Ram - 2* ecogreen F2 1.5tb - 1* wd green 500gb - PicoPSU 150xt - rtorrent - xbmc - ipazzport remote - 42" LCD

Offline

#1208 2010-07-30 18:53:16

Wintervenom
Member
Registered: 2008-08-20
Posts: 1,011

Re: Post your handy self made command line utilities

markp1989 wrote:

[...] tell me whats wrong with using the out put of ls? [...]

See [here].

Offline

#1209 2010-07-30 21:53:22

diegonc
Member
Registered: 2008-12-13
Posts: 42

Re: Post your handy self made command line utilities

for item in /home/mark/esniper/*; do
  i=${item##*/}
  ...
done

And this way is impossible to distinguish a failed expansion from an esniper directory with only one file called '*'.Scratch that, shells have options tongue Just be aware of what happens when expansion fails.  big_smile

@steve___: I think ignoredups works on consecutive duplicate entries only. i.e: in the following sequence both ls get recorded.

$ ls
$ true
$ ls

Offline

#1210 2010-07-31 20:03:16

markp1989
Member
Registered: 2008-10-05
Posts: 431

Re: Post your handy self made command line utilities

Wintervenom wrote:
markp1989 wrote:

[...] tell me whats wrong with using the out put of ls? [...]

See [here].

thanks, that link has alot of good info in it smile


Desktop: E8400@4ghz - DFI Lanparty JR P45-T2RS - 4gb ddr2 800 - 30gb OCZ Vertex - Geforce 8800 GTS - 2*19" LCD
Server/Media Zotac GeForce 9300-ITX I-E - E5200 - 4gb Ram - 2* ecogreen F2 1.5tb - 1* wd green 500gb - PicoPSU 150xt - rtorrent - xbmc - ipazzport remote - 42" LCD

Offline

#1211 2010-08-01 02:27:31

steve___
Member
Registered: 2008-02-24
Posts: 452

Re: Post your handy self made command line utilities

@diegonc - yeah.  I was just tossing out there what I use.  Your solution is more exact.

Offline

#1212 2010-08-05 10:00:25

supulton
Member
Registered: 2008-12-31
Posts: 58

Re: Post your handy self made command line utilities

here's a slightly updated version of my alarm script i posted earlier.

#!/bin/bash
# wakethehellup.sh

# amount of time between snoozes in minutes 
ztime=10

# load playlist, set mpd volume up
mpc -q clear; mpc load alarm; mpc -q shuffle
mpcvol=$1; mpc -q volume ${mpcvol:-80}

# monitor
export DISPLAY=:0.0
xset dpms force on

# gxmessage alarm
alarm_message() {
gxmessage -center \
    -buttons "Stop":1,"Snooze":2 \
    -geometry 400x80 \
    -title "Alarm" \
    'Get up for school ya lazy bum!'    
    action=$?
}

# set volume to low, gradually increase
volume() {
    vol=1
    maxvol=75
    amixer -q sset PCM ${vol}%
    mpc play
    while (( $vol < $maxvol )); do
        amixer -q sset PCM ${vol}%
        (( vol++ ))
        sleep 1
    done
}

# snooze or stop?
volume &
VPID=$!

alarm_message
while [[ $action != 1 ]]
do
    if [[ $action = 2 ]] ;then
        kill $VPID
        mpc -q pause
        sleep 2; xset dpms force standby
        sleep "$ztime"
        xset dpms force on
        volume &
        VPID=$!
    fi
    alarm_message
done

kill $VPID
mpc -q stop

needed: mpc + gxmessage.

the script will load an alarm from mpc playlist 'alarm' , turn on your monitor, and raise your volume slowly from 1 to 75%; gxmessage will pop up and ask if you want to stop it or snooze for 10 minutes. it's handy for me. smile

ps. if you want to use it in your crontab, export your display like this:

00 5 * * 1-5 export DISPLAY=:0.0 && sh /home/vic/bin/wakethehellup.sh

Offline

#1213 2010-08-05 12:29:14

markp1989
Member
Registered: 2008-10-05
Posts: 431

Re: Post your handy self made command line utilities

supulton wrote:

here's a slightly updated version of my alarm script i posted earlier.

#!/bin/bash
# wakethehellup.sh

# amount of time between snoozes in minutes 
ztime=10

# load playlist, set mpd volume up
mpc -q clear; mpc load alarm; mpc -q shuffle
mpcvol=$1; mpc -q volume ${mpcvol:-80}

# monitor
export DISPLAY=:0.0
xset dpms force on

# gxmessage alarm
alarm_message() {
gxmessage -center \
    -buttons "Stop":1,"Snooze":2 \
    -geometry 400x80 \
    -title "Alarm" \
    'Get up for school ya lazy bum!'    
    action=$?
}

# set volume to low, gradually increase
volume() {
    vol=1
    maxvol=75
    amixer -q sset PCM ${vol}%
    mpc play
    while (( $vol < $maxvol )); do
        amixer -q sset PCM ${vol}%
        (( vol++ ))
        sleep 1
    done
}

# snooze or stop?
volume &
VPID=$!

alarm_message
while [[ $action != 1 ]]
do
    if [[ $action = 2 ]] ;then
        kill $VPID
        mpc -q pause
        sleep 2; xset dpms force standby
        sleep "$ztime"
        xset dpms force on
        volume &
        VPID=$!
    fi
    alarm_message
done

kill $VPID
mpc -q stop

needed: mpc + gxmessage.

the script will load an alarm from mpc playlist 'alarm' , turn on your monitor, and raise your volume slowly from 1 to 75%; gxmessage will pop up and ask if you want to stop it or snooze for 10 minutes. it's handy for me. smile

ps. if you want to use it in your crontab, export your display like this:

00 5 * * 1-5 export DISPLAY=:0.0 && sh /home/vic/bin/wakethehellup.sh

thats cool, im gona use this as soon as my htpc is back up


Desktop: E8400@4ghz - DFI Lanparty JR P45-T2RS - 4gb ddr2 800 - 30gb OCZ Vertex - Geforce 8800 GTS - 2*19" LCD
Server/Media Zotac GeForce 9300-ITX I-E - E5200 - 4gb Ram - 2* ecogreen F2 1.5tb - 1* wd green 500gb - PicoPSU 150xt - rtorrent - xbmc - ipazzport remote - 42" LCD

Offline

#1214 2010-08-08 01:18:02

lilsirecho
Veteran
Registered: 2003-10-24
Posts: 5,000

Re: Post your handy self made command line utilities

When using jumanji in kde4, the following autostart text performs like a charm at boot when entered into kde4 program autostart mode.........

jumanji url1 url2 url3 url4 url5url6 url7 url8 url9 url10......

Each url is the name of the url such as, google.com..archlinux.org......

Entire group of ten are accessed via tab commands after download ceases at desktop.

All selections appear in a window which can be full screen.  Tabs are numbered at the top of the window and do not use much space.


Prediction...This year will be a very odd year!
Hard work does not kill people but why risk it: Charlie Mccarthy
A man is not complete until he is married..then..he is finished.
When ALL is lost, what can be found? Even bytes get lonely for a little bit!     X-ray confirms Iam spineless!

Offline

#1215 2010-08-08 02:25:32

supulton
Member
Registered: 2008-12-31
Posts: 58

Re: Post your handy self made command line utilities

markp1989 wrote:
supulton wrote:

here's a slightly updated version of my alarm script i posted earlier.

#!/bin/bash
# wakethehellup.sh

# amount of time between snoozes in minutes 
ztime=10

# load playlist, set mpd volume up
mpc -q clear; mpc load alarm; mpc -q shuffle
mpcvol=$1; mpc -q volume ${mpcvol:-80}

# monitor
export DISPLAY=:0.0
xset dpms force on

# gxmessage alarm
alarm_message() {
gxmessage -center \
    -buttons "Stop":1,"Snooze":2 \
    -geometry 400x80 \
    -title "Alarm" \
    'Get up for school ya lazy bum!'    
    action=$?
}

# set volume to low, gradually increase
volume() {
    vol=1
    maxvol=75
    amixer -q sset PCM ${vol}%
    mpc play
    while (( $vol < $maxvol )); do
        amixer -q sset PCM ${vol}%
        (( vol++ ))
        sleep 1
    done
}

# snooze or stop?
volume &
VPID=$!

alarm_message
while [[ $action != 1 ]]
do
    if [[ $action = 2 ]] ;then
        kill $VPID
        mpc -q pause
        sleep 2; xset dpms force standby
        sleep "$ztime"
        xset dpms force on
        volume &
        VPID=$!
    fi
    alarm_message
done

kill $VPID
mpc -q stop

needed: mpc + gxmessage.

the script will load an alarm from mpc playlist 'alarm' , turn on your monitor, and raise your volume slowly from 1 to 75%; gxmessage will pop up and ask if you want to stop it or snooze for 10 minutes. it's handy for me. smile

ps. if you want to use it in your crontab, export your display like this:

00 5 * * 1-5 export DISPLAY=:0.0 && sh /home/vic/bin/wakethehellup.sh

thats cool, im gona use this as soon as my htpc is back up

hope you like it. i've updated it to allow people to pass some options. just use '--help' to see.

#!/bin/bash
# wakethehellup.sh

usage() {
    echo "Usage: $0 [option] [argument]"
    echo
    echo 'Options:'
    echo '  --snooze, -z    - amount of time between snoozes'
    echo '  --control, -c   - set ALSA mixer control'
    echo '  --playlist, -p  - set name of mpc playlist to use'
    echo '  --message, -m   - set the message to display'
    echo '  --minvol, -a    - set the volume to start at'
    echo '  --maxvol, -b    - set the volume to move up to'
    echo '  --mpcvol, -v    - set the volume of mpc'
    echo '  --help, -h      - display this help message'
    exit 1
}

#if [[ $# -eq 0 ]]; then
#    echo "No arguments supplied"
#    usage
#fi

while [[ $# -gt 0 ]]; do
    case "$1" in
        --snooze|-z)
            ztime=$2
            shift
            ;;
        --control|-c)
            control=$2
            shift
            ;;
        --playlist|-p)
            playlist=$2
            shift
            ;;
        --message|-m)
            msg=$2
            shift
            ;;
        --minvol|-a)
            vol=$2
            shift
            ;;
        --maxvol|-b)
            maxvol=$2
            shift
            ;;
        --mpcvol|-v)
            mpcvol=$2
            shift
            ;;
        --help|-h)
            usage
            ;;
        *)
            echo "Unknown argument: $1"
            usage
            ;;
    esac
    shift
done

# load playlist, set mpd volume up
mpc -q clear
mpc load ${playlist:=alarm}; mpc -q shuffle
mpc -q volume ${mpcvol:=80}

# monitor
export DISPLAY=:0.0
xset dpms force on

# gxmessage alarm
alarm_message() {
gxmessage -center \
    -buttons "Stop":1,"Snooze":2 \
    -geometry 400x80 \
    -title "Alarm" \
    ${msg:='Wake up, ya lazy bum!'}
    action=$?
}

# set volume to low, gradually increase
volume() {
    amixer -q sset ${control:=PCM} ${vol}%
    mpc play
    while (( ${vol:=1} < ${maxvol:=80} )); do
        amixer -q sset ${control:=PCM} ${vol}%
        (( vol++ ))
        sleep 1
    done
}

# snooze or stop?
volume &
VPID=$!

alarm_message
while [[ $action != 1 ]]
do
    if [[ $action = 2 ]] ;then
        kill $VPID
        mpc -q pause
        sleep 2; xset dpms force standby
        sleep "${ztime:=10}"m
        xset dpms force on
        volume &
        VPID=$!
    fi
    alarm_message
done

kill $VPID
mpc -q stop

Offline

#1216 2010-08-08 18:33:30

GraveyardPC
Member
Registered: 2008-11-29
Posts: 99

Re: Post your handy self made command line utilities

I thought it would be a neat idea to create a wallpaper sized pixel maze. Except after spending twenty minutes doing a 100x100 size block, I figured I needed something faster. So here's a simple maze generator using Depth-First Search and Python Image Library.

#!/usr/bin/python
# Maze Generator (pymaze)

import argparse
from PIL import Image
from random import randrange as rand

def mazeDFS(width,height):
    '''
        Maze Generator
        Depth-First Search Algorithm
    '''
    stack    = []
    grid    = [[x%2*y%2 for x in range(width)] for y in range(height)]
    total    = ((width-1)/2)*((height-1)/2)
    cy    = rand(1,height,2)
    cx    = rand(1,width,2)
    visited    = 1

    while visited<total:
        possible= [[y,x] for y,x in [[cy-2,cx],[cy,cx+2],[cy+2,cx],[cy,cx-2]]
              if y>0 and x>0 and y<height-1 and x<width-1]
    
        neighbor= [[y,x] for y,x in possible
              if grid[y-1][x]!=2 and grid[y+1][x]!=2 and
                 grid[y][x-1]!=2 and grid[y][x+1]!=2]

        if len(neighbor)>0:
            ny,nx    = neighbor[rand(0,len(neighbor))]
            wy    = ny if nx!=cx else (ny-1 if ny>cy else cy-1)
            wx    = nx if ny!=cy else (nx-1 if nx>cx else cx-1)

            grid[wy][wx] = 2
            stack.append([cy,cx])
            cy = ny; cx = nx
            visited+=1
        else:
            cy,cx = stack.pop()

    grid[0][1] = 1
    grid[height-1][width-2]    = 1
    return grid

def makeMaze(w,h,scale,fore,back,filename):
    w,h    = int(w/scale),int(h/scale)
    width    = w if w%2 else w-1
    height    = h if h%2 else h-1

    if width<3 or height<3:
        print "Error: Width/Height too small given scale."
        return

    grid    = mazeDFS(width,height)
    im    = Image.new("RGB",(width,height))
    data    = [back if grid[y][x] else fore
           for y in range(height) for x in range(width)]

    im.putdata(data,1.0,0.0)
    im.resize((width*scale,height*scale)).save(filename,"PNG")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(
         prog="pymaze",
         description="Depth-First Search Maze Generator.",
         formatter_class=argparse.ArgumentDefaultsHelpFormatter)

    parser.add_argument("--width",type=int,default=300,
                help="set maze width in pixels")
    parser.add_argument("--height",type=int,default=300,
                help="set maze height in pixels")
    parser.add_argument("--scale",type=int,default=4,
                help="set cell/wall scale in pixels")
    parser.add_argument("-fc","--fore",type=int,
                nargs=3,default=[0,0,0],
                help="foreground color in RGB")
    parser.add_argument("-bc","--back",type=int,
                nargs=3,default=[255,255,255],
                help="background color in RGB")
    parser.add_argument("filename",
                help="save as <filename> (ie. \"maze.png\")")

    m = parser.parse_args()
    makeMaze(m.width,m.height,m.scale,tuple(m.fore),tuple(m.back),m.filename)

maze_300x300.png

Edit, maze avatar:
./pymaze --width 80 --height 80 --scale 4 --fore 87 102 122 --back 245 249 252 maze.png

Last edited by GraveyardPC (2010-08-08 20:41:51)

Offline

#1217 2010-08-08 23:35:19

markp1989
Member
Registered: 2008-10-05
Posts: 431

Re: Post your handy self made command line utilities

GraveyardPC wrote:

I thought it would be a neat idea to create a wallpaper sized pixel maze. Except after spending twenty minutes doing a 100x100 size block, I figured I needed something faster. So here's a simple maze generator using Depth-First Search and Python Image Library.

#!/usr/bin/python
# Maze Generator (pymaze)

import argparse
from PIL import Image
from random import randrange as rand

def mazeDFS(width,height):
    '''
        Maze Generator
        Depth-First Search Algorithm
    '''
    stack    = []
    grid    = [[x%2*y%2 for x in range(width)] for y in range(height)]
    total    = ((width-1)/2)*((height-1)/2)
    cy    = rand(1,height,2)
    cx    = rand(1,width,2)
    visited    = 1

    while visited<total:
        possible= [[y,x] for y,x in [[cy-2,cx],[cy,cx+2],[cy+2,cx],[cy,cx-2]]
              if y>0 and x>0 and y<height-1 and x<width-1]
    
        neighbor= [[y,x] for y,x in possible
              if grid[y-1][x]!=2 and grid[y+1][x]!=2 and
                 grid[y][x-1]!=2 and grid[y][x+1]!=2]

        if len(neighbor)>0:
            ny,nx    = neighbor[rand(0,len(neighbor))]
            wy    = ny if nx!=cx else (ny-1 if ny>cy else cy-1)
            wx    = nx if ny!=cy else (nx-1 if nx>cx else cx-1)

            grid[wy][wx] = 2
            stack.append([cy,cx])
            cy = ny; cx = nx
            visited+=1
        else:
            cy,cx = stack.pop()

    grid[0][1] = 1
    grid[height-1][width-2]    = 1
    return grid

def makeMaze(w,h,scale,fore,back,filename):
    w,h    = int(w/scale),int(h/scale)
    width    = w if w%2 else w-1
    height    = h if h%2 else h-1

    if width<3 or height<3:
        print "Error: Width/Height too small given scale."
        return

    grid    = mazeDFS(width,height)
    im    = Image.new("RGB",(width,height))
    data    = [back if grid[y][x] else fore
           for y in range(height) for x in range(width)]

    im.putdata(data,1.0,0.0)
    im.resize((width*scale,height*scale)).save(filename,"PNG")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(
         prog="pymaze",
         description="Depth-First Search Maze Generator.",
         formatter_class=argparse.ArgumentDefaultsHelpFormatter)

    parser.add_argument("--width",type=int,default=300,
                help="set maze width in pixels")
    parser.add_argument("--height",type=int,default=300,
                help="set maze height in pixels")
    parser.add_argument("--scale",type=int,default=4,
                help="set cell/wall scale in pixels")
    parser.add_argument("-fc","--fore",type=int,
                nargs=3,default=[0,0,0],
                help="foreground color in RGB")
    parser.add_argument("-bc","--back",type=int,
                nargs=3,default=[255,255,255],
                help="background color in RGB")
    parser.add_argument("filename",
                help="save as <filename> (ie. \"maze.png\")")

    m = parser.parse_args()
    makeMaze(m.width,m.height,m.scale,tuple(m.fore),tuple(m.back),m.filename)

http://dl.dropbox.com/u/519931/maze_300x300.png

Edit, maze avatar:
./pymaze --width 80 --height 80 --scale 4 --fore 87 102 122 --back 245 249 252 maze.png

what python libs are required for this?

im getting this mesage. ImportError: No module named argparse

thx, mark


Desktop: E8400@4ghz - DFI Lanparty JR P45-T2RS - 4gb ddr2 800 - 30gb OCZ Vertex - Geforce 8800 GTS - 2*19" LCD
Server/Media Zotac GeForce 9300-ITX I-E - E5200 - 4gb Ram - 2* ecogreen F2 1.5tb - 1* wd green 500gb - PicoPSU 150xt - rtorrent - xbmc - ipazzport remote - 42" LCD

Offline

#1218 2010-08-08 23:39:30

GraveyardPC
Member
Registered: 2008-11-29
Posts: 99

Re: Post your handy self made command line utilities

markp1989 wrote:

what python libs are required for this?

im getting this mesage. ImportError: No module named argparse

thx, mark

Oh yeah, sorry. You're gonna need argparse from AUR and "python-imaging" from the extra repo. I decided to start using newer libraries for this sort of stuff.

Last edited by GraveyardPC (2010-08-08 23:43:12)

Offline

#1219 2010-08-09 00:46:33

simongmzlj
Member
From: Canada
Registered: 2008-11-06
Posts: 135

Re: Post your handy self made command line utilities

This is a massive hack, but this allows me to watch south park episode from www.allsp.com from mplayer.

#!/usr/bin/env ruby

require 'net/http'
require 'uri'

TempFile = '/tmp/allsp.flv'
Episodes = [13, 18, 17, 17, 14, 17, 15, 14, 14, 14, 14, 14, 14, 14, 14]

def decode(season, episode)
  code = 0
  if season > 1 then
    code += Episodes[0..season - 2].inject(nil) { |sum,x| sum ? sum+x : x }
  end
  if episode > Episodes[season - 1] then
    episode = Episodes[season - 1]
  end
  code += episode
end

def sniff_video(episode)
  print "looking for video file...\n"
  url = URI.parse('http://www.allsp.com')
  begin
    Net::HTTP.start(url.host, url.port) { |http|
      resp = http.get("/xml.php?id=#{episode}")
      video = resp.body[/<location>([^<]*)</, 1]
      download_video(video)
    }
  rescue Interrupt
    exit 1
  end
end

def download_video(video)
  print "downloading episode to #{TempFile}\n"
  url = URI.parse(video)
  begin
    Net::HTTP.start(url.host, url.port) { |http|
      File.open(TempFile, "wb") { |file|
        fork { exec "sleep 1 && mplayer -fs #{TempFile}" }
        http.get(url.path + '?' + url.query) { |chunk|
          file.write(chunk)
        }
      }
      Process.waitall
      File.delete(TempFile)
    }
  rescue Interrupt
    File.delete(TempFile)
    exit 1
  end
end

season  = Integer(ARGV[0][/s([^e]*)e/, 1])
episode = Integer(ARGV[0][/e(.*)/, 1])
code = decode(season, episode)

sniff_video(code)

Offline

#1220 2010-08-09 04:15:57

Stebalien
Member
Registered: 2010-04-27
Posts: 1,237
Website

Re: Post your handy self made command line utilities

This is a small python script that looks up a word (or a list of words) with WordNet. If no word is given as a command line argument, it looks up the currently selected words (i.e. the primary clipboard) and displays popups with their definitions. It requires wordnet and needs pygtk and pynotify for notifications.

#!/usr/bin/python
import subprocess

def lookup(*words):
    for word in words:
        out = subprocess.Popen(['/usr/bin/wn', word, '-synsn', '-synsv', '-synsa', '-synsr', '-g', '-n1'], shell=False, stdout=subprocess.PIPE).communicate()[0].split('\n')
        if len(out) > 1:
            t = out[1].split(' ')[-2]
            d = out[4].split('-- (', 1)[1].split(';',1)[0] + '.'
        else:
            t = "err"
            d = "word not found."
        yield word.capitalize(), t, d.capitalize()


if __name__ == "__main__":
    def _cli():
        for d in lookup(*sys.argv[1:]):
            print '[1;37m%s:  [0;32m%s. [0;36m%s[0m' % d

    def _gui():
        import pygtk
        pygtk.require('2.0')
        import gtk
        import pynotify
        pynotify.init("Dictionary")
        clipboard = gtk.Clipboard(selection="PRIMARY")
        if clipboard.wait_is_text_available():
            for d in lookup(*clipboard.wait_for_text().split()):
                n = pynotify.Notification(d[0], "%s. %s" % (d[1], d[2]))
                n.show()
    import sys
    if sys.argv[1:]:
        _cli()
    else:
        _gui()

Steven [ web : git ]
GPG:  327B 20CE 21EA 68CF A7748675 7C92 3221 5899 410C
Do not email: honeypot@stebalien.com

Offline

#1221 2010-08-09 19:33:54

StephenB
Member
From: UK
Registered: 2010-04-25
Posts: 18

Re: Post your handy self made command line utilities

Something for .bashrc to remember the last dir you were in (I call it your 'working directory') and take you there next time you open a console:

cd `cat ~/.working_dir`
cd_working() {
  cd "$@"
  pwd >~/.working_dir
}
alias cd='cd_working'

I find I often want many consoles in the same dir tree; going home 'cd<enter>' is much quicker than having to cd deep into a tree each time.

EDIT: add the following to cd_working (after cd "$@") if you like your terminal title to show your working dir path. (actually, I also add it after cd `cat ~/.working_dir`, so that my terminal title gets set instantly as well as being updated when I change dir)

echo -en "\033]0;`pwd`\007"

Last edited by StephenB (2010-08-09 19:47:56)

Offline

#1222 2010-08-09 19:49:00

akurei
Member
From: Bochum, NRW, Germany
Registered: 2009-05-25
Posts: 152
Website

Re: Post your handy self made command line utilities

Image upload with uimge (because -t [thumbnail] functionally is currently broken)

function picup()
{
    theimg="$(uimge --ib $1)" && echo "$theimg" && echo "$theimg" | xsel -ib
}

function picup_thumb() 
{
    convert "$1" -resize 400x400 "/tmp/$1" && theimg="$(uimge --ib $1)" && thethumbnail="$(uimge --ib /tmp/$1)" && echo "[url=$theimg][img]$thethumbnail[/img][/url]" \
    && echo "[url=$theimg][img]$thethumbnail[/img][/url]" | xsel -ib && rm "/tmp/$1"
}

picup uploads an image and both copies the URL into clipboard and outputs it to stdout.
picup_thumb does the same with BB-Code and generates a 400x400 max Thumbnail.

You can see the resulting output here:

21:48 akurei@joel:Wallpaper $ picup_thumb wall-e.png 
[url=http://imgby.com/walle.png][img]http://imgby.com/wallephp.png[/img][/url]

and here:


wallephp.png

Last edited by akurei (2010-08-09 19:50:05)

Offline

#1223 2010-08-09 20:58:51

xenofungus
Member
From: Spain
Registered: 2009-10-17
Posts: 63

Re: Post your handy self made command line utilities

StephenB wrote:

Something for .bashrc to remember the last dir you were in (I call it your 'working directory') and take you there next time you open a console:

cd `cat ~/.working_dir`
cd_working() {
  cd "$@"
  pwd >~/.working_dir
}
alias cd='cd_working'

I find I often want many consoles in the same dir tree; going home 'cd<enter>' is much quicker than having to cd deep into a tree each time.

EDIT: add the following to cd_working (after cd "$@") if you like your terminal title to show your working dir path. (actually, I also add it after cd `cat ~/.working_dir`, so that my terminal title gets set instantly as well as being updated when I change dir)

echo -en "\033]0;`pwd`\007"

sounds a lot like pushd / popd

Offline

#1224 2010-08-09 23:23:57

fukawi2
Ex-Administratorino
From: .vic.au
Registered: 2007-09-28
Posts: 6,224
Website

Re: Post your handy self made command line utilities

It's dirty, but useful for quick encryption/decryption of individual files (like the text file with the credit card numbers tongue)

CRYPT_EXT='3des'
function encrypt() {
        [ -e "$1" ] || return 1
        openssl des3 -salt -in "$1" -out "$1.$CRYPT_EXT"
        [ -e "$1.$CRYPT_EXT" ] && shred -u "$1"
}
function decrypt() {
        [ -e "$1" ] || return 1
        [ "${1%.$CRYPT_EXT}" != "$1" ] || return 2
        openssl des3 -d -salt -in $1 -out ${1%.$CRYPT_EXT}
        [ -e "${1%.$CRYPT_EXT}" ] && rm -f "$1"
}

And because I'm sick of doing this by hand:

function aurget() {
        [ -n "$1" ] || return 1
        cd /var/abs/local || return 1
        wget -q http://aur.archlinux.org/packages/$1/$1.tar.gz || return 1
        tar xvzf $1.tar.gz
        rm -f $1.tar.gz
}

Offline

#1225 2010-08-10 01:11:57

ataraxia
Member
From: Pittsburgh
Registered: 2007-05-06
Posts: 1,553

Re: Post your handy self made command line utilities

fukawi2 wrote:

And because I'm sick of doing this by hand:

function aurget() {
        [ -n "$1" ] || return 1
        cd /var/abs/local || return 1
        wget -q http://aur.archlinux.org/packages/$1/$1.tar.gz || return 1
        tar xvzf $1.tar.gz
        rm -f $1.tar.gz
}

How about a one-liner per each package, and handling multiple packages at once?

#!/bin/bash
# vim:set filetype=sh: *

for pkg in "$@" ; do
    /usr/bin/curl -L "http://aur.archlinux.org/packages/${pkg}/${pkg}.tar.gz" | /bin/tar -xzv -C /var/abs/local
done

Offline

Board footer

Powered by FluxBB