JavaScript: Soundex implementation

There is a special algorithm for comparision strings, which sound similar (Soundex).

Here is JavaScript Soundex implementation:

function soundex ( s_src )
{
var s_rez = "0000" ;
var new_code, prev, idx

a_codes = { "bfpv": 1, "cgjkqsxz":2, "dt": 3, "l": 4, "mn": 5, "r": 6 };

s_src = s_src.toLowerCase().replace(/ /g,"")

if ( s_src.length < 1) {
return(s_rez);
}

s_rez = s_src.substr(0,1);
prev = "0";

for ( idx = 1 ; idx < s_src.length ; idx++) {
new_code = "0";
cur_char = s_src.substr(idx,1)

for (s_code in a_codes)
if (s_code.indexOf(cur_char) >= 0)
{ new_code = a_codes[ s_code ] ; break ; }

if (new_code != prev && new_code != "0" ) {
s_rez += new_code;
}

prev = new_code;
}

s_rez = s_rez + "0000"

return s_rez.substr(0,4);
}

Topics: javascript | No Comments »

Dynamic image resizing in PHP

Via Darren Hoyt we found a reference to TimThumb, a quick and fast PHP script for on-the-fly image resizing. Once the script is on the server, and named timthumb.php, you can use the following reference to launch it:
<img src="/scripts/timthumb.php?src=/images/whatever.jpg&h=150&w=150&zc=1" alt="" />
Here's the source code for timthumb.php:

// TimThumb script created by Tim McDaniels and Darren Hoyt with tweaks by Ben Gillbanks
// http://code.google.com/p/timthumb/

// MIT License: http://www.opensource.org/licenses/mit-license.php

/* Parameters allowed: */

// w: width
// h: height
// zc: zoom crop (0 or 1)
// q: quality (default is 75 and max is 100)

// HTML example:

if( !isset( $_REQUEST[ "src" ] ) ) { die( "no image specified" ); }

// clean params before use
$src = preg_replace( "/^(\.+(\/|))+/", "", $_REQUEST['src'] );
$src = preg_replace( '/^(s?f|ht)tps?:\/\/[^\/]+/i', '', $src );
$new_width = preg_replace( "/[^0-9]/", "", $_REQUEST[ 'w' ] );
$new_height = preg_replace( "/[^0-9]/", "", $_REQUEST[ 'h' ] );
$zoom_crop = preg_replace( "/[^0-9]/", "", $_REQUEST[ 'zc' ] );

if( !isset( $_REQUEST['q'] ) ) { $quality = 80; } else { $quality = preg_replace("/[^0-9]/", "", $_REQUEST['q'] ); }

// set path to cache directory (default is ./cache)
// this can be changed to a different location
$cache_dir = './cache';

// get mime type of src
$mime_type = mime_type( $src );

// check to see if this image is in the cache already
check_cache( $cache_dir, $mime_type );

// make sure that the src is gif/jpg/png
if( !valid_src_mime_type( $mime_type ) ) {
$error = "Invalid src mime type: $mime_type";
die( $error );
}

// check to see if GD function exist
if(!function_exists('imagecreatetruecolor')) {
$error = "GD Library Error: imagecreatetruecolor does not exist";
die( $error );
}

// set document root
$doc_root = $_SERVER['DOCUMENT_ROOT'];

// get path to image on file system
$src = $doc_root . '/' . $src;

if(strlen($src) && file_exists( $src ) ) {

// open the existing image
$image = open_image($mime_type, $src);
if ($image === false) { die ('Unable to open image : ' . $src ); }

// Get original width and height
$width = imagesx($image);
$height = imagesy($image);

// generate new w/h if not provided
if($new_width && !$new_height) {
$new_height = $height * ($new_width/$width);
}
elseif($new_height && !$new_width) {
$new_width = $width * ($new_height/$height);
}
elseif(!$new_width && !$new_height) {
$new_width = $width;
$new_height = $height;
}

// create a new true color image
$canvas = imagecreatetruecolor($new_width, $new_height);

if( $zoom_crop ) {

$src_x = $src_y = 0;
$src_w = $width;
$src_h = $height;

$cmp_x = $width / $new_width;
$cmp_y = $height / $new_height;

// calculate x or y coordinate and width or height of source

if ( $cmp_x > $cmp_y ) {

$src_w = round( ( $width / $cmp_x * $cmp_y ) );
$src_x = round( ( $width - ( $width / $cmp_x * $cmp_y ) ) / 2 );

}
elseif ( $cmp_y > $cmp_x ) {

$src_h = round( ( $height / $cmp_y * $cmp_x ) );
$src_y = round( ( $height - ( $height / $cmp_y * $cmp_x ) ) / 2 );

}

imagecopyresampled( $canvas, $image, 0, 0, $src_x, $src_y, $new_width, $new_height, $src_w, $src_h );

}
else {

// copy and resize part of an image with resampling
imagecopyresampled( $canvas, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height );

}

// output image to browser based on mime type
show_image( $mime_type, $canvas, $quality, $cache_dir );

// remove image from memory
ImageDestroy( $canvas );

} else {

if( strlen( $src ) ) { echo $src . ' not found.'; } else { echo 'no source specified.'; }

}

function show_image ($mime_type, $image_resized, $quality, $cache_dir) {

// check to see if we can write to the cache directory
$is_writable = 0;
$cache_file_name = $cache_dir . '/' . get_cache_file();

if( touch( $cache_file_name ) ) {
// give 666 permissions so that the developer
// can overwrite web server user
chmod( $cache_file_name, 0666 );
$is_writable = 1;
}
else {
$cache_file_name = NULL;
header('Content-type: ' . $mime_type);
}

if(stristr( $mime_type, 'gif' ) ) {
imagegif( $image_resized, $cache_file_name );
}
elseif( stristr( $mime_type, 'jpeg' ) ) {
imagejpeg( $image_resized, $cache_file_name, $quality );
}
elseif( stristr( $mime_type, 'png' ) ) {
imagepng( $image_resized, $cache_file_name, ceil( $quality / 10 ) );
}
if( $is_writable ) { show_cache_file( $cache_dir, $mime_type ); }
exit;

}

function open_image ($mime_type, $src) {

if(stristr($mime_type, 'gif')) {
$image = imagecreatefromgif($src);
}
elseif(stristr($mime_type, 'jpeg')) {
$image = imagecreatefromjpeg($src);
}
elseif(stristr($mime_type, 'png')) {
$image = imagecreatefrompng($src);
}
return $image;

}

function mime_type ($file) {

$frags = split("\.", $file);
$ext = strtolower( $frags[ count( $frags ) - 1 ] );
$types = array(
'jpg' => 'image/jpeg',
'jpeg' => 'image/jpeg',
'png' => 'image/png',
'gif' => 'image/gif',
'bmp' => 'image/bmp',
'doc' => 'application/msword',
'xls' => 'application/msword',
'xml' => 'text/xml',
'html' => 'text/html'
);
$mime_type = $types[$ext];
if(!strlen($mime_type)) { $mime_type = 'unknown'; }
return($mime_type);

}

function valid_src_mime_type ( $mime_type ) {

if( preg_match( "/jpg|jpeg|gif|png/i", $mime_type ) ) { return 1; }
return 0;

}

function check_cache ( $cache_dir, $mime_type ) {

// make sure cache dir exists
if(!file_exists($cache_dir)) {
// give 777 permissions so that developer can overwrite
// files created by web server user
mkdir( $cache_dir );
chmod( $cache_dir, 0777 );
}
show_cache_file( $cache_dir, $mime_type );

}

function show_cache_file ( $cache_dir, $mime_type ) {

$cache_file = get_cache_file();

if( file_exists( $cache_dir . '/' . $cache_file ) ) {

// check for updates
$if_modified_since = preg_replace('/;.*$/', '', $_SERVER[ "HTTP_IF_MODIFIED_SINCE" ]);
$gmdate_mod = gmdate('D, d M Y H:i:s', filemtime( $cache_dir . '/' . $cache_file ) );
if(strstr($gmdate_mod, 'GMT')) {
$gmdate_mod .= " GMT";
}

//error_log("TimThumb: $gmdate_mod == $if_modified_since");

if ( $if_modified_since == $gmdate_mod ) {
header( "HTTP/1.1 304 Not Modified" );
exit;
}

// send headers then display image
header( "Content-Type: " . $mime_type );
header( "Last-Modified: " . gmdate('D, d M Y H:i:s', filemtime( $cache_dir . '/' . $cache_file ) . " GMT" ) );
header( "Content-Length: " . filesize( $cache_dir . '/' . $cache_file ) );
header( "Cache-Control: max-age=9999, must-revalidate" );
header( "Expires: " . gmdate( "D, d M Y H:i:s", time() + 9999 ) . "GMT" );
readfile( $cache_dir . '/' . $cache_file );
exit;

}

}

function get_cache_file () {

$request_params = $_REQUEST;
$cachename = $_REQUEST['src'] . $_REQUEST['w'] . $_REQUEST['h'] . $_REQUEST['zc'] . $_REQUEST['q'];
$cache_file = md5( $cachename );
return $cache_file;

}

Topics: PHP | 1 Comment »

Oracle: usage of the tablespaces (permanent and temporary)


set pagesize 10000

set COLSEP '|'
set VERIFY off
set serveroutput on size 1000000
BREAK ON report

column tablespace_name format a30 heading 'TABLESPACE'
column sizegb format 9999999999D9 heading 'SIZE-Gb'
column usedproc format 999D99 heading 'USED-%'
column status format a10 heading 'STATUS'
COMPUTE sum LABEL 'Total size:' of sizegb ON report

SELECT b.tablespace_name ,
b.bytes/1024/1024/1024 as sizegb ,
NVL(100-((a.bytes/b.bytes)*100), 100) usedproc,
replace(c.status,' ','_') status
FROM
( select tablespace_name,
sum(bytes) bytes
from dba_free_space
group by tablespace_name
) a ,
( select tablespace_name,
sum(bytes) bytes
from dba_data_files
group by tablespace_name
) b ,
dba_tablespaces c
WHERE b.tablespace_name = a.tablespace_name (+)
AND b.tablespace_name = c.tablespace_name
union
select f.TABLESPACE_NAME,
f.TOTAL_MB/1024 sizegb,
nvl( (u.USED_MB/f.TOTAL_MB)*100, 0 ) usedproc,
'TEMPORARY' status
from
(
select f1.TABLESPACE_NAME,sum( f1.BYTES/1024/1024 ) TOTAL_MB
from (
select TABLESPACE_NAME,BYTES
from dba_temp_files
union all
select TABLESPACE_NAME,BYTES
from dba_data_files
where TABLESPACE_NAME in (
select TABLESPACE_NAME
from dba_tablespaces
where CONTENTS='TEMPORARY'
)
) f1
group by f1.TABLESPACE_NAME
) f,
(
select u1.TABLESPACE,
sum(u1.blocks) * max((select value from v$parameter where name='db_block_size')/1024/1024) USED_MB
from v$sort_usage u1
group by u1.TABLESPACE
) u
where f.TABLESPACE_NAME = u.tablespace (+)
ORDER BY 1;

Topics: Oracle, space, tablespace, temp | No Comments »

AppleScript: rotate mov file in QuickTime Pro

Some kind of life hack: it's very easy to make mov file with digital camera, rotating it 90 degrees. However, it's not so easy to convert the result file to the 'visible' form.

QuickTime Pro could do this, and I found the AppleScript script, which could make it even more easy.


tell application "QuickTime Player"
set m to (get movie 1)
rotate m by -90
save self contained m in (choose file name with prompt "save self contained movie")
end tell

The script is mentioned here

Topics: AppleScript, video | 1 Comment »

Oracle: plan of the running query

col object_name for a40

select operation,
options,
object_name,
partition_id
from v$sql_plan
where address in
( select sql_address from v$session where sid = &sid.)
order by id;

Topics: Oracle, performance | No Comments »

Oracle: using DBMS_METADATA for getting table structure


set long 5000

select dbms_metadata.get_ddl('TABLE','EMP','SCOTT');

Topics: Oracle, reverse | No Comments »

Oracle: using substitution variables in sqlplus

Get the value:


ACCEPT my_password CHAR PROMPT 'Password: ' HIDE
ACCEPT birthday DATE FORMAT 'dd/mm/yyyy' DEFAULT '01/01/1950' PROMPT 'Enter birthday date: '

Declaring the variable

DEFINE the_answer = 42

Undefine the variable

UNDEFINE the_answer

How to remember the result of the query

column the_date new_value the_rundate noprint;
select to_char(sysdate, 'DDMMYYYY_HH24MI') the_date from dual;

select '&the_rundate' from dual ;

Save the variables to the file

store set myvars.txt create
store set myvars.txt replace
store set myvars.txt append

Assign several values to the variable

DEFINE my_list = " 'the Life', 'the Universe', 'and Everything'"

select *
from Book
where answer in ( &my_list );

Topics: Oracle, sqlplus | 1 Comment »

Oracle: disable all constraints referencing the table


begin
for cur in (select fk.owner, fk.constraint_name , fk.table_name
from all_constraints fk, all_constraints pk
where fk.CONSTRAINT_TYPE = 'R' and
pk.owner = '&which_owner' and
fk.R_CONSTRAINT_NAME = pk.CONSTRAINT_NAME
and pk.TABLE_NAME = '&which_table'
) loop
execute immediate 'ALTER TABLE '||cur.owner||'.'||cur.table_name||' MODIFY CONSTRAINT '||cur.constraint_name||' DISABLE';
end loop;
end;

Topics: Oracle | 1 Comment »

Oracle: info about the corrupted block


select * from dba_extents
where file_id = &file_id
and &block_id between block_id and block_id + blocks - 1;

Topics: Oracle, error, restore | No Comments »

Spiraling quine in Perl


#!/usr/bin/perl
$_='
$q ="\ 47"; wh
ile ($ ;=
$z += .5 ){
%c= $r=0;$/ ="";whi le(2
0+ $z>($;+=.05)){$c{int$ _+ 2
6+ 2*($ r+= .0 2) *
s in$ ;}{1 -$_
+1 0+ int $r*c o s
$ ;} =1for(0. .1) }$
t =r ever se;$ /. =`
c le ar `. " #!
/ usr /bi n/ pe
rl \n\ $_ =$q \n" ;
fo r$y (1..20){$c{$_} {
$ y }? $ /.=chop$t :
($/ . =" \4
0") for(0. .53) ;
$/. ="\n"}pri nt"$/$ q;
s; ". chr(9 2)."s;;g;eval\n "}

';s;\s;;g;eval

Courtesy of PerlMonks

Topics: perl, quine | No Comments »

« Previous Entries Next Entries »