Archive for the category “Codebits”

June 11th, 2008 at 11:03 am

Shell script to optimize all tables in all databases (MySQL)

If you have many databases with many write operations, it may be that the table overhead takes a good amount of space. (This is due to the fact that MySQL doesn't free the space of deleted entries.) With "optimizing" the tables, you can free that space.

Save the following script as /usr/local/sbin/optimizealltables.sh, make it chmod 700 (very important!), then replace YOURPASSWORD with your root MySQL password.

CODE:
  1. #!/bin/bash
  2.  
  3. MYSQL_LOGIN='-u root --password=YOURPASSWORD'
  4.  
  5. for db in $(echo "SHOW DATABASES;" | mysql $MYSQL_LOGIN | grep -v -e "Database" -e "information_schema")
  6. do
  7.         TABLES=$(echo "USE $db; SHOW TABLES;" | mysql $MYSQL_LOGIN |  grep -v Tables_in_)
  8.         echo "Switching to database $db"
  9.         for table in $TABLES
  10.         do
  11.                 echo -n " * Optimizing table $table ... "
  12.                 echo "USE $db; OPTIMIZE TABLE $table" | mysql $MYSQL_LOGIN >/dev/null
  13.                 echo "done."
  14.         done
  15. done

April 16th, 2008 at 11:20 am

Clear a sized select field

If you have have a select form element with a size attribute, one common option for the user is to leave it empty (especially in combination with multiple). The problem is, as soon as one or more options are selected, it is quite impossible in most browsers, to not select anything at all. And even if there is a way, it is not easy to accomplish. Try for yourself to deselect all items:

With a little JavaScript magic, we can offer a button to clear the select field:

JavaScript:
  1. function nl_clear_select(element)
  2. {
  3.     var opt_length = document.getElementById(element).options.length;
  4.     for (var i = 0; i <opt_length; i++)
  5.         document.getElementById(element).options[i].selected = false;
  6. }

Now try again to clear the select field. Hint: clicking on "Clear selection" will help a lot. ;)

Clear selection

Neat, eh?

April 10th, 2008 at 12:14 pm

Get radio button value in JavaScript

Here's how to get the currently checked value of radio button section. The parameter elementName is the name attribute of the radio input.

JavaScript:
  1. function getRadioValue(elementName)
  2. {
  3.     var element = document.getElementsByName(elementName);
  4.     var bt_count = element.length; // can't use element.length in the loop, as it would decrement
  5.  
  6.     for (var i = 0; i <bt_count; i++)
  7.         if (element[i].checked == true)
  8.             return element[i].value;
  9. }

April 3rd, 2008 at 12:06 pm

Calculate interest rates with a shell script

If you put your cash to a bank account, you will want to know how much money you get with a certain amount at a given rate within a given period. Save the following Bash script as /usr/local/bin/loancalc (or something like that), make it executable, and you will be able to calculate the return on your investments with a single one-liner.

CODE:
  1. #!/bin/bash
  2.  
  3. function calc()
  4. {
  5.     return $(echo "scale=$2; $1" | bc)
  6. }
  7.  
  8. if [ "$1" == "-h" ] || [ "$1" == "--help" ]; then
  9.     echo "$0 calculates the interest loan of a given amount with a given rate for a given duration."
  10.     echo "Usage: $0 AMOUNT RATE DURATION"
  11.     exit 0
  12. fi
  13.  
  14. if [ -z "$3" ]; then
  15.     echo "Please enter the amount, the rate and the duration (in this order)."
  16.     exit 1
  17. fi
  18.  
  19. AMOUNT=$1
  20. ZINS=$2
  21. DURATION=$3
  22.  
  23. echo "Investment: $AMOUNT bucks at a rate of $ZINS% for $DURATION years."
  24. echo "          Loan            Total"
  25.  
  26. for i in $(seq 1 $DURATION); do
  27.     INTERESTLOAN=$(echo "scale=10; ($AMOUNT/100)*$ZINS" | bc)
  28.     AMOUNT=$(echo "scale=10; $AMOUNT+$INTERESTLOAN" | bc)
  29.     printf "Year ${i} %8.2f " $INTERESTLOAN; printf " %14.2f\n" $AMOUNT;
  30. done
  31.  
  32. printf "Final amount: %1.2f bucks.\n" $AMOUNT

For example:

CODE:
  1. you@yourmachine ~ $ loancalc 3000 3.5 5
  2. Investment: 3000 bucks at a rate of 3.5% for 5 years.
  3.           Loan            Total
  4. Year 1   105.00         3105.00
  5. Year 2   108.68         3213.68
  6. Year 3   112.48         3326.15
  7. Year 4   116.42         3442.57
  8. Year 5   120.49         3563.06
  9. Final amount: 3563.06 bucks.

December 18th, 2007 at 10:07 am

Improve loading speed of webpages by compressing HTML

Here's a simple HTML "compressor" in PHP, which will reduce the size of HTML served to the client by 10 to 20 percent, depending on your indentation style and commenting. If many of your readers have lousy bandwidth, the slight overhead of this method is worth it.

PHP:
  1. <?php
  2.     function compress($content)
  3.     {
  4.         $content = preg_replace('/[\n\t\s]+/s', ' ', $content);
  5.         $content = preg_replace('/<!--.*?-->/s', '', $content);
  6.         return $content;
  7.     }
  8.  
  9.     ob_start();
  10.     require "/var/www/htdocs/somefile.php";
  11.     $content = ob_get_contents();
  12.     ob_end_clean();
  13.  
  14.     echo compress($content);
  15. ?>

By the way, if you have a rather hungry dynamic application (e.g. WordPress with certain plugins) on a rather weak server, consider using a caching solution like 1 Blog Cacher, so you don't have to regenerate the pages everytime somebody retrieves them. And, of course, consider using output gzip compression -- be it via webserver modules such as mod_gzip/mod_deflate or based on your web application.

December 15th, 2007 at 5:26 pm

Count over two SQL tables

A bit of SQL that saved my butt lately: Have you ever needed to relate a value from one table to the count of another value in another table? Given you have two tables, one for a timetable, the other for tickets, and you want to find out how many tickets are sold for each tour in the timetable, the following will give it to you (tours.tour_id is related to tickets.ticket_tour_id, who'd have thought of that):

MySQL:
  1. SELECT DISTINCT tour_id, COUNT(ticket_tour_id)
  2. FROM tours
  3. RIGHT JOIN tickets
  4. ON tour_id = ticket_tour_id
  5. GROUP BY ticket_tour_id
  6. ORDER BY departure;

December 11th, 2007 at 7:17 am

Calculating the V.A.T. amount from the total price

Sometimes you need to calculate the V.A.T. (for Germans: MwSt.) from a given total price. This is, for example, if you charge an arbitrary total price, but need to display the V.A.T. percentage along with the V.A.T. amount. For this purpose, you can use the following code:

PHP:
  1. <?php
  2.    
  3.     function calc_vat_amount_from_total($total, $vat)
  4.     {
  5.         $total = (float)$total;
  6.         $vat = (float)$vat;
  7.  
  8.         if (!$total || !$vat) return false;
  9.  
  10.         $net = $total / (float)('1.'.$vat);
  11.         $vatAmount = $total - $net;
  12.  
  13.         return sprintf("%01.2f", $vatAmount);
  14.     }
  15.  
  16.     $total = '35.00'; // It's a string, but could also be a float or int.
  17.     $vat = '19'; // dito
  18.  
  19.     $vat_amount = calc_vat_amount_from_total($total, $vat);
  20.     echo "The ticket fare of $total &#8364; contains $vat% V.A.T. ($vat_amount &#8364;).";
  21.  
  22. ?>