Posts Tagged ‘Linux’

Python’s range() for Bash

March 9, 2010

I doubt I’m the only one who often ends up typing: for i in 1 2 3 4 … a lot. I got sick and tired of it. Sometimes for the longer ones I’d start python, and use it to generate the sequence for me. It was absurd, so I fixed it.

Just set up the following Python script in /usr/local/bin/range and you’ll be good to go:


#!/usr/bin/env python

import sys

out = " "
if len(sys.argv) < 2 or len(sys.argv) > 4:
print "Usage: range [begin] end [[inc]]"
elif len(sys.argv) == 2:
for i in range(int(sys.argv[1])):
out += repr(i) + " "
elif len(sys.argv) == 3:
for i in range(int(sys.argv[1]), int(sys.argv[2])):
out += repr(i) + " "
else:
for i in range(int(sys.argv[1]), int(sys.argv[2]), int(sys.argv[3])):
out += repr(i) + " "
print out

(Ugh. WordPress is destroying indents….)

Now you can just do for i in `range 100`; … Yipee!

And yes, this is trivial. I don’t know why it took me so long to decide to do this.

Advertisement

/dev/audio: Raw Audio

June 23, 2009

Most Linux users are familiar with /dev/audio. Writing to it plays audio and reading from it records it. It accepts raw audio.

Some popular tricks with it are:

cat /dev/urandom > /dev/audio #Play Random Noise
cat /dev/audio > soundrecording #Record audio to file.
cat soundrecording > /dev/audio #Play recorded file.

A more complex one is eavesdroping on a room with a remote computer.

cat /dev/audio | nc -lp $PORT #Remote Computer
nc $IPADDR $PORT > /dev/audio #Local Computer

Where $PORT is the port you wish to use and $IP is the address of the remote computer.

But can one make synthetic sounds? I couldn’t find any documentation on how /dev/audio represents information. After playing around with it, however, I have come up with a model that at the very least predicts it reasonably well.

It seems that every character represents a certain voltage being applied to the speaker. Each characters value is proportional to its integer representation. /dev/audio accepts approximately 6000 chars/s. Thus, we can create a C function like:

/** @param freq: The frequency in Hertz (s^-1)
  * @param amp:  The amplitude (ie. loudness), unit not defined. Within the range 0-256.
  * @param time: The length in seconds.
  * @return A string representing the sound. Write to /dev/audio to play.  */
string sound(double freq, double amp, double time) {
	double r = 6000; // The number of characters interpreted by the speaker per second.
	int n = (int) time*r;
	string ret;
	for (int i = 0; i < n; ++i){
		ret += (char) (sin(i*freq)*amp+128);
	}
	return ret;
}

It’s not perfect, but it works. In particular, the low sampling rate results in horrible sound quality. r is not quite right either…

Update: It has come to my attention that /dev/audio accepts .wav files. The resolution can be changed.

A Couple Fish Hacks

June 13, 2009

The Friendly Interactive Shell is a fun shell to use. Here are a few cool things I’ve done with it.

‘Keymap’ mods

Fish allows us to use the bind builtin to modify the way it interprets keys. This allows to to easily make ‘keymaps’ for Fish. We can bind commands to keys as well, so we can make it switch back and forth…

eg. ASCII and Greek letters


First we make two functions: one for each set of bindings.

function keymap_ascii --description 'Normal key bindings'
	set keymap ascii
	bind --erase --all	# Clear earlier bindings, if any
	bind "" self-insert	# This is the default binding, i.e. the one used if no other binding matches
	bind -k dc delete-char
	bind -k backspace backward-delete-char
	bind -k right     forward-char
	bind -k left      backward-char
	bind -k home      beginning-of-line
	bind -k end       end-of-line
	bind -k down      down-or-search
	bind    \e\[A     down-or-search
	bind -k up        up-or-search
	bind    \e\[B     up-or-search
	bind    \n        execute
#	bind \e\n "commandline -i \n"
	bind \t complete
#	bind \cy yank
	bind \cl 'clear; commandline -f repaint'
	bind \ck 'keymap_greek; infobar'
	bind \cb 'infobar'
end

function keymap_greek --description 'Binds Greek keys to normal keys'
	set keymap greek
	bind --erase --all	# Clear earlier bindings, if any
	bind "" self-insert	# This is the default binding, i.e. the one used if no other binding matches
	bind -k dc delete-char
	bind -k backspace backward-delete-char
	bind -k right forward-char
	bind -k left backward-char
	bind -k home beginning-of-line
	bind -k end end-of-line
	bind -k down down-or-search
	bind -k up up-or-search
	bind   \n execute
#	bind \e\n "commandline -i \n"
	bind \t complete
#	bind \cy yank
	bind \cl 'clear; commandline -f repaint'
	bind \cb 'infobar'

	bind a 'commandline -i α'
	bind b 'commandline -i β'
	bind c 'commandline -i ς'
	bind d 'commandline -i δ'
	bind e 'commandline -i ε'
	bind f 'commandline -i φ'
	bind g 'commandline -i γ'
	bind h 'commandline -i η'
	bind i 'commandline -i ι'
#	bind j 'commandline -i '
	bind k 'commandline -i κ'
	bind l 'commandline -i λ'
	bind m 'commandline -i μ'
	bind n 'commandline -i ν'
	bind o 'commandline -i ο'
	bind p 'commandline -i π'
	bind q 'commandline -i θ'
	bind r 'commandline -i ρ'
	bind s 'commandline -i σ'
	bind t 'commandline -i τ'
	bind u 'commandline -i υ'
#	bind v 'commandline -i '
	bind w 'commandline -i ω'
	bind x 'commandline -i χ'
	bind y 'commandline -i ψ'
	bind z 'commandline -i ζ'
	bind A 'commandline -i Α'
	bind B 'commandline -i Β'
#	bind C 'commandline -i '
	bind D 'commandline -i Δ'
	bind E 'commandline -i Ε'
	bind F 'commandline -i Φ'
	bind G 'commandline -i Γ'
	bind H 'commandline -i Η'
	bind I 'commandline -i Ι'
#	bind J 'commandline -i '
	bind K 'commandline -i Κ'
	bind L 'commandline -i Λ'
	bind M 'commandline -i Μ'
	bind N 'commandline -i Ν'
	bind O 'commandline -i Ο'
	bind P 'commandline -i Π'
	bind Q 'commandline -i Θ'
	bind R 'commandline -i Ρ'
	bind S 'commandline -i Σ'
#	bind T 'commandline -i '
#	bind U 'commandline -i '
#	bind V 'commandline -i '
#	bind W 'commandline -i '
#	bind X 'commandline -i '
#	bind Y 'commandline -i '
#	bind Z 'commandline -i '

	bind \ck 'keymap_ascii; infobar'
end

Notice that C-k (Control k) is bound to switching the keymap. Don’t worry about infobar for now…

Now, we just need to make it the default binding:

function bfish_default_key_bindings --description 'Default (Emacs-like) key bindings for fish'
	keymap_ascii
end

Really, this isn’t the way to handle it… One should try and do it at another level. I’m toying with the idea of trying to make a kernel module to do this. And simultaneously make cap-locks actually useful. By changing what it does.

Information Bar

We can also create a information bar. We need a function that returns the cursor to where it started once it has made the bar. How? We use tput sc (save cursor) and tput rc (return cursor). Here’s the function, as a straight line, with a colored background…

function info_bar
tput sc
tput cup 0 0
tput setb 1
tput setaf 7
tput el
date
echo -n "  ||  "
pwd
tput rc
end

We need this function to run at least when we clear and run a command, so:

function fish_prompt
infobar
printf (tput setaf 4)(date +%H:%M)(tput setaf 2)(prompt_pwd)(tput setaf 1)"\$ "(tput setaf 0)
end

function clear
/usr/bin/clear
echo ""
infobar
end

Notice that the prompt is just my personal preferred one.

W3Counter: Linux Market Share at 2.06%

February 26, 2009

I don’t know if anyone else noticed, but for January ’09 the W3Counter puts Linux at 2.06%. A year a go Linux was at 1.84%. Malthus did say that growth is exponential…

Ubuntu is for Nerds, Too

January 18, 2009

infact [sic] ubuntu [sic] is for the mass [sic] and not for pros [sic] — Fabioamd87, Ubuntu Brainstorm

Ubuntu is the Linux distribution that I suggest to new users but in my interactions with the Ubuntu community, I am concerned by the growing “anti-advanced-user” mentality. And I’m not the only one, one of my friends switched to OpenSUSE, advising me to do the same: “Ubuntu is not for you.”

Now, you may be wondering why an advanced user would want to use an “easy” Linux distrobution like Ubuntu. The fact of the matter is that, just because I could, doesn’t mean I want to compile everything by hand. That’s not to say that there aren’t alternatives; I could run SUSE, Gentoo, Debian, et cetera… But I like Ubuntu and would really hate to have to stop using Ubuntu because of something like this.

So, I suppose, the logical next thing to point out is how is this “anti-advanced-user” mentality manifesting itself in the actual software? It’s difficult to see because, in comparison to Mac and Windows, Ubuntu is great for advanced users. But when one starts using other Linux distributions, they begin to notice that Ubuntu is falling behind. Furthermore, this is a trend so one needs to consider not only how it is now, but how it will be in the future.

The problem is self-magnifying: Ubuntu chases off advanced users, they aren’t there to represent themselves. Ubuntu chases off advanced users….

So what can be done to fix the problem? First of all and most importantly, this mentality needs to be fixed: The Ubuntu users who feel that advanced users shouldn’t benefit from Ubuntu need to understand that both beginner and advanced users can use the same Linux distribution and in fact benefit from sharing the same distribution. This will lead to many of the other problems fixing them selves. On the other hand, advanced users need to start giving and promoting suggestions instead of just walking away.

The problem is small right now. Let’s keep it that way.

The Linux community is splintered enough.

Modernizing the Command Line

January 14, 2009

One of the greatest features of Linux is the command line. Sadly, it has been somewhat neglected as of late. The purpose of this “Blog Entry” is to point out some command line features and possibilities that are not often taken advantage of.

The explanations provided are intended for an Ubuntu user using BASH as a shell, but could easily be modified for others. Some of the things mentioned in this entry are well known while other are not. The well known ones are here in case someone doesn’t know.

Color Arguments

Several programs produce color output when given certain arguments. To make this default, add the following to ~/.bashrc.

#Add to .bashrc
    alias ls="ls --color=auto"
    alias grep="grep --color=auto"
    alias less="less -R"

Color Versions

Using the programs colormake colorgcc and colordiff instead of their non-color equivalent can be pleasant. Install the color versions and alias them.

#Run to install
 sudo apt-get install colormake colorgcc colordiff
#Add to ~/.bashrc
alias make="colormake"
alias diff="colordiff"
alias gcc="colorgcc"

Variables

The PS1 variable is printed as the prompt in bash. It can contain escape sequences and commands. One suggestion would be mine:

#Add to the end of ~/.bashrc
PS1="\[33[0;34m\]$(date +"%H:%M")\[33[0;32m\]\w\[33[0;31m\]\$ \[33[00m\]"

Which results in:

blue:21:31 green:~ red:$

Some other suggestions and resources for PS1 variable can be found at the CLUG wiki.

Individuals may also be interested in adding colorful man pages by adding the following:

#Add to  ~/.bashrc
#note that the variables could easily be other
#escape sequences.
# For colourful man pages (CLUG-Wiki style)
export LESS_TERMCAP_mb=$'\E[01;31m'
export LESS_TERMCAP_md=$'\E[01;31m'
export LESS_TERMCAP_me=$'\E[0m'
export LESS_TERMCAP_se=$'\E[0m'
export LESS_TERMCAP_so=$'\E[01;44;33m'
export LESS_TERMCAP_ue=$'\E[0m'
export LESS_TERMCAP_us=$'\E[01;32m'

as suggested by the CLUG wiki

Compare:

Escape Codes in Raw Text Files

One Idea (that I haven’t seen anywhere else yet… UPDATE: I found another site with this…) is to put escape codes in files like /etc/motd or /etc/issue.

The following is my /etc/motd.tail (which forms /etc/motd on startup on Ubuntu systems). It is based on the normal Ubuntu one.

The programs included with the Ubuntu system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Ubuntu comes with ABSOLUTELY NO WARRANTY, to the extent permitted by
applicable law.

To access official Ubuntu documentation, please visit
http://help.ubuntu.com/

It renders as:


The programs included with the Ubuntu system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Ubuntu comes with ABSOLUTELY NO WARRANTY, to the extent permitted by applicable law.

To access official Ubuntu documentation, please visit
http://help.ubuntu.com/

One could do the same with /etc/issue which is printed right before login starts.

Others

One interesting thing to do is use lesspipe. There is a detailed entry about this on another blog.

It is also interesting to change the text printed out by the init functions. More information on this can be found on Ubuntu Forums.

Readers may also wish to look into framebuffers, which allow the displaying of pictures ( and pdfs, etc… once installed see fbi and links2 -g) and smaller fonts in the ttys. A good tutorial can be found on Ubuntu Forums.

I would advise readers to install gpm (general purpose mouse) which allows the use of a mouse in a tty.

It is also worth making sure that the readers are aware that vim, emacs and nano can all do syntax highlighting.