Encode Array as String
I wanted to store an array in a cookie, so I wrote these two functions:
return base64_encode(serialize($data));
}
function decode_arr($data) {
return unserialize(base64_decode($data));
}
jQuery Select Text Range
Here's a jQuery function I wrote which you can use to select a range of text in an input field.
return this.each(function() {
if(this.setSelectionRange) {
this.focus();
this.setSelectionRange(start, end);
} else if(this.createTextRange) {
var range = this.createTextRange();
range.collapse(true);
range.moveEnd('character', end);
range.moveStart('character', start);
range.select();
}
});
};
Simple Rounded Corners with CSS
I know there are umpteen billion tutorials on rounded corners out there, but here's an easy way that I like to do it. Requires only one image, and allows you to nudge your text as close to the corners are you like.
If you want a 3px radius corner, have a black background, and white foreground, you need to create a 6x6 (i.e. radius*2) image of a white circle on a black background. This method won't support transparency unfortunately.
The HTML:
<div id="tl"></div><div id="tr"></div><div id="bl"></div><div id="br"></div>
Your content here.
</div>
The CSS:
position:relative;
background-color: #fff;
width:600px;
height:300px;
}
#tl,#tr,#bl,#br{
background: #000 url(images/circle.gif);
width:3px;
height:3px;
position:absolute;
}
#tl{top:0;left:0}
#tr{top:0;right:0;background-position:3px 0}
#bl{bottom:0;left:0;background-position:0 3px}
#br{bottom:0;right:0;background-position:3px 3px}
Adjust all the "3px"s to match your radius, and modify the background attribute to meet your needs, and style content however you want. You probably want to put some padding on there. The important thing is that #content has position:relative so that the corners are aligned to the content box rather than the page.
I used this technique on my personal site, mnbayazit.com.
Vertically center text with CSS
Anyone who has used CSS for awhile knows that vertically aligning stuff isn't easy. Vertically aligning just text, however, is pretty simple. If your container is 30px tall, just set the line-height to 30px too and your text will be perfectly centered! Hurray! This only works for a single line of text however... if you want more, you're probably better off fighting with margins, padding, or absolute positioning.
Draw an Unfilled Circle
OpenGL doesn't seem to have any functions for drawing an unfilled circle, so you can use this code instead. It uses lines, so you can adjust the line thickness with glLineWidth and anti-alias it with glEnable(GL_LINE_SMOOTH) if you want.
static const double inc = M_PI / 12;
static const double max = 2 * M_PI;
glBegin(GL_LINE_LOOP);
for(double d = 0; d < max; d += inc) {
glVertex2f(cos(d) * r + x, sin(d) * r + y);
}
glEnd();
}
If you want a filled circle, I would suggest you just set glPointSize to whatever size you want, and then plot a single point with glBegin(GL_POINTS) where ever you want your circle. Otherwise, you can use the above code with GL_POLYGON if you want more control. If you want a smoother circle, decrease the size of "inc".
Base62 Encode
If you have large integers and you want to shrink them down in size for whatever reason, you can use this code. Should be easy enough to extend if you want even higher bases (just add a few more chars and increase the base).
/**
* Converts a base 10 number to any other base.
*
* @param int $val Decimal number
* @param int $base Base to convert to. If null, will use strlen($chars) as base.
* @param string $chars Characters used in base, arranged lowest to highest. Must be at least $base characters long.
*
* @return string Number converted to specified base
*/
function base_encode($val, $base=62, $chars='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') {
if(!isset($base)) $base = strlen($chars);
$str = '';
do {
$m = bcmod($val, $base);
$str = $chars[$m] . $str;
$val = bcdiv(bcsub($val, $m), $base);
} while(bccomp($val,0)>0);
return $str;
}
/**
* Convert a number from any base to base 10
*
* @param string $str Number
* @param int $base Base of number. If null, will use strlen($chars) as base.
* @param string $chars Characters use in base, arranged lowest to highest. Must be at least $base characters long.
*
* @return int Number converted to base 10
*/
function base_decode($str, $base=62, $chars='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') {
if(!isset($base)) $base = strlen($chars);
$len = strlen($str);
$val = 0;
$arr = array_flip(str_split($chars));
for($i = 0; $i < $len; ++$i) {
$val = bcadd($val, bcmul($arr[$str[$i]], bcpow($base, $len-$i-1)));
}
return $val;
}
(code updated 26-Aug-2011 for arbitrary precision using BC Math)
Easy Current Page Tab
So, you have a bunch of links along the top of your page, and you want to highlight the current one when you click on it. Easy enough to do if you copy and paste the entire navbar onto every page and add some CSS to the current tab, but that's just bad practice! You want to throw the navbar in a layout, and still have it work.
Well, here's an easy solution! Just drop this in your layout:
<?php
$pages = array(
'url1' => 'linktext1',
'url2' => 'linktext2',
'url3' => 'linktext3'
);
foreach($pages as $url => $name) {
if($url == $currentPage) echo '<li class="current">'.$name.'</li>';
else echo '<li><a href="'.$url.'">'.$name.'</a></li>';
}
?>
</ul>
And make sure you set $currentPage properly. You could use $_SERVER['REQUEST_URI'] if your URLs are in the same format (leading and trailing slashes if necessary).
Update: Made a little wrapper function out of this too.
global $currentPage;
foreach($links as $name => $url) {
$class = strtolower($name);
$class = preg_replace('`[^a-z\s]`', '', $class);
$class = preg_replace('`\s+`', '-', $class);
$class = trim($class, '-');
if(ltrim($url,'/') == $currentPage) echo '<li class="',$class,'"><a href="',$url,'" class="selected">',$name,'</a></li>';
else echo '<li class="',$class,'"><a href="',$url,'">',$name,'</a></li>';
}
}
This one adds a class to each <li> too so you can style it in your CSS.
Human-readable file size in C
I did a quick search on Google and couldn't find any code that did this in C/C++, so here's my contribution for the day. Just remember the allocate enough space in the buffer -- about 10 chars should be enough.
int i = 0;
const char* units[] = {"B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"};
while (size > 1024) {
size /= 1024;
i++;
}
sprintf(buf, "%.*f %s", i, size, units[i]);
return buf;
}
// usage
struct stat info;
char buf[10];
lstat("somefile.txt", &info);
printf("File size: %s\n", readable_fs(info.st_size, buf));
Extract (almost) any archive type
After getting tired of trying to remember "tar xvzf", I wrote a little script for extracting almost any file type via the linux command-line. You can copy and paste this script into a text editor like gedit and save it to "/usr/local/bin" for convenience. I called mine "untar" since it doesn't seem to be taken. Remember to `chmod +x
me=`basename $0`
if [ $# -eq 0 ]; then
echo "usage: $me <files...>"
fi
for file in $@; do
bn=`basename $file`
case $file in
*.tar)
tar xvf $file;;
*.tar.gz|*.tgz|*.tar.Z|*.tar.z)
tar xvzf $file;;
*.tar.bz2)
tar xvjf $file;;
*.zip)
unzip $file;;
*.rar)
unrar x $file;;
*)
echo "$me: $bn: unkown filetype";;
esac
done
Draw IplImage
OpenCV stores images in a data structure called IplImage. They provide methods for rendering it to the screen, but if you want to use OpenGL instead (which should be faster and gives you more flexibility), I wrote the following code. It should be a little faster than loading the IplImage into a texture first, and then drawing it (if you have to do this every frame).
{
GLenum format;
switch(image->nChannels) {
case 1:
format = GL_LUMINANCE;
break;
case 2:
format = GL_LUMINANCE_ALPHA;
break;
case 3:
format = GL_BGR;
break;
default:
return;
}
glRasterPos2i(x, y);
glPixelZoom(xZoom, yZoom);
glDrawPixels(image->width, image->height, format, GL_UNSIGNED_BYTE, image->imageData);
}
It should be pretty straight forward to use. Handles IplImages with 1 or 3 layers. Should work with 2 layers too, but I haven't needed or found an example of this.