Tag Archive for function

PHP JavaScript ROT13 Encoder Function

/**
* Returns a rot13 encrypted string as well as a JavaScript decoder function.
* @param string $inputString The string to encrypt
* @return string An encoded javascript function
*/

function js_rot13_encode($inputString) {
$rotated = str_replace('"','"',str_rot13($inputString));
return <<<EOF
<script type="text/javascript">
/*<![CDATA[*/
document.write("$rotated".replace(/[a-zA-Z]/g, function(c){return String.fromCharCode((c<="Z"?90:122)>=(c=c.charCodeAt(0)+13)?c:c-26);}));
/*]]>*/
</script>

EOF;
// N.B Make sure there are no whitespace or extra characters following the semicolon above!
}

// ========
// = Demo =
// ========

echo js_rot13_encode('<a href="mailto:user@host.com">user@host.com</a>');
echo js_rot13_encode('user@host.com');

source

elapsed_time (human readable time span given total seconds)

def elapsed_time(seconds, suffixes=['y','w','d','h','m','s'], add_s=False, separator=' '):
"""
Takes an amount of seconds and turns it into a human-readable amount of time.
"""
# the formatted time string to be returned
time = []

# the pieces of time to iterate over (days, hours, minutes, etc)
# - the first piece in each tuple is the suffix (d, h, w)
# - the second piece is the length in seconds (a day is 60s * 60m * 24h)
parts = [(suffixes[0], 60 * 60 * 24 * 7 * 52),
(suffixes[1], 60 * 60 * 24 * 7),
(suffixes[2], 60 * 60 * 24),
(suffixes[3], 60 * 60),
(suffixes[4], 60),
(suffixes[5], 1)]

# for each time piece, grab the value and remaining seconds, and add it to
# the time string
for suffix, length in parts:
value = seconds / length
if value > 0:
seconds = seconds % length
time.append('%s%s' % (str(value),
(suffix, (suffix, suffix + 's')[value > 1])[add_s]))
if seconds < 1:
break

return separator.join(time)

if __name__ == '__main__':
# 2 years, 1 week, 6 days, 2 hours, 59 minutes, 23 seconds
# 2y 1w 6d 2h 59m 23s
seconds = (60 * 60 * 24 * 7 * 52 * 2) + (60 * 60 * 24 * 7 * 1) + (60 * 60 * 24 * 6) + (60 * 60 * 2) + (60 * 59) + (1 * 23)
print elapsed_time(seconds)
print elapsed_time(seconds, [' year',' week',' day',' hour',' minute',' second'])
print elapsed_time(seconds, [' year',' week',' day',' hour',' minute',' second'], add_s=True)
print elapsed_time(seconds, [' year',' week',' day',' hour',' minute',' second'], add_s=True, separator=', ')

source

Random value between two numbers

public function getRandom(_min, _max):Number{
var tNumber:Number;
tNumber = Math.round(Math.random()*(_max-_min))+_min;
return tNumber;
} // END getRandom()

source

Checking Plurals With ASP – A Simple Check Plural Function

function CheckPlural(input)
if input << 1 then
CheckPlural = "s"
else
CheckPlural = ""
end if
end function

'function can be called like so:
'25 Vote<%=CheckPlural(25)%>

source

function

function name()
{

}

source

Javascript image preload object

<html>
<head>
<script type="text/javascript">
oHW = {

myimgs : new Array(),
reimgs : new Array(),
oId : '',
preMontar : function() {
for (v=0; v<this.preMontar.arguments.length; v++){
this.myimgs[v] = new Image();
this.myimgs[v].src = this.preMontar.arguments[v];
}
},
Cambiar : function(myid,n) {
this.myimgs[myid] = document.getElementById(myid).src;
this.oId = myid;
document.getElementById(myid).src = n;
},
Restore : function() {
document.getElementById(this.oId).src = this.myimgs[this.oId];
this.oId = '';
}

} // ..
</script>
</head>

<body onload="oHW.preMontar('img1_on.jpg','img2_on.jpg','img3_on.jpg');">

<a href="#" onmouseout="oHW.Restore()" onmouseover="oHW.Cambiar('mn1','img1_on.jpg')"><img border="0" id="mn1" src="img1.jpg" alt="" /></a>

<a href="#" onmouseout="oHW.Restore()" onmouseover="oHW.Cambiar('mn2','img2_on.jpg')"><img border="0" id="mn2" src="img2.jpg" alt="" /></a>

<a href="#" onmouseout="oHW.Restore()" onmouseover="oHW.Cambiar('mn3','img3_on.jpg')"><img border="0" id="mn3" src="img3.jpg" alt="" /></a>

</body>
</html>

source

Recursive chmod in PHP

<?
/**
Chmods files and folders with different permissions.

This is an all-PHP alternative to using:

<tt>exec("find ".$path." -type f -exec chmod 644 {} ;");</tt>

<tt>exec("find ".$path." -type d -exec chmod 755 {} ;");</tt>

@author Jeppe Toustrup (tenzer at tenzer dot dk)
@param $path An either relative or absolute path to a file or directory
which should be processed.
@param $filePerm The permissions any found files should get.
@param $dirPerm The permissions any found folder should get.
@return Returns TRUE if the path if found and FALSE if not.
@warning The permission levels has to be entered in octal format, which
normally means adding a zero ("0") in front of the permission level.

More info at: <a href="http://php.net/chmod." >http://php.net/chmod.</a>
*/

function recursiveChmod($path, $filePerm=0644, $dirPerm=0755)
{
// Check if the path exists
if(!file_exists($path))
{
return(FALSE);
}
// See whether this is a file
if(is_file($path))
{
// Chmod the file with our given filepermissions
chmod($path, $filePerm);
// If this is a directory...
} elseif(is_dir($path)) {
// Then get an array of the contents
$foldersAndFiles = scandir($path);
// Remove "." and ".." from the list
$entries = array_slice($foldersAndFiles, 2);
// Parse every result...
foreach($entries as $entry)
{
// And call this function again recursively, with the same permissions
recursiveChmod($path."/".$entry, $filePerm, $dirPerm);
}
// When we are done with the contents of the directory, we chmod the directory itself
chmod($path, $dirPerm);
}
// Everything seemed to work out well, return TRUE
return(TRUE);
}
?>

source

Elapsed time string from time in seconds

function elapsedTime (createdAt)
{
var ageInSeconds = (new Date().getTime() - new Date(createdAt).getTime()) / 1000;
var s = function(n) { return n == 1 ? '' : 's' };
if (ageInSeconds < 0) {
return 'just now';
}
if (ageInSeconds < 60) {
var n = ageInSeconds;
return n + ' second' + s(n) + ' ago';
}
if (ageInSeconds < 60 * 60) {
var n = Math.floor(ageInSeconds/60);
return n + ' minute' + s(n) + ' ago';
}
if (ageInSeconds < 60 * 60 * 24) {
var n = Math.floor(ageInSeconds/60/60);
return n + ' hour' + s(n) + ' ago';
}
if (ageInSeconds < 60 * 60 * 24 * 7) {
var n = Math.floor(ageInSeconds/60/60/24);
return n + ' day' + s(n) + ' ago';
}
if (ageInSeconds < 60 * 60 * 24 * 31) {
var n = Math.floor(ageInSeconds/60/60/24/7);
return n + ' week' + s(n) + ' ago';
}
if (ageInSeconds < 60 * 60 * 24 * 365) {
var n = Math.floor(ageInSeconds/60/60/24/31);
return n + ' month' + s(n) + ' ago';
}
var n = Math.floor(ageInSeconds/60/60/24/365);
return n + ' year' + s(n) + ' ago';
}

// Make date parseable in IE
function fixDate (d)
{
var a = d.split(' ');
var year = a.pop();
return a.slice(0, 3).concat([year]).concat(a.slice(3)).join(' ');
}

source

Function invocation and ‘this’ Context Example

//Define our objects
var o1 = {handle:'o1'};
var o2 = {handle:'o2'};
var o3 = {handle:'o3'};
//Set handle to window
window.handle = 'window';

function whoAmI() {
return this.handle;
}
//Create method in object 01
o1.identifyMe = whoAmI;

alert(whoAmI()); //Alerts 'window'
alert(o1.identifyMe()); //Alerts 'o1'
alert(whoAmI.call(o2)); //Alerts 'o2' (call is running whoAmI in the context of o2)
alert(whoAmI.apply(o3)); //Alerts 'o3' (apply is running whoAmI in the context of o3)

source

PHP – is_valid_email

function is_valid_email($email)
{
return preg_match("/[a-zA-Z0-9_-.+]+@[a-zA-Z0-9_-.]+.[a-zA-Z]+/", $email) > 0;
}

source