Sunday, August 25, 2013

HowTo Format Date For Display or Use In a Shell Script

How do I format date to display on screen on for my shell scripts as per my requirements on Linux or Unix like operating systemsYou need to use the standard date command to format date or time. You can use the same command with the shell script.
 The syntax is
  1. date +FORMAT 
  2. date +"%FORMAT"
  3. date +"%FORMAT%FORMAT" 
  4. date +"%FORMAT-%FORMAT"

Task: Display date in mm-dd-yy format

Open a terminal and type the following date command:
$ date +"%m-%d-%y"Sample output:
02-27-07
To turn on 4 digit year display:
$ date +"%m-%d-%Y"Just display date as mm/dd/yy format:
$ date +"%D"

Task: Display time only

Type the following command:
$ date +"%T"Outputs:
19:55:04
To display locale's 12-hour clock time, enter:
$ date +"%r"Outputs:
07:56:05 PM
To display time in HH:MM format, type:
$ date +"%H-%M"Sample outputs:
00-50

How do I save time/date format to the shell variable?

$ NOW=$(date +"%m-%d-%Y"To display a variable use echo / printf command:
$ echo $NOW

A sample shell script

#!/bin/bash
NOW=$(date +"%m-%d-%Y")
FILE="backup.$NOW.tar.gz"
echo "Backing up data to /nas42/backup.$NOW.tar.gz file, please wait..."
# rest of script
# tar xcvf /nas42/backup.$NOW.tar.gz /home/ /etc/ /var
 

A complete list of FORMAT control characters supported by the date command

FORMAT controls the output. It can be the combination of any one of the following:
%FORMAT StringDescription
%%a literal %
%alocale's abbreviated weekday name (e.g., Sun)
%Alocale's full weekday name (e.g., Sunday)
%blocale's abbreviated month name (e.g., Jan)
%Blocale's full month name (e.g., January)
%clocale's date and time (e.g., Thu Mar 3 23:05:25 2005)
%Ccentury; like %Y, except omit last two digits (e.g., 21)
%dday of month (e.g, 01)
%Ddate; same as %m/%d/%y
%eday of month, space padded; same as %_d
%Ffull date; same as %Y-%m-%d
%glast two digits of year of ISO week number (see %G)
%Gyear of ISO week number (see %V); normally useful only with %V
%hsame as %b
%Hhour (00..23)
%Ihour (01..12)
%jday of year (001..366)
%khour ( 0..23)
%lhour ( 1..12)
%mmonth (01..12)
%Mminute (00..59)
%na newline
%Nnanoseconds (000000000..999999999)
%plocale's equivalent of either AM or PM; blank if not known
%Plike %p, but lower case
%rlocale's 12-hour clock time (e.g., 11:11:04 PM)
%R24-hour hour and minute; same as %H:%M
%sseconds since 1970-01-01 00:00:00 UTC
%Ssecond (00..60)
%ta tab
%Ttime; same as %H:%M:%S
%uday of week (1..7); 1 is Monday
%Uweek number of year, with Sunday as first day of week (00..53)
%VISO week number, with Monday as first day of week (01..53)
%wday of week (0..6); 0 is Sunday
%Wweek number of year, with Monday as first day of week (00..53)
%xlocale's date representation (e.g., 12/31/99)
%Xlocale's time representation (e.g., 23:13:48)
%ylast two digits of year (00..99)
%Yyear
%z+hhmm numeric timezone (e.g., -0400)
%:z+hh:mm numeric timezone (e.g., -04:00)
%::z+hh:mm:ss numeric time zone (e.g., -04:00:00)
%:::znumeric time zone with : to necessary precision (e.g., -04, +05:30)
%Zalphabetic time zone abbreviation (e.g., EDT)
SEE ALSO:

Call and store response from a url using bash script

#!/bin/bash

## generate random string of length 18

function randpass
{
        echo `</dev/urandom tr -dc A-Za-z0-9 | head -c18`
}


## get current time stamp

timestamp=$(date  +%s);
sessionId="$(randpass).$(randpass).$timestamp";
privateKey='test';
 

## get substring of sessionId from 0 to 5 characters.
sessionIdPart=${sessionId:0:5};
systemKeyPart=${privateKey:0:4};


## reverse string and store in a variable

word="$(echo "$sessionIdPart" | rev)$(echo "$systemKeyPart" | rev)";
word="$word$sessionId$privateKey";
 

## make a string md5
hash=`echo -n "$word" | md5sum | awk '{print $1}'`;
hash=${hash:0:10};
breakRest="securedSessionKey=$sessionId&securedHash=$hash";
 

saveFile=$(date +"%Y-%m-%d %T")
## saveFile would be '2013-08-25 19:23:28'

## calling a url using 'curl' and store response to some file.
curl -s -L -o "$saveFile.html" "http://domain.com/getStudent?$breakRest" &
## "&" sign at the end means run curl in background.

exit 1;

Friday, August 23, 2013

How can i add css with !important , only using jquery

jQuery code


var div = $(".my_class")
div.click(function() {
 div.style("color", "blue", "important")
        div.append("<div>Color: " + div.style('color') + "</div>")
 div.append("<div>Is_Important: " + div.style().getPropertyPriority('color') + "</div>")
})

$.fn.style = function(styleName, value, priority) {
    var node = this.get(0)
    if (typeof node == 'undefined') {
        return
    }
    var style = node.style
    if (typeof styleName != 'undefined') {
        if (typeof value != 'undefined') {
            var priority = typeof priority != 'undefined' ? priority : ''
            style.setProperty(styleName, value, priority)
        }
        else {
            return style.getPropertyValue(styleName)
        }
    } 
    else {
        return style
    }
}

And finally jsFiddle link

Click here to view effect

Thursday, August 22, 2013

Using php execute command/run another php file wihtout waiting for result

<?php
session_start();
$_SESSION["student_name"] = "Pritom Kumar Mondal";

$_SESSION["roll"] = "College: 2150, Varsity: 060238";
echo "Start time: " date('h:i:s');
$phpCommandLocation "C:\\xampp\\php\\php.exe";
$phpFileLocation    "C:\\xampp\\htdocs\\test1\\call.php";
$logLocation        "C:\\tmp\\result.log";
$argvList = " session_id=".session_id(); /*You can send session id*/ 
$argvList.= " name=".rawurlencode("Pritom Kumar Mondal");
$command            $phpCommandLocation " -f "           .
    $phpFileLocation . $argvList " 1>>" $logLocation " 2>&1 &"; 
pclose(popen("start /B " $command"r"));
echo 
"<BR>End time: " date('h:i:s'); 

?>

And output is:
Start time: 11:07:26
End time: 11:07:26

And call.php looks like:
<?php
foreach($argv as $argvString) {
    $argvStringList = explode("=", $argvString);
    if($argvStringList[0] == "session_id") {
        session_id($argvStringList[1]);
        session_start();

        /* Start session with received session id, BINGO... */
    }
}
$string 
"\r\n-------------------------------\r\nStart time: " date('h:i:s'); 

$string .= "\r\nStart sleeping for 5 seconds."; 
sleep(5); 
$string .= "\r\nEnd time: " date('h:i:s');
 file_put_contents("data.txt" 
    "SOMETHING WENT GOOD...................\r\n" 
    $string);
echo 
$string; 

echo "\r\nReceived argv list: ";
print_r($argv); /* Printing argv as array */
echo "\r\nPrevious index.php session variables in currently executed php: ";
print_r($_SESSION); /* Printing argv as array */
?>
Yellow background showing that this script wait for 5 seconds.

The C:\\tmp\\result.log is:
-------------------------------
Start time: 11:07:28
Start sleeping for 5 seconds.

End time: 11:07:33
Received argv list: 
Array
(
    [0] => C:\xampp\htdocs\test1\call.php
    [1] => session_id=gjbf54ql8dhuvg0njsgt4hh8n7
    [2] => name=Pritom%20Kumar%20Mondal%2C%20Roll%3D2525

Previous index.php session variables in currently executed php:
Array
(
    [
student_name] => Pritom Kumar Mondal
    [roll] => College: 2150, Varsity: 060238
)


There are a few thing that are important here.

First of all: put the full path to the php binary, because this command will run under the apache user, and you will probably not have command alias like php set in that user.

Seccond: Note 2 things at the end of the command string: the '2>&1' and the '&'. The '2>&1' is for redirecting errors to the standard IO. And the most important thing is the '&' at the end of the command string, which tells the terminal not to wait for a response.

Third: Make sure you have 777 permissions on the 'result.log' file

If you use linux operating system just write:
<?php
exec
($command " > /dev/null &"); 

?>

Asynchronous cURL Requests

A possibly underused technique available to PHP developers is the ability to spawn a background PHP script without JavaScript. All you need to do this is the cURL library and a few lines of code. Let me explain, suppose you have a script that is going to take minutes (or longer) to run, you don’t want to sit looking at a blank screen, and your users certainly won’t! In this kind of scenario you can separate out that logic to a background file and leave your view free for other things, perhaps to query the database to see how the background process is doing?
All you need to do to set this off is use the following code (entering your own url):
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'http://www.yoursite.com/background-script.php');
curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 1);
curl_setopt($ch, CURLOPT_NOBODY, true); 

curl_exec($ch);
curl_close($ch);
There is an irritating 1 second delay for this to finish, but this cannot be helped (so far as I am aware!)
Remember to be careful with this technique (especially if you turn off script timeout etc) and build in a control to stop the script should you need to (database query every minute? or a lock file?)
Enjoy!

Update

It has been pointed out to me that on modern systems (cURL 7.16.2 or higher and PHP 5.2.3 or above) you can use a millisecond option to reduce the delay effectively to zero.
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'http://www.yoursite.com/background-script.php');
curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
curl_setopt($ch, CURLOPT_TIMEOUT_MS, 1);
curl_setopt($ch, CURLOPT_NOBODY, true);

curl_exec($ch);
curl_close($ch);