drop function if exists luhn;
drop function if exists luhn_check;
delimiter //
-- Function that calculates a Luhn (mod 10) check digit from a numeric string.
-- The behavior is undefined if the string contains anything else than digits.
-- Assumes that the string does not have a check digit added yet, so it starts
-- with a weight of 2 at the last digit.
create function luhn(p_number varchar(31))
returns char(1)
sql security invoker
begin
declare i, mysum, r, weight int;
set weight = 2;
set mysum = 0;
set i = length(p_number);
while i > 0 do
set r = substring(p_number, i, 1) * weight;
set mysum = mysum + if(r > 9, r - 9, r);
set i = i - 1;
set weight = 3 - weight;
end while;
return (10 - mysum % 10) % 10;
end //
-- Check if a numeric string has a valid check digit. Does this by cutting off
-- the last digit, recalculating the Luhn check digit, and comparing the strings.
create function luhn_check(p_number varchar(32))
returns boolean
sql security invoker
begin
declare luhn_number varchar(32);
set luhn_number = substring(p_number, 1, length(p_number) - 1);
set luhn_number = concat(luhn_number, luhn(luhn_number));
return luhn_number = p_number;
end //
delimiter ;
Author Archives: Mats Gefvert
Common ffmpeg parameters
-codecs Display codecs
-formats Display formats
-f fmt Force format "fmt"
-i filename Set input file name
-y Overwrite output file
-t secs Force duration to specific length (hh:mm:ss[.xxx] syntax works)
-fs limit Set file size limit
-ss secs Seek to given time position (hh:mm:ss[.xxx] syntax works)
-target type Specify target type ("vcd", "svcd", "dvd", "dv", "dv50", "pal-vcd" etc)
All the format options are set automatically
Video
-b bitrate Video bitrate in bps
-r fps Set frame rate (default 25)
-s WxH Set frame size (default same as source)
-aspect aspect Set aspect ratio (4:3, 16:9 etc)
-vn Disable video
-sameq Same quality as input (implies VBR)
-pass n Multipass rendering (1 or 2)
-vcodec Force video codec
Audio
-ar freq Audio frequency (default 44100 Hz)
-ab bitrate Audio bitrate in bps (default 64k)
-aq quality Audio quality (codec-specific, VBR)
-ac channels Audio channels
-an Disable audio
-acodec Force audio codec
Subtitles
-scodec Force subtitle codec ("copy" to copy stream)
-sn Disable subtitles
A Small Script to Compress Movies for Cellphones
I wrote this small script for Windows to compress movies (avi, mkv etc) down to cell phone format. The encoding isn’t great, but the average two-hour movie compresses down to just about ~100 MB, which is really nice. Works fine on Nokia N85. Edit to suit your needs. It relies on ffmpeg, which you can find Windows binary downloads for here and there. Google for it, kid, google for it!
Oh, it also requires cygwin, for the perl interpreter. (Or ActivePerl, I suppose.)
ff-m4v.cmd:
@echo off
set CYGWIN=nodosfilewarning
for %%F in (%*) do (
echo.
echo ######## %%F #########
echo.
perl %~dpn0.pl %%F
)
ff-m4v.pl:
$in = shift; $data = `ffmpeg -i '$in' 2>&1`; $out = $in; $out =~ s/\.[A-Za-z0-9]+$/\.m4v/; ($x, $y) = $data =~ /Video:.*?(\d+)x(\d+)/i; $dx = 320 / $x; $dy = 240 / $y; $d = $dx < $dy ? $dx : $dy; $dim = int($d * $x) . 'x' . int($d * $y); $opt = "ffmpeg -i '$in' -f mp4 -vcodec mpeg4 -b 80000 -r 12 -acodec aac -ar 16000 -ab 48000 -ac 1 -threads 2 -y -s $dim '$out'"; print "$opt\n"; system($opt);
The parameters evaluate to mpeg4 encoding, 80 kbit/s bitrate for video, 12 frames per second; AAC encoding with 48 kbit/s bitrate, mono sound. It compresses the movie down to a maximum of 320x240 pixels, but preserves aspect ratio (effectively becoming 320x196, 320x160 or whatever). If you want to use 2-pass encoding, it's easy; just repeat the system($opt) call with "-pass 1" and "-pass 2" parameters.
Put both in the same folder, make sure ffmpeg.exe is in the system path, and run "ff-m4v *.avi".
CMD File to Run the Same Programs at Work Every Day
I usually sign on to work by starting at least four different programs: Microsoft Lync, Miranda, a SIP telephone, and a little break clock. I used to have a Python script for it, but I thought that installing ActivePython on a Windows machine just to start four programs is a bit of an overkill. So I wrote a CMD file instead. It’s really amazing what you can beat the old CMD interpreter into doing.
startToday.cmd:
@echo off
tasklist /nh > __tasklist.txt
for /f "delims=" %%F in (startToday.files) do (
findstr /b /i "%%~nxF" __tasklist.txt > nul
if errorlevel 1 (
echo starting %%F
start "" "%%F"
)
)
del /q /f __tasklist.txt
startToday.files:
C:\Program Files\CounterPath\X-Lite\x-lite.exe C:\Program Files\Miranda IM\miranda32.exe C:\Program Files\Microsoft Lync\communicator.exe C:\Home\stuff\software projects\BreakTime\BreakTime.exe
Voila!
Making Beautiful Lists
This is a nice way to make beautiful lists. Take any old list of unordered elements, for instance:
- Apples
- Bananas
- Blistering barnacles
- Gargoyles
- Oranges
- Pears
- Sunfruit
Looks good? Sure. But sometimes, you want it horizontally. Let’s add the following style sheet to it.
ul { list-style: none; padding: 0; margin: 0; }
ul li { list-style: none; padding: 0; margin: 0; display: inline; }
ul li:after { content: '\B7'; padding: 0 0.2em 0 0.5em; }
ul li:last-child:after { content: '' }
And what do we get? Something as beautiful as this:
- Apples
- Bananas
- Blistering barnacles
- Gargoyles
- Oranges
- Pears
- Sunfruit
A nice, horizontal list; and the best thing about it, is that there are no little dots in the HTML code, no handling for first or last elements (no ul class=”last”), nothing. Just pure css. And, of course, each element can be styled, you can make links, or any old thing. Seems to work fine in Firefox and Chrome; IE8 doesn’t seem to get the last “ul li:last-child:after” element, but all you get is a little dot after the last element. Worse things could happen.
Backup up MySQL Tables Using Only CMD.EXE and 7-zip
A small batch file I wrote today, to back up MySQL databases, table by table.
So many times have I needed to restore only a specific table, and yet it’s so difficult to dig out the correct table from the whole database backup file (or even worse, server backup file).
This little file will store the whole database/server in individual files, and if you run it on a daily basis, will keep history in “backup.n” directories.
@echo off rem Enable delayed expansion - otherwise the backup.n folder renaming won't work setlocal enabledelayedexpansion rem Change to the script's home folder %~d0 cd %~p0 rem Rotate previous backup folders if exist backup.9 rd /s /q backup.9 for /l %%i in (8 -1 1) do ( set /a j=%%i + 1 if exist backup.%%i move backup.%%i backup.!j! > nul ) if exist backup move backup backup.1 > nul md backup rem Change these to reflect your MySQL connection parameters set OPT=-ubackup -pbackup -hlocalhost rem List all the databases and process them mysql %OPT% -e"show databases" --skip-column-names -B | findstr /v "information_schema" > _db.txt for /f %%d in (_db.txt) do call :backupdb %%d rem Clean up, clean up, everybody wants to clean up del /f /q _dbt.txt del /f /q _db.txt dir backup goto :eof :backupdb rem List the tables in the current database echo %1 mysql %OPT% -e"show tables" --skip-column-names -B %1 > _dbt.txt md backup\work rem Dump each table into an SQL file echo - dumping data for /f %%t in (_dbt.txt) do mysqldump --opt %OPT% -rbackup\work\%%t.sql %1 %%t rem Compress them with 7-zip into a single zip file echo - compressing cd backup\work ..\..\7z -y a ..\%1.zip * > nul rem Clean up cd .. rd /s /q work cd .. echo. goto :eof
Download 7-zip, extract 7z.exe and 7z.dll and put in the same folder as the “backup.cmd” file above, and you should be good to go. Change the -u and -p parameters in the “set OPT” statement to reflect the login settings for your database server.
Measuring the Cool-off Effect of Water in Different Types of Containers
The question was formed recently due to a conversation with a fellow tea-drinker. Does tea in a large cup cool off quicker – or slower – than in a small cup? I thought previously that the greater area in the larger teacup would cause a quicker cool-off than the small area of a smaller teacup. However, the volume is also larger, so how does that effect the cool-off?
One possible alternative is to consider the growth of area versus volume. Since area grows by O(n^2), but volume grows by O(n^3), it might seem that the larger the container, the more energy that needs to irradiate through a smaller area. In general, this theory holds with for instance animals – mice needs to eat much more often than elephants, because they have a much larger skin surface compared to their volume. An elephant the size of a mouse would die – it would never be able to feed itself quickly enough the replace the heat loss through the skin.
So, the following experiment was set up. Hot water at a starting temperature of 96 C was poured into different containers:
- Cup A – a small, paper cup for holding “Glögg”. Diameter 6cm, 1x water content.
- Cup B – a large McDonalds coffee mug (official McD size: “medium”). Diameter 9cm, 2x water content.
- Cup C – a medium-size ceramic coffee mug. Diameter 8cm, 1.3x water content.
- Cup D – a large (=tall) glass. Diameter 7cm, 2x water content.
Sample data was collected over 15 minutes using a steak thermometer. (Not the world’s most precise, mind you.)
The results are as follows (time is in UTC):

Surprisingly, the container that held its best was the McDonalds coffee mug. The water in the McDonalds mug was consistently hotter than in the others.
Not surprisingly, the small paper Glögg cup was a total failure – dropping down below the measurable 55 degrees Celsius on the steak thermometer, and had to be estimated to about 52.
Unfortunately, it seems that the data collected so far fails to support any conclusive theory. It seems to be largely dependent on the materials of the container, as well as “other factors”, not determined by this study.
Persistence
/** * NF_Persistence * * Agent Smith: "Why, Mr. Anderson, why? Why do you persist?" * Neo: "Because I choose to." * * PHP Version 5 * * @category NiftyFramework * @package NiftyFramework * @subpackage Database * @author Mats Gefvert* @license http://www.sun.com/cddl/ Common Development and Distribution License */ class NF_PersistenceRelationMap { ....
I make myself laugh sometimes. Is that a good sign? :)
A Little Drummer Boy
I think my favorite Christmas song (yeah, there you go, I’m already singing Christmas songs…) is the one about the little drummer boy.
Come, they told me, pa rum pum pum pum
A newborn King to see, pa rum pum pum pum
Our finest gifts we bring, pa rum pum pum pum
To lay before the King, pa rum pum pum pum
Rum pum pum pum, rum pum pum pum
So to honor him, pa rum pum pum pum
When we come.
When I went through bible school in 1994-95, we all had ideals that soared mile-high. We were going to be the new Benny Hinns, ministers of the faith, apostles and prophets (like all bible school students, I suppose) and shake the whole world upside down.
I think, through the years, at least I have maybe cooled down a little bit. Those lofty ideals seem … surprisingly not remote, but actually rather unimportant. It is not important that I stand in big arenas and preach to tens of thousands of people. It is not important if I start a huge ministry. Riches, honor and fame, even in the subtle shape of Christian ministry, is not important.
It is actually quite liberating to realize that I am unimportant. There is a sense of freedom in knowing that my name will never be famous. I grew up in a small house, and maybe I’ll die in a small house – it doesn’t bother me. Maybe I’ll never be rich. Maybe I will only touch a few people’s lives in all my days on earth. It is not important.
What really matters is our devotion to Him – to God, our heavenly father. And as little as I am, with the few things I can do or say, if I can only do it for him, then it will matter for eternities to come:
I played my drum for him, pa rum pum pum pum
I played my best for him, pa rum pum pum pum
Rum pum pum pum, rum pum pum pum
Then he smiled at me, pa rum pum pum pum
Me and my drum.
Such as I have, I give. And even if all I can ever pull off is a small concert for him on my cheap little drum, he still deserves my very best. So I play for him, tears in my eyes, as well as I can on my drum. And if I do that, if I give him my very best, as minute as it still may seem… I know he will smile at me; and in that smile he will justify my entire existence.
Does the Star-Spangled Banner Yet Wave?
Sometimes, I listen to people singing the Star-Spangled Banner – you know, at sports events, stuff like that. Which is great and all, I think it’s a great song, but why do people only sing the first verse?
In this case, it goes like this:
O, say, can you see, by the dawn’s early light
What so proudly we hailed at the twilight’s last gleaming?
Whose broad stripes and bright stars, through the perilous fight,
O’er the ramparts we watched, were so gallantly streaming?
And the rockets’ red glare, the bombs bursting in air,
Gave proof through the night that our flag was still there.
O, say, does that star-spangled banner yet wave
O’er the land of the free and the home of the brave?
It ends with a question – does the star-spangled banner yet wave? And in a sense, it is a fitting question if you look at the United States of today. Since we omit the next three verses and never sing it, we take out the good stuff from it, bringing to mind Alexis de Tocqueville’s famous comment “America is great because she is good, and when she ceases to be good, she will cease to be great.”
So it ends with a question – and this question has resounded over America for a great many years. Does the banner yet wave? Is she intact? Is she still there, the beacon of freedom through the world, shining gallantly for liberty and justice as the red, white and blue snaps in the wind?
It was with the same amount of tremor and hesitation that Francis Scott Key watched through the night, seeking indication of whether the British had captured Fort McHenry or not. And the jubilant sight he beheld when the large flag was raised in the early morning is recorded in the following verses.
On the shore, dimly seen through the mists of the deep,
Where the foe’s haughty host in dread silence reposes,
What is that which the breeze, o’er the towering steep,
As it fitfully blows, half conceals, half discloses?
Now it catches the gleam of the morning’s first beam,
In full glory reflected now shines in the stream:
‘Tis the star-spangled banner!! Oh long may it wave!
O’er the land of the free and the home of the brave.And where is that band who so vauntingly swore
That the havoc of war and the battle’s confusion,
A home and a country should leave us no more?
Their blood has washed out their foul footsteps’ pollution!
No refuge could save the hireling and slave
From the terror of flight, or the gloom of the grave!
And the star-spangled banner in triumph doth wave
O’er the land of the free and the home of the brave.
And it ends with this benediction.
O, thus be it ever, when freemen shall stand
Between their loved home and the war’s desolation!
Blest with victory and peace, may the heav’n rescued land
Praise the Power that hath made and preserved us a nation.
Then conquer we must, when our cause it is just,
And this be our motto: ‘In God is our trust.’
And the star-spangled banner in triumph shall wave
O’er the land of the free and the home of the brave!
It is a terrible tragedy when the divine intervention in creating a new country, a home for the refugees of the world, is sacrificed on the altar of political correctness. So the question still stands. “Does the star-spangled banner yet wave?”
Maybe Heaven itself will answer that question. “Yet a little while”, a soft voice might whisper in the night, “yet a little while.”