jueves, 27 de diciembre de 2012
Angel Canales, Solo sé que tiene nombre de mujer
Angel Canales, Solo sé que tiene nombre de mujer
Solo sé que tiene nombre de mujer, solo sé que tiene nombre de mujer,
solo sé que vive que respira y anda que es una esperanza para mi amanecer,
solo sé que vive que respira y anda que es una esperanza para mi amanecer.
Solo sé que tiene canela en su piel, ay solo se que tiene canela en su piel,
sus labios rosados y en sus ojos miel, sus labios rosados y en sus ojos miel,
que sobre su pecho tengo fino estampa su pelo azabache le suele caer,
que sobre su pecho tengo fino estampa su pelo azabache le suele caer
No sé donde se encuentra pero la buscaré,
ay no sé donde se encuentra pero la buscaré,
y si se me esconde yo la encontraré, y si se me esconde yo la encontraré,
Desde que yo creo en su existencia que tengo la esperanza de volverla a ver,
desde que yo creo en su existencia que tengo la esperanza de volverla a ver.
Aaaaaaaaabreme la pueeeerta , abreme la puerta buena
buena suerte mira que yo la quiero volver a ver.
Coro:
Abreme la puerta buena suerte que yo la quiero volver a ver
Yo quiero, yo quiero, yo quiero concocer a esa mujer por que yo quiero ser su negro
Abreme la puerta buena suerte que yo la quiero volver a ver
Yo quiero yo quiero yo quiero conocerla por que la quiero sacar a comer
Abreme la puerta buena suerte que yo la quiero volver a ver
abreme la puerta buena suerte mira que yo la quiero volver a ver.
eeeeeeeehh
aleeleeleelelele alaleleeeeaa
aaaaabreme la puerta buena suerte mira que yo la quiero, la quiero, la quiero, la quiero,
la quiero, la quiero volver a ver
ábreme la puerta buena suerte que yo la quiero verla
yo quiero ir la a bailar con ella, yo quiero también sacarla a comer
ábreme la puerta buena suerta que yo la quiero volver a ver
y cuando yo me encuentre con ella te juro que la voy hacer mi mujer
ábreme la puerta buena suerta que yo la quiero volver a ver
ábreme la puerta, ábreme la puerta,
ábreme la puerta buena suerte mira que aqui afuera
se encuentra tu querer.
Angel canales Hace tiempo
Angel canales, Hace tiempo
Hace tiempo que no duermo... tú ve
Porque estoy pensando en ti
Y es lo mucho que te quiero, mamá
Y tú no me quiere a mí.
Muchas mamis que me invitan... tú ve
Pero yo me muero por ti
No me hagas sufrir tanto, no, no
Ay, no me hagas padecer así.
(Ay, ay, ay, no me haga padecer así)
Ay, eche mozo más vinillo
Mire que me quiero emborrachar
(Ay, ay, ay) Ay, pero que ay, ay, ay
(No me haga padecer así)
Oye, por qué mi vida se ha ido tras de aquella
Ay, que no supo mi amor nunca apreciar
(Ay, ay, ay) Ay, pero que ay, ay, ay
(No me haga padecer así)
Ay, mamita, dame tu cosita, oye mami
Ay, que dame, dame, que dámela
(Ay, ay, ay) Ay, como una vida entera
(No me haga padecer así)
Oye, porque una vida entera, morena
La rumba buena contigo yo quiero bailar.
Ay, pero que quítate la ropa
Y ven y monta mi caballito, mira que es bien mansito.
La hora de Ricaldo…
Nooooo... ay, no o o o
(Ay, ay, ay) Ay, pero que ay, ay, ay
(No me haga padecer así)
Ay, nooooo… ay, no o o o
(Ay, ay, ay) Ay, pero que ay, ay, ay
(No me haga padecer así)
Oye, mamita, que a mí me da el sol en el alumbrado
Cuando te encuentro yo aquí a mi lado
(Ay, ay, ay) Ay, pero que ay, ay, ay
(No me haga padecer así)
Ay, pero así no me haga padecer
Ay, no me hagas así padecer
(Ay, ay, ay) Ay, que ay, ay, ay
(No me haga padecer así)
Ay, mamita, ay dame tu cosita, mami
(No me haga padecer así)
Ay, pero que no me haga padecer así, pero que no
(No me haga padecer así)
ay mamita mira que te llevo en mi corazón
(No me haga padecer así)
Lleva! Oh…oh.
Ya, pa’ que no haya más discusión
(No me haga padecer así)
Ay, no me haga mami, no o o
(No me haga padecer así)
Oye, que to’a la noche yo le rezo al santo
Al santo loco y de rodillas
(No me haga padecer así)
Pero que de rodillas yo le pido cosas buena
Y que vuelvas a mí
(No me haga padecer así)
Ay, pero que no haga, no
(No me haga padecer así)
Ay, no me haga padecer así, mami, no…
viernes, 14 de diciembre de 2012
sábado, 1 de diciembre de 2012
Habilitar USB en Android para transferencia de datos How to Enable USB Storage on Android Devices
http://www.infonucleo.com/2012/02/17/como-leer-la-tarjeta-de-memoria-microsd-en-el-samsung-galaxy-mini-desde-la-pc-usando-usb/
Como leer la tarjeta de memoria MicroSD en el Samsung Galaxy Mini desde la PC (usando USB)
En primer lugar desconectar el cable USB del móvil y la PC
Ir a “Configuración” o “Ajustes” luego entrar a “Aplicaciones” y luego a “Desarrollo” aquí debemos DESMARCAR donde dice “Depuración USB”
Conectar el cable USB al móvil y la PC, en algunos casos se vuelve a marcar “Depuración USB”, hay que volver a DESMARCAR esta opción
Aparecerá el ícono de Android y un botón que dice “Activar el almacenamiento USB”, hacemos click en este botón y ya podremos ver desde la PC el contenido de nuestra tarjeta Micro SD, pasar música, vídeos, libros o lo que queramos.
Espero con esto solucionar el problema de como acceder a la memoria Micro SD en el Samsung Galaxy Mini (y otros smartphones Samsung) desde la PC.
Cualquier comentario, duda o sugerencia es siempre bienvenido!.
jueves, 15 de noviembre de 2012
5 Tools to Introduce Programming to Kids
http://blogs.kqed.org/mindshift/2011/05/5-tools-to-introduce-programming-to-kids/
5 Tools to Introduce Programming to Kids
May 16, 2011 | 9:39 AM | By Audrey Watters
Being able to use the Internet and operate computers is one thing, but it may be just as valuable to teach students how to code. Giving students an introduction to programming helps peel back the layers of what happens inside computers and how computers communicate with one another online. Programming knowledge, even at a very basic level, makes technology seem less magical and more manageable. Programming also teaches other important skills, including math and logic.
Many students don’t have access to computer science courses until college, and that’s a missed opportunity to introduce younger students to programming. There are many tools out there that provide a great introduction to computer science for K-12 students, but here are a few of our favorites.
SCRATCH
Developed by the MIT Media Lab, Scratch is a visual programming language for children age 6 and up. Since its release in 2007, over 800,000 users have joined the Scratch website and have shared over 1.7 million projects — from games to animations. That sharing aspect is an important part of the Scratch community, so the projects that are uploaded to the site are licensed under the Creative Commons attribute and share alike license so that others can download and remix them. Scratch is available free of charge and runs on Mac, Windows, and Linux computers.
ALICE
Alice is a free and open source 3D programming environment designed to teach students object-oriented and event-driven programming. With Alice, students drag and drop graphic tiles in order to animate an object and create a program. A variant of Alice, Storytelling Alice was developed by Caitlin Kelleher as part of her doctoral work in Computer Science at Carnegie Mellon University. By emphasizing animations and social interactions, this approach was found to greatly increase the level of student interest in programming.
HACKETY HACK
Hackety Hack is an open source application that teaches the basics of programming in the popular Ruby language. Hackety Hack offers an interactive tutorial that runs on Windows, Mac, and Linux operating systems. While both Scratch and Alice use a graphical programming language with “blocks,” Hackety Hack teaches the basics of Ruby syntax. The tutorial and the text editor are well-integrated, so there isn’t any flipping back-and-forth to move between the How-To guide and the actual coding. Hackety Hack gives students a solid foundation in the language so they can quickly and easily start building their own apps in Ruby.
ARDUINO
Arduino is an open-source electronics prototyping platform with both hardware and software components. Arduino’s hardware is programmed with a language similar to C++, and although it may not be the easiest of entry points for learning programming, there’s something about building things that actually move that can be pretty compelling. Projects that use Arduino to introduce children to programming include a modification of Scratch to support simple programming on the Arduino hardware. As Google recently announced that it would allow Android mobile devices to communicate with Arduino hardware, look for more opportunities to work with this platform in the future, perhaps even via the Android App Inventor, a tool that provides a visual interface for building Android apps.
LEGO MINDSTORMS
One of the most popular toys in history, Lego may be best known for its brick-building. But Lego Mindstorms also enables robotics-building. Lego Mindstorms’ kits — which can be purchased in educational and consumer versions — include sensors and motors, and the programming is command-box rather than code programming. The kits come with languages supplied by Lego, but can be modified to work with third party languages. Like several of the tools on this list, Lego Mindstorms has its roots at the MIT Media Lab.
These are just a few of the options for introducing someone to programming. What other languages or tools have you used — in the classroom or at home?
FILED UNDER: Teaching With Tech, Alice, Arduino, Hackety Hack, Lego, programming, Ruby, Scratch
sábado, 13 de octubre de 2012
bash script tutorial
http://linuxconfig.org/Bash_scripting_Tutorial
bash script tutorial
First you need to find out where is your bash interpreter located. Enter the following into your command line:
Open up you favorite text editor and a create file called hello_world.sh. Insert the following lines to a file:
NOTE:Every bash shell script in this tutorial starts with shebang:"#!" which is not read as a comment. First line is also a place where you put your interpreter which is in this case: /bin/bash.
Here is our first bash shell script example:
Now you are ready to execute your first bash script:
Your backup script and variables:
Bash script execution with an output:
Similarly for example we can use while loop to check if file does not exists. This script will sleep until file does exists. Note bash negator "!" which negates the -e option.
The syntax fo ansi-c bash quoting is: $'' . Here is an example:
bash script tutorial
Last Updated on Wednesday, 02 November 2011 06:35
>PDF DOWNLOAD< >PDF DOWNLOAD< |
This bash script tutorial assumes no
previous knowledge of bash scripting.As you will soon discover in this
quick comprehensive bash scripting guide, learning the bash shell
scripting is very easy task. However, if you do not find an answer to
your questions by reading this bash tutorial or you need extra help,
feel free to ask us on our new Linux Forum. We will be more than happy to help you with your bash questions there. Lets begin this bash scripting tutorial with a simple "Hello World" script. Let's start with Learning the bash Shell: Unix Shell Programming Bash Scripting Beginners Guide FREE PDF DOWNLOAD Bash Scripting Advanced Guide FREE PDF DOWNLOAD |
1. Hello World Bash Shell Script
First you need to find out where is your bash interpreter located. Enter the following into your command line:
$ which bash
Open up you favorite text editor and a create file called hello_world.sh. Insert the following lines to a file:
NOTE:Every bash shell script in this tutorial starts with shebang:"#!" which is not read as a comment. First line is also a place where you put your interpreter which is in this case: /bin/bash.
Here is our first bash shell script example:
#!/bin/bash # declare STRING variable STRING="Hello World" #print variable on a screen echo $STRINGNavigate to a directory where your hello_world.sh is located and make the file executable:
$ chmod +x hello_world.sh
Now you are ready to execute your first bash script:
./hello_world.sh
2. Simple Backup bash shell script
#!/bin/bash tar -czf myhome_directory.tar.gz /home/linuxconfig
3. Variables
In this example we declare simple bash variable and print it on the screen ( stdout ) with echo command.#!/bin/bash STRING="HELLO WORLD!!!" echo $STRING
Your backup script and variables:
#!/bin/bash OF=myhome_directory_$(date +%Y%m%d).tar.gz tar -czf $OF /home/linuxconfig
3.1. Global vs. Local variables
#!/bin/bash #Define bash global variable #This variable is global and can be used anywhere in this bash script VAR="global variable" function bash { #Define bash local variable #This variable is local to bash function only local VAR="local variable" echo $VAR } echo $VAR bash # Note the bash global variable did not change # "local" is bash reserved word echo $VAR
4. Passing arguments to the bash script
#!/bin/bash # use predefined variables to access passed arguments #echo arguments to the shell echo $1 $2 $3 ' -> echo $1 $2 $3' # We can also store arguments from bash command line in special array args=("$@") #echo arguments to the shell echo ${args[0]} ${args[1]} ${args[2]} ' -> args=("$@"); echo ${args[0]} ${args[1]} ${args[2]}' #use $@ to print out all arguments at once echo $@ ' -> echo $@' # use $# variable to print out # number of arguments passed to the bash script echo Number of arguments passed: $# ' -> echo Number of arguments passed: $#'
/arguments.sh Bash Scripting Tutorial
5. Executing shell commands with bash
#!/bin/bash # use backticks " ` ` " to execute shell command echo `uname -o` # executing bash command without backticks echo uname -o
6. Reading User Input
#!/bin/bash echo -e "Hi, please type the word: \c " read word echo "The word you entered is: $word" echo -e "Can you please enter two words? " read word1 word2 echo "Here is your input: \"$word1\" \"$word2\"" echo -e "How do you feel about bash scripting? " # read command now stores a reply into the default build-in variable $REPLY read echo "You said $REPLY, I'm glad to hear that! " echo -e "What are your favorite colours ? " # -a makes read command to read into an array read -a colours echo "My favorite colours are also ${colours[0]}, ${colours[1]} and ${colours[2]}:-)"
7. Bash Trap Command
#!/bin/bash # bash trap command trap bashtrap INT # bash clear screen command clear; # bash trap function is executed when CTRL-C is pressed: # bash prints message => Executing bash trap subrutine ! bashtrap() { echo "CTRL+C Detected !...executing bash trap !" } # for loop from 1/10 to 10/10 for a in `seq 1 10`; do echo "$a/10 to Exit." sleep 1; done echo "Exit Bash Trap Example!!!" |
8. Arrays
8.1. Declare simple bash array
#!/bin/bash #Declare array with 4 elements ARRAY=( 'Debian Linux' 'Redhat Linux' Ubuntu Linux ) # get number of elements in the array ELEMENTS=${#ARRAY[@]} # echo each element in array # for loop for (( i=0;i<$ELEMENTS;i++)); do echo ${ARRAY[${i}]} done
8.2. Read file into bash array
#!/bin/bash # Declare array declare -a ARRAY # Link filedescriptor 10 with stdin exec 10<&0 # stdin replaced with a file supplied as a first argument exec < $1 let count=0 while read LINE; do ARRAY[$count]=$LINE ((count++)) done echo Number of elements: ${#ARRAY[@]} # echo array's content echo ${ARRAY[@]} # restore stdin from filedescriptor 10 # and close filedescriptor 10 exec 0<&10 10<&-
linuxconfig.org $ cat bash.txt Bash Scripting Tutorial Guide linuxconfig.org $ ./bash-script.sh bash.txt Number of elements: 4 Bash Scripting Tutorial Guide linuxconfig.org $
9. Bash if / else / fi statements
9.1. Simple Bash if/else statement
Please note the spacing inside the [ and ] brackets! Without the spaces, it won't work!#!/bin/bash directory="./BashScripting" # bash check if directory exists if [ -d $directory ]; then echo "Directory exists" else echo "Directory does not exists" fi
9.2. Nested if/else
#!/bin/bash # Declare variable choice and assign value 4 choice=4 # Print to stdout echo "1. Bash" echo "2. Scripting" echo "3. Tutorial" echo -n "Please choose a word [1,2 or 3]? " # Loop while the variable choice is equal 4 # bash while loop while [ $choice -eq 4 ]; do # read user input read choice # bash nested if/else if [ $choice -eq 1 ] ; then echo "You have chosen word: Bash" else if [ $choice -eq 2 ] ; then echo "You have chosen word: Scripting" else if [ $choice -eq 3 ] ; then echo "You have chosen word: Tutorial" else echo "Please make a choice between 1-3 !" echo "1. Bash" echo "2. Scripting" echo "3. Tutorial" echo -n "Please choose a word [1,2 or 3]? " choice=4 fi fi fi done
10. Bash Comparisons
10.1. Arithmetic Comparisons
-lt | < |
-gt | > |
-le | <= |
-ge | >= |
-eq | == |
-ne | != |
#!/bin/bash # declare integers NUM1=2 NUM2=2 if [ $NUM1 -eq $NUM2 ]; then echo "Both Values are equal" else echo "Values are NOT equal" fi
#!/bin/bash # declare integers NUM1=2 NUM2=1 if [ $NUM1 -eq $NUM2 ]; then echo "Both Values are equal" else echo "Values are NOT equal" fi
#!/bin/bash # declare integers NUM1=2 NUM2=1 if [ $NUM1 -eq $NUM2 ]; then echo "Both Values are equal" elif [ $NUM1 -gt $NUM2 ]; then echo "NUM1 is greater then NUM2" else echo "NUM2 is greater then NUM1" fi
10.2. String Comparisons
= | equal |
!= | not equal |
< | less then |
> | greater then |
-n s1 | string s1 is not empty |
-z s1 | string s1 is empty |
#!/bin/bash #Declare string S1 S1="Bash" #Declare string S2 S2="Scripting" if [ $S1 = $S2 ]; then echo "Both Strings are equal" else echo "Strings are NOT equal" fi
#!/bin/bash #Declare string S1 S1="Bash" #Declare string S2 S2="Bash" if [ $S1 = $S2 ]; then echo "Both Strings are equal" else echo "Strings are NOT equal" fi
11. Bash File Testing
-b filename | Block special file |
-c filename | Special character file |
-d directoryname | Check for directory existence |
-e filename | Check for file existence |
-f filename | Check for regular file existence not a directory |
-G filename | Check if file exists and is owned by effective group ID. |
-g filename | true if file exists and is set-group-id. |
-k filename | Sticky bit |
-L filename | Symbolic link |
-O filename | True if file exists and is owned by the effective user id. |
-r filename | Check if file is a readable |
-S filename | Check if file is socket |
-s filename | Check if file is nonzero size |
-u filename | Check if file set-ser-id bit is set |
-w filename | Check if file is writable |
-x filename | Check if file is executable |
#!/bin/bash file="./file" if [ -e $file ]; then echo "File exists" else echo "File does not exists" fi
Similarly for example we can use while loop to check if file does not exists. This script will sleep until file does exists. Note bash negator "!" which negates the -e option.
#!/bin/bash while [ ! -e myfile ]; do # Sleep until file does exists/is created sleep 1 done
12. Loops
12.1. Bash for loop
#!/bin/bash # bash for loop for f in $( ls /var/ ); do echo $f doneRunning for loop from bash shell command line:
$ for f in $( ls /var/ ); do echo $f; done
12.2. Bash while loop
#!/bin/bash COUNT=6 # bash while loop while [ $COUNT -gt 0 ]; do echo Value of count is: $COUNT let COUNT=COUNT-1 done
12.3. Bash until loop
#!/bin/bash COUNT=0 # bash until loop until [ $COUNT -gt 5 ]; do echo Value of count is: $COUNT let COUNT=COUNT+1 done
12.4. Control bash loop with
Here is a example of while loop controlled by standard input. Until the redirection chain from STDOUT to STDIN to the read command exists the while loop continues.#!/bin/bash # This bash script will locate and replace spaces # in the filenames DIR="." # Controlling a loop with bash read command by redirecting STDOUT as # a STDIN to while loop # find will not truncate filenames containing spaces find $DIR -type f | while read file; do # using POSIX class [:space:] to find space in the filename if [[ "$file" = *[[:space:]]* ]]; then # substitute space with "_" character and consequently rename the file mv "$file" `echo $file | tr ' ' '_'` fi; # end of while loop done
13. Bash Functions
!/bin/bash # BASH FUNCTIONS CAN BE DECLARED IN ANY ORDER function function_B { echo Function B. } function function_A { echo $1 } function function_D { echo Function D. } function function_C { echo $1 } # FUNCTION CALLS # Pass parameter to function A function_A "Function A." function_B # Pass parameter to function C function_C "Function C." function_D
14. Bash Select
#!/bin/bash PS3='Choose one word: ' # bash select select word in "linux" "bash" "scripting" "tutorial" do echo "The word you have selected is: $word" # Break, otherwise endless loop break done exit 0
15. Case statement conditional
#!/bin/bash echo "What is your preferred programming / scripting language" echo "1) bash" echo "2) perl" echo "3) phyton" echo "4) c++" echo "5) I do not know !" read case; #simple case bash structure # note in this case $case is variable and does not have to # be named case this is just an example case $case in 1) echo "You selected bash";; 2) echo "You selected perl";; 3) echo "You selected phyton";; 4) echo "You selected c++";; 5) exit esac
16. Bash quotes and quotations
Quotations and quotes are important part of bash and bash scripting. Here are some bash quotes and quotations basics.16.1. Escaping Meta characters
Before we start with quotes and quotations we should know something about escaping meta characters. Escaping will suppress a special meaning of meta characters and therefore meta characters will be read by bash literally. To do this we need to use backslash "\" character. Example:#!/bin/bash #Declare bash string variable BASH_VAR="Bash Script" # echo variable BASH_VAR echo $BASH_VAR #when meta character such us "$" is escaped with "\" it will be read literally echo \$BASH_VAR # backslash has also special meaning and it can be suppressed with yet another "\" echo "\\"
16.2. Single quotes
Single quotes in bash will suppress special meaning of every meta characters. Therefore meta characters will be read literally. It is not possible to use another single quote within two single quotes not even if the single quote is escaped by backslash.#!/bin/bash #Declare bash string variable BASH_VAR="Bash Script" # echo variable BASH_VAR echo $BASH_VAR # meta characters special meaning in bash is suppressed when using single quotes echo '$BASH_VAR "$BASH_VAR"'
16.3. Double Quotes
Double quotes in bash will suppress special meaning of every meta characters except "$", "\" and "`". Any other meta characters will be read literally. It is also possible to use single quote within double quotes. If we need to use double quotes within double quotes bash can read them literally when escaping them with "\". Example:#!/bin/bash #Declare bash string variable BASH_VAR="Bash Script" # echo variable BASH_VAR echo $BASH_VAR # meta characters and its special meaning in bash is # suppressed when using double quotes except "$", "\" and "`" echo "It's $BASH_VAR and \"$BASH_VAR\" using backticks: `date`"
16.4. Bash quoting with ANSI-C style
There is also another type of quoting and that is ANSI-C. In this type of quoting characters escaped with "\" will gain special meaning according to the ANSI-C standard.\a | alert (bell) | \b | backspace |
\e | an escape character | \f | form feed |
\n | newline | \r | carriage return |
\t | horizontal tab | \v | vertical tab |
\\ | backslash | \` | single quote |
\nnn | octal value of characters ( see [http://www.asciitable.com/ ASCII table] ) | \xnn | hexadecimal value of characters ( see [http://www.asciitable.com/ ASCII table] ) |
#!/bin/bash # as a example we have used \n as a new line, \x40 is hex value for @ # and \56 is octal value for . echo $'web: www.linuxconfig.org\nemail: web\x40linuxconfig\56org'
17. Arithmetic Operations
17.1. Bash Addition Calculator Example
#!/bin/bash let RESULT1=$1+$2 echo $1+$2=$RESULT1 ' -> # let RESULT1=$1+$2' declare -i RESULT2 RESULT2=$1+$2 echo $1+$2=$RESULT2 ' -> # declare -i RESULT2; RESULT2=$1+$2' echo $1+$2=$(($1 + $2)) ' -> # $(($1 + $2))'
17.2. Bash Arithmetics
#!/bin/bash echo '### let ###' # bash addition let ADDITION=3+5 echo "3 + 5 =" $ADDITION # bash subtraction let SUBTRACTION=7-8 echo "7 - 8 =" $SUBTRACTION # bash multiplication let MULTIPLICATION=5*8 echo "5 * 8 =" $MULTIPLICATION # bash division let DIVISION=4/2 echo "4 / 2 =" $DIVISION # bash modulus let MODULUS=9%4 echo "9 % 4 =" $MODULUS # bash power of two let POWEROFTWO=2**2 echo "2 ^ 2 =" $POWEROFTWO echo '### Bash Arithmetic Expansion ###' # There are two formats for arithmetic expansion: $[ expression ] # and $(( expression #)) its your choice which you use echo 4 + 5 = $((4 + 5)) echo 7 - 7 = $[ 7 - 7 ] echo 4 x 6 = $((3 * 2)) echo 6 / 3 = $((6 / 3)) echo 8 % 7 = $((8 % 7)) echo 2 ^ 8 = $[ 2 ** 8 ] echo '### Declare ###' echo -e "Please enter two numbers \c" # read user input read num1 num2 declare -i result result=$num1+$num2 echo "Result is:$result " # bash convert binary number 10001 result=2#10001 echo $result # bash convert octal number 16 result=8#16 echo $result # bash convert hex number 0xE6A result=16#E6A echo $result
17.3. Round floating point number
#!/bin/bash # get floating point number floating_point_number=3.3446 echo $floating_point_number # round floating point number with bash for bash_rounded_number in $(printf %.0f $floating_point_number); do echo "Rounded number with bash:" $bash_rounded_number done
17.4. Bash floating point calculations
#!/bin/bash # Simple linux bash calculator echo "Enter input:" read userinput echo "Result with 2 digits after decimal point:" echo "scale=2; ${userinput}" | bc echo "Result with 10 digits after decimal point:" echo "scale=10; ${userinput}" | bc echo "Result as rounded integer:" echo $userinput | bc
18. Redirections
18.1. STDOUT from bash script to STDERR
#!/bin/bash echo "Redirect this STDOUT to STDERR" 1>&2To prove that STDOUT is redirected to STDERR we can redirect script's output to file:
18.2. STDERR from bash script to STDOUT
#!/bin/bash cat $1 2>&1To prove that STDERR is redirected to STDOUT we can redirect script's output to file:
18.3. stdout to screen
The simple way to redirect a standard output ( stdout ) is to simply use any command, because by default stdout is automatically redirected to screen. First create a file "file1":$ touch file1 $ ls file1 file1As you can see from the example above execution of ls command produces STDOUT which by default is redirected to screen.
18.4. stdout to file
The override the default behavior of STDOUT we can use ">" to redirect this output to file:$ ls file1 > STDOUT $ cat STDOUT file1
18.5. stderr to file
By default STDERR is displayed on the screen:$ ls file1 STDOUT $ ls file2 ls: cannot access file2: No such file or directoryIn the following example we will redirect the standard error ( stderr ) to a file and stdout to a screen as default. Please note that STDOUT is displayed on the screen, however STDERR is redirected to a file called STDERR:
$ ls file1 STDOUT $ ls file1 file2 2> STDERR file1 $ cat STDERR ls: cannot access file2: No such file or directory
18.6. stdout to stderr
It is also possible to redirect STDOUT and STDERR to the same file. In the next example we will redirect STDOUT to the same descriptor as STDERR. Both STDOUT and STDERR will be redirected to file "STDERR_STDOUT".$ ls file1 STDERR STDOUT $ ls file1 file2 2> STDERR_STDOUT 1>&2 $ cat STDERR_STDOUT ls: cannot access file2: No such file or directory file1File STDERR_STDOUT now contains STDOUT and STDERR.
18.7. stderr to stdout
The above example can be reversed by redirecting STDERR to the same descriptor as SDTOUT:$ ls file1 STDERR STDOUT $ ls file1 file2 > STDERR_STDOUT 2>&1 $ cat STDERR_STDOUT ls: cannot access file2: No such file or directory file1
18.8. stderr and stdout to file
Previous two examples redirected both STDOUT and STDERR to a file. Another way to achieve the same effect is illustrated below:$ ls file1 STDERR STDOUT $ ls file1 file2 &> STDERR_STDOUT $ cat STDERR_STDOUT ls: cannot access file2: No such file or directory file1or
ls file1 file2 >& STDERR_STDOUT $ cat STDERR_STDOUT ls: cannot access file2: No such file or directory file1
Writing Sheel Scripts Linux Unix
http://linuxcommand.org/writing_shell_scripts.php
|
|
Here is where the fun beginsWith the thousands of commands available for the command line user, how can you remember them all? The answer is, you don't. The real power of the computer is its ability to do the work for you. To get it to do that, we use the power of the shell to automate things. We write scripts.Scripts are collections of commands that are stored in a file. The shell can read this file and act on the commands as if they were typed at the keyboard. In addition to the things you have learned so far, the shell also provides a variety of useful programming features to make your scripts truly powerful. What are scripts good for? A wide range of tasks can be automated. Here are some of the things I automate with scripts:
Contents
|
|
© 2000-2012,
William E. Shotts, Jr.
Verbatim copying and distribution of this entire article is
permitted in any medium, provided this copyright notice is preserved.
Linux® is a registered trademark of Linus Torvalds.
|
Linux Shell Scripting Tutorial v1.05r3 A Beginner's handbook
http://www.freeos.com/guides/lsst/
Linux Shell Scripting Tutorial v1.05r3
Copyright © 1999-2002 by
Vivek G. Gite <vivek@nixcraft.com> |
|
Table of Contents
- Chapter 1: Quick Introduction to Linux
- What Linux is?
Who developed the Linux?
How to get Linux?
How to Install Linux
Where I can use Linux?
What Kernel Is?
What is Linux Shell?
How to use Shell
What is Shell Script ?
Why to Write Shell Script ?
More on Shell... - Chapter 2: Getting started with Shell Programming
- How to write shell script
Variables in shell
How to define User defined variables (UDV)
Rules for Naming variable name (Both UDV and System Variable)
How to print or access value of UDV (User defined variables)
echo Command
Shell Arithmetic
More about Quotes
Exit Status
The read Statement
Wild cards (Filename Shorthand or meta Characters)
More commands on one command line
Command Line Processing
Why Command Line arguments required
Redirection of Standard output/input i.e. Input - Output redirection
Pipes
Filter
What is Processes
Why Process required
Linux Command(s) Related with Process - Chapter 3: Shells (bash) structured Language Constructs
- Decision making in shell script ( i.e.
if command)
test command or [ expr ]
if...else...fi
Nested ifs
Multilevel if-then-else
Loops in Shell Scripts
for loop
Nested for loop
while loop
The case Statement
How to de-bug the shell script? - Chapter 4: Advanced Shell Scripting Commands
- /dev/null - to send unwanted output of
program
Local and Global Shell variable (export command)
Conditional execution i.e. && and ||
I/O Redirection and file descriptors
Functions
User Interface and dialog utility-Part I
User Interface and dialog utility-Part II
Message Box (msgbox) using dialog utility
Confirmation Box (yesno box) using dialog utility
Input (inputbox) using dialog utility
User Interface using dialog Utility - Putting it all together
trap command
The shift Command
getopts command - Chapter 5: Essential Utilities for Power User
- Preparing for Quick Tour of essential
utilities
Selecting portion of a file using cut utility
Putting lines together using paste utility
The join utility
Translating range of characters using tr utility
Data manipulation using awk utility
sed utility - Editing file without using editor
Removing duplicate lines from text database file using uniq utility
Finding matching pattern using grep utility - Chapter 6: Learning expressions with ex
- Getting started with ex
Printing text on-screen
Deleting lines
Coping lines
Searching the words
Find and Replace (Substituting regular expression)
Replacing word with confirmation from user
Finding words
Using range of characters in regular expressions
Using & as Special replacement character
Converting lowercase character to uppercase - Chapter 7: awk Revisited
- Getting Starting with awk
Predefined variables of awk
Doing arithmetic with awk
User Defined variables in awk
Use of printf statement
Use of Format Specification Code
if condition in awk
Loops in awk
Real life examples in awk
awk miscellaneous
sed - Quick Introduction
Redirecting the output of sed command
How to write sed scripts?
More examples of sed - Chapter 8: Examples of Shell Scripts
- Logic Development:
Shell script to print given numbers sum of all digit
Shell script to print contains of file from given line number to next given number of lines
Shell script to say Good morning/Afternoon/Evening as you log in to system
Shell script to find whether entered year is Leap or not
Sort the given five number in ascending order (use of array)
Command line (args) handling:
Adding 2 nos. suppiled as command line args
Calculating average of given numbers on command line args
Finding out biggest number from given three nos suppiled as command line args
Shell script to implement getopts statement.
Basic math Calculator (case statement)
Loops using while & for loop:
Print nos. as 5,4,3,2,1 using while loop
Printing the patterns using for loop.
Arithmetic in shell scripting:
Performing real number calculation in shell script
Converting decimal number to hexadecimal number
Calculating factorial of given number
File handling:
Shell script to determine whether given file exist or not.
Screen handling/echo command with escape sequence code:
Shell script to print "Hello World" message, in Bold, Blink effect, and in different colors like red, brown etc.
Background process implementation:
Digital clock using shell script
User interface and Functions in shell script:
Shell script to implements menu based system.
System Administration:
Getting more information about your working environment through shell script
Shell script to gathered useful system information such as CPU, disks, Ram and your environment etc.
Shell script to add DNS Entery to BIND Database with default Nameservers, Mail Servers (MX) and host
Integrating awk script with shell script:
Script to convert file names from UPPERCASE to lowercase file names or vice versa. - Chapter 9: Other Resources
- Appendix - A : Linux File Server Tutorial
(LFST) version b0.1 Rev. 2
Appendix - B : Linux Command Reference (LCR)
About the author
About this Document
|
||
Quick Introduction to Linux
|
martes, 9 de octubre de 2012
Imagenes
http://www6.uniovi.es/vision/intro/node36.html
http://elgva1.usc.es/~mjose/docencia/3ciclo/tema1.htm
http://www.tsc.uc3m.es/imagine/Curso_ProcesadoBasico/Contenido/OperacionesPuntuales/OperacionesPuntuales.html#appletOperacionesPuntuales
http://alojamientos.us.es/gtocoma/pid/tema1-2.pdf
http://www.cs.buap.mx/~iolmos/pdi/Sesion3_Histograma.pdf
http://elgva1.usc.es/~mjose/docencia/3ciclo/tema1.htm
http://www.tsc.uc3m.es/imagine/Curso_ProcesadoBasico/Contenido/OperacionesPuntuales/OperacionesPuntuales.html#appletOperacionesPuntuales
http://alojamientos.us.es/gtocoma/pid/tema1-2.pdf
http://www.cs.buap.mx/~iolmos/pdi/Sesion3_Histograma.pdf
Electronic Chillout Voice - Sunlounger-The_Downtempo_Edition-2CD-2010-TGX
http://forum.funkysouls.com/dump/f54t40178n200.html
Sunlounger-The_Downtempo_Edition-2CD-2010-TGX
Artist ............ : Sunlounger
Title ............. : The Downtempo Edition
Genre ............. : Ambient
Label ............. : Armada Music
Catalog Number .... : ARMA232
Source ............ : CD
Quality ........... : 197kbps avg / 44.1KHz / Joint Stereo
Playtime .......... : 02:17:50 (194.MB)
Release Date ...... : 2010-01-20
[Track List]
Disc 1/2
--------
1. Sunlounger - Another Day On The Terrace 8:13
2. Sunlounger - In & Out 5:35
3. Sunlounger - White Sand 4:49
4. Sunlounger - Losing Again 5:14
5. Sunlounger feat. Seis Cuerdas - A Balearic Dinner 5:32
6. Sunlounger feat. Zara - Crawling 6:54
7. Sunlounger - Aguas Blancas 7:25
8. Sunlounger - Keep Our Ring 6:15
9. Sunlounger - Hierbas Ibicencas 5:10
10.Sunlounger - Lounging By The Sea 3:58
11.Sunlounger - Shine On Me 6:16
12.Sunlounger - Lumumba 5:39
Disc 2/2
--------
1. Sunlounger - Sunny Tales 6:01
2. Sunlounger feat. Kyler England - Change Your Mind 6:16
3. Sunlounger - Mediterranean Flower 5:33
4. Sunlounger feat. Zara - Lost 5:38
5. Sunlounger - Spiritual Hideout 5:44
6. Sunlounger feat. Cap & Stephanie Asscher - Heart of the Sun 6:45
7. Sunlounger - Punta Galera 4:29
8. Sunlounger feat. Lorilee - Your Name 4:54
9. Sunlounger - Catwalk 4:57
10.Sunlounger feat. Zara - Talk To me 6:46
11.Sunlounger & Ingsha feat. Simon Binkenborn - One More Day 6:01
12.Sunlounger feat. Seis Cuerdas - A Balearic Breakfast 3:46
[Release Notes]
There's a calmness under the warm waves of Roger Shah's music. Over the
past 4 years, the German music creator has warmed the trance scene with
several strong, Balearic trance productions. Whether played out in their
dance versions for the ten thousands of clubbers, or slipped into the
ears through home speakers or headphones in the chilled out lounge
versions, Shah's tracks have pleased crowds all across the globe.
Shah released some of his biggest productions under the Sunlounger
moniker. The very first Sunlounger track, 'White Sand' turned the heads
and made the trance scene wonder who managed to capture the Balearic
spirit so perfectly. Their need to hear more was fulfilled with two
complete Sunlounger albums, 'Another Day On The Terrace' in 2007,
followed by 'Sunny Tales' in 2008.
'Sunlounger - The Downtempo Edition' is a collection of the chill
versions of the tracks of both albums. 24 guitar-driven, melodic
infusions of pure sunlight captured in beats, synths and the true Shah
sound. Relax, ease your mind and slip this one into your player. Let the
Balearic senses take over completely, with Sunlounger as your guide.
Sunlounger-The_Downtempo_Edition-2CD-2010-TGX
Artist ............ : Sunlounger
Title ............. : The Downtempo Edition
Genre ............. : Ambient
Label ............. : Armada Music
Catalog Number .... : ARMA232
Source ............ : CD
Quality ........... : 197kbps avg / 44.1KHz / Joint Stereo
Playtime .......... : 02:17:50 (194.MB)
Release Date ...... : 2010-01-20
[Track List]
Disc 1/2
--------
1. Sunlounger - Another Day On The Terrace 8:13
2. Sunlounger - In & Out 5:35
3. Sunlounger - White Sand 4:49
4. Sunlounger - Losing Again 5:14
5. Sunlounger feat. Seis Cuerdas - A Balearic Dinner 5:32
6. Sunlounger feat. Zara - Crawling 6:54
7. Sunlounger - Aguas Blancas 7:25
8. Sunlounger - Keep Our Ring 6:15
9. Sunlounger - Hierbas Ibicencas 5:10
10.Sunlounger - Lounging By The Sea 3:58
11.Sunlounger - Shine On Me 6:16
12.Sunlounger - Lumumba 5:39
Disc 2/2
--------
1. Sunlounger - Sunny Tales 6:01
2. Sunlounger feat. Kyler England - Change Your Mind 6:16
3. Sunlounger - Mediterranean Flower 5:33
4. Sunlounger feat. Zara - Lost 5:38
5. Sunlounger - Spiritual Hideout 5:44
6. Sunlounger feat. Cap & Stephanie Asscher - Heart of the Sun 6:45
7. Sunlounger - Punta Galera 4:29
8. Sunlounger feat. Lorilee - Your Name 4:54
9. Sunlounger - Catwalk 4:57
10.Sunlounger feat. Zara - Talk To me 6:46
11.Sunlounger & Ingsha feat. Simon Binkenborn - One More Day 6:01
12.Sunlounger feat. Seis Cuerdas - A Balearic Breakfast 3:46
[Release Notes]
There's a calmness under the warm waves of Roger Shah's music. Over the
past 4 years, the German music creator has warmed the trance scene with
several strong, Balearic trance productions. Whether played out in their
dance versions for the ten thousands of clubbers, or slipped into the
ears through home speakers or headphones in the chilled out lounge
versions, Shah's tracks have pleased crowds all across the globe.
Shah released some of his biggest productions under the Sunlounger
moniker. The very first Sunlounger track, 'White Sand' turned the heads
and made the trance scene wonder who managed to capture the Balearic
spirit so perfectly. Their need to hear more was fulfilled with two
complete Sunlounger albums, 'Another Day On The Terrace' in 2007,
followed by 'Sunny Tales' in 2008.
'Sunlounger - The Downtempo Edition' is a collection of the chill
versions of the tracks of both albums. 24 guitar-driven, melodic
infusions of pure sunlight captured in beats, synths and the true Shah
sound. Relax, ease your mind and slip this one into your player. Let the
Balearic senses take over completely, with Sunlounger as your guide.
Цитата: |
DepositFiles.com LetitBit.net Rapidshare1 Rapidshare2 Rapidshare3 iFolder1 iFolder2 iFolder3 |
lunes, 8 de octubre de 2012
The 'Classic' Non-Recursive DIF FFT Routine.
http://www.engineeringproductivitytools.com/stuff/T0001/PT03.HTM#Head134
Bottom Previous Contents
If N is even, the above sum can be split into 'top' (n=0..N/2-1) and 'bottom' (n=N/2..N-1) halves and re-arranged as follows:
If we now consider the form of this result for even and odd valued k separately, we can see how this result enables us to express an N point FFT in terms of 2 (N/2) point FFT's.
Even k, k=2k' (k'=0..N/2-1):
or equivalently..
Odd k, k=2k'+1 (k'=0..N/2-1):
or equivalently..
The process of dividing the frequency components into even and odd parts
is what gives this algorithm its name 'Decimation In Frequency'. If N is a regular power of 2, we can apply this method recursively until we get to the trivial 1 point transform. The factors TN are conventionally referred to as 'twiddle factors'.
This has solution:
or, in terms of N (=2p):
Dropping the constant scaling factors (including the log base) we get an algorithmic complexity of O(N.logN)
What if the last loop were somehow replaced by a simple catenation the results of the two sub-transforms? Say we put all the even k samples in the top half of the result and all the odd samples in the bottom half of the result. Treating k as a binary number, the least significant bit of k determines which 'half' of the result array the corresponding value resides in. The least significant bit of k becomes the most significant bit of the corresponding (binary) array index. Because the function is recursive, this bit swapping will occur for each sub-transform etc.. I.E. The array index is determined by bit reversing k. Doing this won't save any time, unless we can arrange that the catenation operation is actually performed implicitly by each sub-transform. This suggests that an 'in place' algorithm should be used (one which performs all necessary operations in a single array, rather than allocating temporary arrays on the stack). Looking at the form of the first loop in the above routine indicates how to do this, put the 'even' subset values back in f[n] (the top half) and put the 'odd' subset values back in f[n+N'] (the bottom half), then perform the DIF operation on each half. Pulling all these ideas together, we get a more efficient (recursive) in-place DIF routine:
It is worth noting that this is the simplest formulation of the 'in-place' DIF algorithm. It takes normal order input and generates bit reversed order output. However, this is not fundamental to the algorithm, it is merely a consequence of the simplest implementation. It is possible to write a reverse order DIF algorithm FFT which takes bit reversed order input and generates normal order output. This requires the DIF FFT routine to be amended in two ways:
In practice, calculating these will require time consuming COS's and
SIN's, so you certainly don't want to do this for every butterfly (if
you do your FFT will be anything but fast). So what you need is a look
up table (an array of size N/2) which is calculated just once. The important thing to realise is that you don't need a separate table for each DIF pass (N
halves each pass). Instead you use the same table each pass and
introduce an additional 'twiddle_step_size' parameter which starts at 1
and doubles after each pass. The twiddle factor used has index
n*twiddle_step_size. (The array bounds will never be exceeded, because N halves on each pass and the maximum value of n is N/2-1.)
The next trick is to notice that often the twiddle factor will be either +1 or -j (it will never be -1 or +j). In such cases there is no need to do a full blown complex multiply (remember this requires 4 real multiplies and 2 real adds). Simple addition and subtraction will suffice. We shall call butterflies that use on or other of these twiddle factors 'trivial butterflies'. Specifically:
How often does this occur? Consider the last DIF FFT pass (N=2). In this case T2(0)=1
is the only twiddle factor used. So the entire last pass consists of
trivial butterflies. Similarly, the first butterfly of of any sub-block
will use TN(0)=1. In general, in pass P (P=0..p-1), there are BP (=2P) sub-blocks and therefore 2P butterflies which use a twiddle factor of +1.
In the penultimate (N=4) pass the butterflies will use either T4(0)=1 or T4(1)=-j. So this pass also uses only trivial butterflies. As in the above case, in each of the previous (N>4, P<p-2) passes, there are BP (=2P) sub-blocks and therefore 2P butterflies which use a twiddle factor of -j (at n=N/4) .
We can now calculate exactly how many of these trivial butterflies Triv(p) there are in a typical DIF FFT for sizes >4 (p>2). This is the sum of the number of butterflies in the last 2 passes (the easy bit) and the number of trivial butterflies in all the other passes (the hard bit, but the result in Annex B is useful here):
The total number of butterflies was calculated earlier:
So for a 2p point DIF FFT, the proportion of trivial butterflies is about 3/p. If this shortcut is exploited, then large FFT's benefit less than small FFT's. For example, in a 512 point (p=9) DIF FFT about 1/3 of the butterflies will be trivial.
The non-recursive routine presented above can be modified to exploit trivial butterflies by doing something like this:
As a final note, we can observe that there are further opportunities to exploit which we haven't considered:
These aren't quite so trivial (should call them semi-trivial?), but
there are still potentially faster ways of using these than full blown
complex multiplication.
The 'Classic' Non-Recursive DIF FFT Routine.
For many processors/languages a recursive routine is not attractive, because of the overhead incurred by a procedure call. Be careful though, in reality an aversion to recursion could cost performance (see the note about cache efficiency). There is also a particular problem with DSP's which often have small hardware stacks, so deeply recursive routines will cause stack overflow. It is fairly easy to see that the above routine can be flattened into nested loops, to yield something resembling the 'classic' (non recursive) DIF FFT. Each DIF uses 2 'half size' DIF's, which in turn will use 4 'quarter size' DIF's, etc.. the last (not trivial) DIF will be for size 2. So, keeping notation consistent with the above recursive DIF, we get 3 nested loops:- Pass Loop: An N (=2p ) point transform will perform p 'passes', indexed by P=0..p-1.
- Block Loop: Pass will P operate on BP (=2P ) sub-blocks, each of size NP (=N/BP=2p-P), indexed by b=0..BP-1
- Butterfly Loop: Each sub-block operation will perform N'P (=NP/2=2p-P-1) butterflies, indexed by n=0..N'P-1.
{Perform in place DIF of 2^p points (=size of f)} PROCEDURE DIF(p,VAR f); LOCAL Bp,Np,Np',P,b,n,BaseE,BaseO,e,o; BEGIN {DIF} {initialise pass parameters} Bp:=1; {No. of blocks} Np:=1<<p; {No. of points in each block} {perform p passes} FOR P:=0 TO (p-1) DO BEGIN {pass loop} Np':=Np>>1; {No. of butterflies} BaseE:=0; {Reset even base index} FOR b:=0 TO (Bp-1) DO BEGIN {block loop} BaseO:=BaseE+Np'; {calc odd base index} FOR n:=0 TO (Np'-1) DO BEGIN {butterfly loop} e:= f[BaseE+n]+f[BaseO+n]; o:=(f[BaseE+n]-f[BaseO+n])*T(Np,n); f[BaseE+n]:=e; f[BaseO+n]:=o; END; {butterfly loop} BaseE:=BaseE+Np; {start of next block} END; {block loop} {calc parameters for next pass} Bp:=Bp<<1; {twice as many blocks} Np:=Np>>1; {half as many points in each block} END; {pass loop} END; {DIF}That's as far as we'll go on DIF code. Of course, if you look, there's still plenty of scope for further optimisation of this routine. We won't do it here for fear of obscuring the code even more. The remainder of this section is devoted to a few observations about the practical details of the twiddle factors, which so far have been largely neglected.
Bottom Previous Contents
The Radix 2 Decimation In Frequency (DIF) Algorithm.
The Maths.
We defined the FFT as:Even k, k=2k' (k'=0..N/2-1):
Odd k, k=2k'+1 (k'=0..N/2-1):
A Recursive DIF FFT Routine.
Given the above results, we can now have a 'first stab' at a recursive routine to implement this algorithm (in a hypothetical Pascal like programming language which supports complex numbers and allows arrays as function arguments and results):FUNCTION DIF(N,f); LOCAL N',n,fe,fo,Fe,Fo,k',F; IF N==1 THEN RETURN(f); {trivial if N==1} ELSE BEGIN {perform 2 sub-transforms} N':=N/2; {size of sub-transforms} FOR n:=0 TO (N'-1) DO {perform N' DIF 'butterflies'} BEGIN fe[n]:= f[n]+f[n+N']; {even subset} fo[n]:=(f[n]-f[n+N'])*T(N,n); {odd subset} END; Fe:=DIF(N',fe); {even k} Fo:=DIF(N',fo); {odd k} FOR k':=0 TO (N'-1) DO BEGIN F[2*k' ]:= Fe[k']; {even k} F[2*k'+1]:= Fo[k']; {odd k} END; RETURN(F); END;This is simplest form of DIF implementation and directly reflects the mathematical derivation of the algorithm. The process of calculating the fe and fo components is conventionally referred to as a (DIF) 'butterfly', and is the basic primitive operation of the FFT. (Apparently, this name was aquired from certain diagramatic representations of this operation which resemble butterflies.)
DIF FFT Algorithmic Complexity (Why it's fast).
The algorithmic complexity of an FFT is usually quantified in terms of the total number of butterfly operations performed. Let this number be C(p) for a 2p point transform. Looking at the DIF routine above, it is easy to see that C(p) must satisfy the following recurrence relation:A Recursive 'In Place' DIF FFT Routine.
If you coded something like the above routine in a real programming language it would work fine. However, from an efficiency point of view it is somewhat less than ideal. Allocating local arrays on the stack will make this implementation fairly memory hungry, and the last loop in the above routine performs no useful numerical computation, it simply re-arranges values previously calculated.What if the last loop were somehow replaced by a simple catenation the results of the two sub-transforms? Say we put all the even k samples in the top half of the result and all the odd samples in the bottom half of the result. Treating k as a binary number, the least significant bit of k determines which 'half' of the result array the corresponding value resides in. The least significant bit of k becomes the most significant bit of the corresponding (binary) array index. Because the function is recursive, this bit swapping will occur for each sub-transform etc.. I.E. The array index is determined by bit reversing k. Doing this won't save any time, unless we can arrange that the catenation operation is actually performed implicitly by each sub-transform. This suggests that an 'in place' algorithm should be used (one which performs all necessary operations in a single array, rather than allocating temporary arrays on the stack). Looking at the form of the first loop in the above routine indicates how to do this, put the 'even' subset values back in f[n] (the top half) and put the 'odd' subset values back in f[n+N'] (the bottom half), then perform the DIF operation on each half. Pulling all these ideas together, we get a more efficient (recursive) in-place DIF routine:
{Perform in place DIF of N points starting at position BaseE DIF(0,N,f) performs DIF FFT on entire array f, N= size of f } PROCEDURE DIF(BaseE,N, VAR f); {f is an external array} LOCAL N',BaseO,n,e,o; IF N==1 THEN {do nothing} ELSE BEGIN N':=N>>1; {shift right to get size of sub-transforms} BaseO:=BaseE+N'; {split block into 2 halves} FOR n:=0 TO (N'-1) DO BEGIN e:= f[BaseE+n]+f[BaseO+n]; o:=(f[BaseE+n]-f[BaseO+n])*T(N,n); f[BaseE+n]:=e; f[BaseO+n]:=o; END; DIF(BaseE,N',f); {even sub-transform} DIF(BaseO,N',f); {odd sub-transform} END;This version of the DIF routine is a little simpler and more efficient than the first, but has the disadvantage that the output is in 'jumbly' (bit reversed) order. This may on may not be a serious problem, depending on what the output is to be used for and whether or not your processor/programming language supports bit reversed addressing (most DSP's do). If bit reversed addressing is not available then you may need to produce a bit reversed index look up table to access the output.
It is worth noting that this is the simplest formulation of the 'in-place' DIF algorithm. It takes normal order input and generates bit reversed order output. However, this is not fundamental to the algorithm, it is merely a consequence of the simplest implementation. It is possible to write a reverse order DIF algorithm FFT which takes bit reversed order input and generates normal order output. This requires the DIF FFT routine to be amended in two ways:
- Passing an additional parameter which specifies the spacing between elements in each sub-array to be transformed. In the simple code above, this is always 1. In the reverse order FFT, this will start at 1 and double for each sub transform. This parameter is also useful feature for multi-dimensional transforms.
- Since the input to each sub-transform is now in bit reversed order, the twiddle factors must also used in bit reversed order. This isn't difficult if the twiddle factors are taken from a table in bit reversed order, or if bit reversed addressing is available.
The 'Classic' Non-Recursive DIF FFT Routine.
For many processors/languages a recursive routine is not attractive, because of the overhead incurred by a procedure call. Be careful though, in reality an aversion to recursion could cost performance (see the note about cache efficiency). There is also a particular problem with DSP's which often have small hardware stacks, so deeply recursive routines will cause stack overflow. It is fairly easy to see that the above routine can be flattened into nested loops, to yield something resembling the 'classic' (non recursive) DIF FFT. Each DIF uses 2 'half size' DIF's, which in turn will use 4 'quarter size' DIF's, etc.. the last (not trivial) DIF will be for size 2. So, keeping notation consistent with the above recursive DIF, we get 3 nested loops:- Pass Loop: An N (=2p ) point transform will perform p 'passes', indexed by P=0..p-1.
- Block Loop: Pass will P operate on BP (=2P ) sub-blocks, each of size NP (=N/BP=2p-P), indexed by b=0..BP-1
- Butterfly Loop: Each sub-block operation will perform N'P (=NP/2=2p-P-1) butterflies, indexed by n=0..N'P-1.
{Perform in place DIF of 2^p points (=size of f)} PROCEDURE DIF(p,VAR f); LOCAL Bp,Np,Np',P,b,n,BaseE,BaseO,e,o; BEGIN {DIF} {initialise pass parameters} Bp:=1; {No. of blocks} Np:=1<<p; {No. of points in each block} {perform p passes} FOR P:=0 TO (p-1) DO BEGIN {pass loop} Np':=Np>>1; {No. of butterflies} BaseE:=0; {Reset even base index} FOR b:=0 TO (Bp-1) DO BEGIN {block loop} BaseO:=BaseE+Np'; {calc odd base index} FOR n:=0 TO (Np'-1) DO BEGIN {butterfly loop} e:= f[BaseE+n]+f[BaseO+n]; o:=(f[BaseE+n]-f[BaseO+n])*T(Np,n); f[BaseE+n]:=e; f[BaseO+n]:=o; END; {butterfly loop} BaseE:=BaseE+Np; {start of next block} END; {block loop} {calc parameters for next pass} Bp:=Bp<<1; {twice as many blocks} Np:=Np>>1; {half as many points in each block} END; {pass loop} END; {DIF}That's as far as we'll go on DIF code. Of course, if you look, there's still plenty of scope for further optimisation of this routine. We won't do it here for fear of obscuring the code even more. The remainder of this section is devoted to a few observations about the practical details of the twiddle factors, which so far have been largely neglected.
Twiddle Factor Tricks.
Recall the form of the twiddle factors:The next trick is to notice that often the twiddle factor will be either +1 or -j (it will never be -1 or +j). In such cases there is no need to do a full blown complex multiply (remember this requires 4 real multiplies and 2 real adds). Simple addition and subtraction will suffice. We shall call butterflies that use on or other of these twiddle factors 'trivial butterflies'. Specifically:
In the penultimate (N=4) pass the butterflies will use either T4(0)=1 or T4(1)=-j. So this pass also uses only trivial butterflies. As in the above case, in each of the previous (N>4, P<p-2) passes, there are BP (=2P) sub-blocks and therefore 2P butterflies which use a twiddle factor of -j (at n=N/4) .
We can now calculate exactly how many of these trivial butterflies Triv(p) there are in a typical DIF FFT for sizes >4 (p>2). This is the sum of the number of butterflies in the last 2 passes (the easy bit) and the number of trivial butterflies in all the other passes (the hard bit, but the result in Annex B is useful here):
The non-recursive routine presented above can be modified to exploit trivial butterflies by doing something like this:
- Make the last 2 passes 'specials' which have the appropriate twiddle factors (+1 or -j) 'hard wired' into the code.
- For the remaining passes (N>4, N'p>2) break the inner butterfly loop into two, each half of which has a 'special' as the first butterfly. The first loop special butterfly should use +1 as the twiddle factor. The second loop special butterfly should use -j as the twiddle factor.
As a final note, we can observe that there are further opportunities to exploit which we haven't considered: