2012 in review

The WordPress.com stats helper monkeys prepared a 2012 annual report for this blog.

Here’s an excerpt:

4,329 films were submitted to the 2012 Cannes Film Festival. This blog had 24,000 views in 2012. If each view were a film, this blog would power 6 Film Festivals

Click here to see the complete report.

 

Add a Shutdown menu to the Windows 8 desktop

As you know, the Start menu in Windows not only provided you with a way to launch your application but also a way to shut down your computer. For example, in Windows 7 there is a Shut down as well as a pop-up menu that displays six other related options: Switch user, Log off, Lock, Restart, Sleep, and Hibernate.

In Windows 8, these options are spread out between the Power Charm and the context menu associated with your user picture on the Start screen, as shown in Figure A. Unfortunately, this new arrangement isn’t convenient for everyone. I’ve heard numerous complaints about this as well as requests for the ability to shut down or restart the system to be put back on the desktop.

Figure A

This composite image shows the power options on the Power Charm and the context menu associated with your user picture.

I began investigating this possibility and have found a technique that will allow you to recreate a reasonable facsimile of the Shut down pop-up menu on Windows 8’s desktop. The technique involves creating a series of shortcuts using special commands, saving them to a folder, and then specifying that folder as a taskbar toolbar. Let take a closer look.

The special commands

As you may know, Windows comes with a command line utility called Shutdown.exe that, along with special parameters, can be used to create the majority of the options for our Shut down menu. To create the other options we’ll use two other command line utilities: Rundll32.exe and Tsdiscon.exe. These commands and their parameters are shown in Table A.

Table A

Menu option

Command

Shut down shutdown.exe /s /t 00
Restart shutdown.exe /r /t 00
Log off shutdown.exe /l
Sleep or Hibernate rundll32.exe powrprof.dll,SetSuspendState
Lock rundll32.exe user32.dll,LockWorkStation
Switch user tsdiscon.exe

Sleep vs. Hibernate

The differences between activating Sleep and Hibernate from the command line in Windows 8 can be tricky, so be aware.

As you can see the same command line is used to initiate Sleep and Hibernate. If you have the Hibernate feature enabled, then this command line will put the system into Hibernation mode. If you have the Hibernate feature disabled, then this command line will put the system into Sleep mode.

Keep in mind that if the Hibernate feature is disabled, then the only power saving option you will have available is Sleep mode. If the Hibernate feature is enabled, then both power saving options, Hibernate and Sleep, will be available – just not both from the command line.

If you leave the Hibernate feature enabled, then you can use a shortcut to activate the Hibernation mode and can then activate Sleep mode from the Power Charm or by configuring the power button on the computer to activate Sleep mode. As such, I chose to leave the Hibernate feature enabled.

Now, if you want to disable or enable the Hibernate feature, you will press [Windows]+X to bring up the Tools menu and then select Command Prompt (Admin). Then, you will use one of the following commands:

powercfg -hibernate off
powercfg  -hibernate on

Creating the shortcuts

In order to use the taskbar toolbar, you’ll need to create all your shortcuts in a single folder. To make it simple, I created a folder called Shut down and then used Create Shortcut wizard to create my shortcuts in that folder. To do so, just right click on the background and choose the New | Shortcut command. When you see the first screen in the Create Shortcut wizard, type the first command from Table A in the text box, as shown in Figure B.

Figure B

Type the first command from Table A in the text box.

In this command, the /s is the shut down parameter and the /t 00 is the timer parameter which instructs the shut down command to shut down the system in 00 seconds or immediately. Once you type the command, you can click Next. When you see the second screen in the Create Shortcut wizard, type Shut down as shown in Figure C. To complete the wizard, just click Finish.

Figure C

Name this shortcut Shut down.

Once you create the Shutdown shortcut, you’ll create the Restart shortcut, as shown in Figure D. In this command, the /r is the restart parameter and the /t 00 is the timer parameter which instructs the shut down command to restart the system immediately.

Figure D

The /r parameter instructs the shutdown command to restart the computer.

You can then create the Log off shortcut as shown in Figure E. In this command, the /l is the log off parameter.

Figure E

The /l parameter instructs the shutdown command to Log off the computer.

You’ll then create the Hibernate shortcut as shown in Figure F. In this command line, rundll32.exe activates the Power Profile (powerprof.dll) and then launches the default power saving mode (SetSuspendState). Keep in mind that case is important in this last command – you must use both upper and lower case letters.

Figure F

You must use both upper and lower case letters in last part of the Hibernate command.

You can now create the Lock shortcut as shown in Figure G. In this command line, rundll32.exe accesses the currently logged on user’s session (user32.dll) and locks the session (LockWorkStation). Again, case is important in the last command.

Figure G

The last part of the Lock command must use both upper and lower case letters.

The Switch user shortcut is quite simple, as you can see in Figure H. There is only the tsdiscon.exe command – no parameters.

Figure H

The Switch user shortcut has a simple command.

Once you have created your shortcuts, you can assign each one a unique icon if you wish. To do so, right click on the shortcut icon and select the Properties command. When you see the Properties dialog box, click the Change Icon button to open the Change Icon dialog box. Then, click the Browse button. You can find a host of icons in the Shell32.dll file, as shown in Figure I.

Figure I

The Shell32.dll file contains a host of icons.

Creating the toolbar

Now that you have your shortcuts created in the Shut down folder, you can create the toolbar. Right-click on the taskbar and then select the Toolbars | New toolbar command, as shown in Figure J.

Figure J

Select the New toolbar command.

When you do, you’ll see the New Toolbar – Choose a folder dialog box and will need to locate and select the Shutdown folder, as shown in Figure K.

Figure K

In the New Toolbar – Choose a folder dialog box, just select the Shutdown folder.

Your new Shut down menu will now appear on the right edge of the taskbar, as shown in Figure L. You can leave it there or you can move it to the far left if you want. For me it works best on the right side of the taskbar. Regardless of where you place it, you can now quickly and easily Shut down, Restart, Lock, Log off, Hibernate, or Switch user right from the Windows 8 desktop.

Figure L

The Shut down menu may work best on the right side of the taskbar.
[Ref: http://www.techrepublic.com/blog/window-on-windows/add-a-shutdown-menu-to-the-windows-8-desktop/7031?tag=main;river-newest]

Converting Oracle DATE types and PHP/Unix Timestamps

If you need to convert between Oracle date and PHP/Unix timestamp then you might need to implement two function in Oracle.

The following two Oracle functions implement this for DATE types.

To convert a UNIX timestamp into an Oracle DATE type:

CREATE OR REPLACE
    FUNCTION unixts_to_date(unixts IN PLS_INTEGER) RETURN DATE IS
        /**
         * Converts a UNIX timestamp into an Oracle DATE 
         */
        unix_epoch DATE := TO_DATE('19700101000000','YYYYMMDDHH24MISS');
        max_ts PLS_INTEGER := 2145916799; -- 2938-12-31 23:59:59
        min_ts PLS_INTEGER := -2114380800; -- 1903-01-01 00:00:00
        oracle_date DATE;

        BEGIN

            IF unixts > max_ts THEN
                RAISE_APPLICATION_ERROR(
                    -20901,
                    'UNIX timestamp too large for 32 bit limit'
                );
            ELSIF unixts < min_ts THEN
                RAISE_APPLICATION_ERROR(
                    -20901,
                    'UNIX timestamp too small for 32 bit limit' );
            ELSE
                oracle_date := unix_epoch + NUMTODSINTERVAL(unixts, 'SECOND');
            END IF;

            RETURN (oracle_date);

    END;

The following PHP script shows how this might be used. Note that this script requires PHP 5.x+, as it uses the new OCI extension function names:

<?php
$conn = oci_connect('scott', 'tiger');

$sql = "
    SELECT
        *
    FROM EMP
    WHERE
        hiredate
    BETWEEN
        unixts_to_date(:startdate)
    AND
        unixts_to_date(:enddate)
    ORDER BY
        hiredate
    DESC
    ";

$stmt = oci_parse($conn, $sql);

// Bind a UNIX timestamps to :startdate and :enddate
oci_bind_by_name($stmt, ":startdate", mktime(0,0,0,1,1,1981));
oci_bind_by_name($stmt, ":enddate", mktime(0,0,0,1,1,1990));

oci_execute($stmt);

print "NAME  : HIREDATE\n";
while ( $row = oci_fetch_assoc($stmt) ) {
   print "{$row['ENAME']} : {$row['HIREDATE']}\n";
}
oci_free_statement($stmt);

oci_close($conn);
?>

In reverse, the following function returns a UNIX timestamp given an Oracle DATE type:

CREATE OR REPLACE
    FUNCTION date_to_unixts(oracle_date IN DATE) RETURN PLS_INTEGER IS
        /**
         * Converts an Oracle DATE to a UNIX timestamp
         */
        unix_epoch DATE := TO_DATE('19700101000000','YYYYMMDDHH24MISS');
        max_date DATE := TO_DATE('20380101000000','YYYYMMDDHH24MISS');
        min_date DATE := TO_DATE('19030101000000','YYYYMMDDHH24MISS');
        unix_ts PLS_INTEGER;

        BEGIN

            IF oracle_date > max_date THEN
                RAISE_APPLICATION_ERROR( -20902,'Date too large for 32bit UNIX timestamp' );
            ELSIF oracle_date < min_date THEN
                RAISE_APPLICATION_ERROR( -20902,'Date too small for 32bit UNIX timestamp' );
            ELSE
                unix_ts := (oracle_date - unix_epoch) / (1/86400);
            END IF;

            RETURN (unix_ts);

        END;

The following query shows how it might be used:SELECT
    ename,
    TO_CHAR(hiredate, 'YYYY') AS hired_year,
    TO_CHAR(hiredate, 'YYYYMM') AS hired_month,
    TO_CHAR(hiredate, 'ddth Mon, YYYY') AS hired_pretty
    date_to_unixts(hiredate) AS hired_unixts
FROM
    emp
ORDER BY
    hiredate

It’s now easy to convert the timestamp into a formatted date, using thedate() function as you loop through the result set.

 

Working with Dates and Times in Oracle and PHP

Both PHP and Oracle provide functionality manipulating dates and times. Which to use and when?

If you’re new to PHP or Oracle, working out how to handle dates efficiently can be tricky. You may have strategies, which you’ve applied successfully on other platforms, but will they fit to the combination of Oracle and PHP?

This Oracle+PHP recipe should help you understand the functionality, available in both PHP and Oracle, for working with dates and times and how they relate to each other. In doing so, it should help you decide where to draw line in deciding which technology will handle what, and answer questions like “Do I calculate the difference between these two dates in PHP or Oracle?”

Dates and Times in Oracle

Oracle provides three data types for storing date/time values:

  • The DATE type, which represents a date and time. A value stored in a DATE field contains “components” corresponding to the century, year, month, day, hour, minute and second. Dates can be anywhere in the range from January 1, 4712 B.C., to December 31, 9999 A.D.
  • The TIMESTAMP type, available since Oracle9i, is effectively an extended form of the DATE type and complies with ANSI SQL. It provides greater precision in time, supporting fractions of a second up to nine places and is also capable of storing time zone information.
  • The INTERVAL type, since Oracle9i, which supports storage of a time difference such as “two years and five months” or “three days, 18 hours and 45 minutes” and can be summed with a DATE or TIMESTAMP to produce a new DATE / TIMESTAMP value.

The focus here will be on the DATE type, although much that applies to DATE also applies to TIMESTAMP. (For more background about TIMESTAMP and INTERVAL types, read Jonathan Gennick’s Oracle Magazine articles ” Datetime Datatypes Add Precision” and ” Finding the Time in Between” (both published in the Nov.-Dec. 2002 issue).

How Oracle Stores DATEs. The first thing to grasp about the DATE type in Oracle is that its internal representation allows it to be displayed and manipulated in many different ways. It is effectively independent of any specific string format. If you SELECT a DATE type, Oracle automatically converts it to readable string, but this is not how the value is actually been stored.

Selecting the current system time using SYSDATE, which returns a value of type DATE and is the current date and time set for the operating system on which the database resides :

SELECT SYSDATE FROM dual /* e.g. 25-JUL-05 */

The format is controlled by the Oracle parameterNLS_DATE_FORMAT, and can changed on a session basis (see below). To get a feeling for the internal representation:

SELECT DUMP(SYSDATE) FROM dual /* e.g. Typ=13 Len=8: 213,7,7,25,23,7,15,0 */

Comma-separated values in the result correspond to the bytes Oracle uses to store each component of a date and time, from century down to second One important note here; when comparing DATE types, all the DATE’s components will be compared, down to the seconds. In some cases you may want to compare two dates on a different basis, such as the year, month or day. In such cases functions like TRUNC can be useful to round down the hours, minutes and seconds components of the two DATEs you are comparing. See ” Date Arithmetic” below for more detail.

If you’re familiar with OOP, it may also be helpful to think of DATE types as objects. They possess both properties (year, month, hour etc.) and behavior, such as

SELECT SYSDATE - 7 FROM dual /* e.g. 18-JUL-05 */

This returns the date seven days ago. Further “behavior” includesDATE comparisons, which implies you canSORT BY,GROUP BY, find datesBETWEEN and so on, and subtraction: subtract oneDATE from another to get the integer difference in days (or anINTERVAL type, when usingTIMESTAMP values).

Converting Between DATE Types and Strings. The TO_DATE() and TO_CHAR() functions are used to convert between Oracle DATE”objects” and human readable date strings. Both functions take three arguments; the value to convert, an optional format mask and an optional string identify a language (e.g. FRENCH). Conceptually the format mask is similar to a regular expression; you specify a pattern for a date, which tells Oracle how to relate a matching string to a DATE type. The format mask is described in the Oracle Database SQL Reference under ” Format Models.”

Working with TO_CHAR. Here’s a simple example, again using the SYSDATE function:

SELECT TO_CHAR( SYSDATE, 'YYYY-MM-DD HH24:MI:SS' ) FROM dual
    /* e.g. 2005-07-26 17:34:04 */

Looking at format mask in detail, the’YYYY’ denotes a four-digit year,’MM’ a two digit month,’DD’ a two-digit day of the month,’HH24′ the hours in a 24-hour clock,’MI’ the minutes between 0 and 59, and’SS’ the seconds between 0 and 59. Note the following characters are passed from the format mask into the output “as-is”:

/ - , . ; :

Further strings can be “passed through” by enclosing them in quotes:

SELECT TO_CHAR(SYSDATE, '"The time is now " HH24:MI:SS "precisely"') FROM dual
    /* e.g. The time is now 17:38:22 precisely

There are many more format mask patterns available to address a wide range of use cases, as you will find the documentation.

Note: TO_CHAR can also be used with TIMESTAMP types.

Working with TO_DATE. Oracle can parse strings into DATE types, using the same format masks as TO_CHAR. Given a string like 20050726173102:

SELECT TO_DATE( '20050726173102', 'YYYYMMDDHH24MISS' ) FROM dual

Or to convert “Jul 26, 2005 17:13:05”, I can use:

SELECT TO_DATE('Jul 26, 2005 17:13:05', 'Mon DD, YYYY HH24:MI:SS') FROM dual

Note: ForTIMESTAMP types the equivalent function isTO_TIMESTAMP.

Changing the default date format. Oracle displays DATE types, by default, according to the format mask defined in the NLS_DATE_FORMAT parameter. This can be changed in the session like:

ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD HH24:MI:SS'

Date arithmetic. To determine the date six days after the 26th July, 2005, I simply add the value 6 to theDATE object:

SELECT TO_DATE( '20050726173102', 'YYYYMMDDHH24MISS' ) + 6 FROM dual
    /* e.g. 2005-08-01 17:13:05 */

The smallest whole unit for this type of operation is a single day. To subtract 18 hours, I need the appropriate fraction of a day:

SELECT TO_DATE( '20050726173102', 'YYYYMMDDHH24MISS' ) - (1/24 * 18) FROM dual
    /* e.g. 2005-07-25 23:31:02 */

Similarly, to add 59 seconds:

SELECT TO_DATE( '20050726173102', 'YYYYMMDDHH24MISS' ) + (1/(24*60*60) * 59) FROM dual

To work in months or years, given that neither can be expressed in a constant number of days (bearing in mind given leap years and months with different numbers of days), you need theADD_MONTHS function. To add twelve months to a date:

SELECT ADD_MONTHS( TO_DATE( '20050726173102', 'YYYYMMDDHH24MISS' ), 12) FROM dual
    /* e.g. 2006-07-26 17:31:02 */

Note: To subtract months, use a negative sign.

The LAST_DAY function returns the last day of the month for a DATE type:

SELECT LAST_DAY( TO_DATE( '20050701', 'YYYYMMDD' ) ) FROM dual
    /* e.g. 2005-07-31 00:00:00 */

TheTRUNC function rounds down theDATE, according to the date mask it is provided as the second argument. You might use it when makingDATE comparisons where you want to eliminate units such as seconds and minutes from the comparison:

SELECT TRUNC( TO_DATE( '20050726173102', 'YYYYMMDDHH24MISS' ), 'DD' ) FROM dual
    /* e.g. 2005-07-26 00:00:00 */

If no date mask is provided,TRUNC will round down theDATE to the start of the day it represents.

Other date-related functions include MONTHS_BETWEEN, for the integer difference in months between two DATE types, NEXT_DAY, to obtain a DATE type of the next week day matching a string literal (for example, ‘MONDAY’), and ROUND, similar to TRUNC, but returning the nearest DATE rounded up or down.

Building SQL Statements using Dates

Some simple examples of using the DATE type in an SQL statement, using the “emp” (employees) table (part of the sample data that comes with an Oracle installation). The “hiredate” column of the “emp” table stores values using the DATE type.

Locating all employees hired between two dates:

SELECT
    ename, TO_CHAR(hiredate, 'ddth Mon, YYYY')
FROM
    emp
WHERE
    hiredate
BETWEEN
    TO_DATE('1980-01-01','YYYY-MM-DD')
AND
    TO_DATE('1985-01-01','YYYY-MM-DD')
ORDER BY
    hiredate
DESC

Adding a new employee:

INSERT INTO emp
   (
        empno,
        ename,
        job,
        mgr,
        hiredate,
        sal,
        deptno
    )
VALUES
   (
        8002,
        'JOHNSON',
        'ANALYST',
        7566,
        TO_DATE('2005-07-22','YYYY-MM-DD'),
        3000,
        20
    )

Finding all employees who have been with the company for more than 15 years, using anINTERVAL type returned form theTO_YMINTERVAL function:

SELECT
    *
FROM
    emp
WHERE
    SYSDATE - TO_YMINTERVAL('15-00') >  hiredate

Dates and Times in PHP

A list of all available functions, based around the UNIX timestamp, can be found in the PHP Manual in the Date and Time Functions section. The focus here will be the date() and mktime() functions, which will typically be the functions you use most. Note that PHP version 5.1.x introduces additional date related functionality, while the examples here restrict themselves to operations available in earlier PHP versions 4.3.x and 5.0.x, although they are also forwards compatible with PHP 5.1.x.

The raw material of dates and times in PHP is the UNIX timestamp; the number of seconds before or after the UNIX epoch, which occurred at 00:00:00 UTC (GMT) on the January 1, 1970. To see a UNIX timestamp, simply print the result of PHP’s time() function; which is equivalent to Oracle’s SYSDATE:

<?php
print time(); // e.g. 1122391862
?>

To add or subtract units of days, hours, minutes, you convert the unit to seconds and apply it directly to the timestamp. Performing arithmetic using units of month and year requires the mktime() function (see below).

Formatting UNIX timestamps. The date() function is used to format UNIX timestamps:

<?php
print date('Y-m-d H:i:s',time()); // e.g. 2005-07-26 17:31:02
?>

The masks for the date() function are well documented in the manual. Any characters thatdate() does not recognize are automatically “passed though” into the output, such as punctuation characters. Characters, which could be mistaken for part of the format, can be escaped with a backslash, for example:

<?php
print date('l \t\he jS of F',1122391862); // e.g. Tuesday the 26th of July
?>

Resulting in “Tuesday the 26th of July.”

Note: If you place the format mask inside double quotes you may need a double backslash to escape certain characters; see the PHP Manual on string types and double quotes for details.

The date() function can also be useful for certain calculations:

<?php
$years = range(2005, 2020);
foreach ( $years as $year ) {
    if ( date('L', mktime(0,0,0,1,1,$year) ) ) {
        print "$year is a leap year\n";
    }
}
?>

Which tells me:
    2008 is a leap year
    2012 is a leap year
    2016 is a leap year
    2020 is a leap year

Note also the gmdate() function, which is almost exactly the same as thedate() function except that it converts the result to Greenwich Mean Time (UTC).

Creating and manipulating UNIX timestamps. The mktime() function is used to generate a UNIX timestamp from a date, given integers values which represent the components of the date. You could regard mktime() as the parallel to Oracle’s TO_DATE function. For example:

<?php
$year = 2005;
$month = 7;
$day = 27;
$hour = 12;
$minute = 34;
$second = 43;

print mktime($hour, $minute, $second, $month, $day, $year);
?>

Themktime() function takes care of adjustments required when boundaries, such as that between months are crossed:

<?php
$year = 2005;
$month = 7;
$day = 27 + 10; // Add 10 days
$hour = 12;
$minute = 34;
$second = 43;

print date('Y-M-d H:i:s',mktime($hour, $minute, $second, $month, $day, $year));
    // e.g. 2005-Aug-06 12:34:43
?>

Here, attempting to givemktime()”July 37″ results in the correct adjustment into August.

To find the last day of a given month, you can use the proceeding month along with a zero value as the day of that month. For example:

<?php
$year = 2005;
$month = 8; // August
$day = 0; // Last day of July
$hour = 12;
$minute = 34;
$second = 43;

print date('Y-M-d',mktime($hour, $minute, $second, $month, $day, $year));
?>

As with the date() function, there’s also a gmmktime() function which also adjusts to GMT.

Problems with dates and time in PHP. One limitation of UNIX timestamps is they are tied to the 32-bit limit of today’s mainstream CPU’s and operating systems. It means you can only represent a range of dates up to the year 2038 and back to 1902 on UNIX platforms. If this limitation poses a problem for your application, you may find the PEAR Date library a useful, albeit slower, alternative.

Another problem area is localization; the date() function only supports English weekday and month names. You may find the easiest practical solution, if you only need to support a handful of languages, is to translate the names using associative arrays.

Note that work is in progress to enhance PHP’s native date and time functions. You’ll find this outlined by Derick Rethans, one of the core PHP developers, in his PHP Time Handling talk which he gave at ApacheCON 2005 in Germany.

Drawing the Line

So the question is where do you draw the line? Where do you place the responsibility for handling date related operations? In PHP or Oracle? This section discusses the options, to help you make informed decisions.

In general, Oracle’s date facilities are more powerful than PHP’s, allowing greater flexibility when it comes to parsing date strings or formatting date output, thanks to a wider range of date formatting masks. Add to that the 32-bit limitation of the UNIX timestamp, that TIMESTAMP can store time zones and localization issues and you may consider passing off all date related work to Oracle. It should be pointed out though that many Web applications, particularly intranet applications, only target a single locale region, so operating within a single language and time zone. Also the range of a UNIX timestamp is often more than enough of the type of data the application will be handling. In such cases, PHP’s date time functions should pose no problems.

Date storage. Considering date and time storage, with some databases it may be necessary to use UNIX timestamps such as PHP5’s built-in SQLite. With Oracle it’s better to use DATE or TIMESTAMP as your column types, for storage for data and time values. The supporting functionality makes date operations easy, particularly when SELECTing based on DATEs and TIMESTAMPs. You’ll also find visually checking dates becomes much easier, as tools like SQL*Plus automatically display dates in a human readable form.

Date formatting. One argument against Oracle’s date formatting capabilities, when thinking in terms of a layered architecture, is that formatting output in your application’s data storage layer is “bad practice”, this being the job of the presentation layer.

If you’re in the (unusual) position of writing an application to run against multiple database implementations, this may be a valid argument. In such cases you may well want to investigate what John Lim has provided ADOdb to help with this problem—see his “Tips on Writing Portable SQL”, “Data Types” section.

More commonly, you’ll be developing against a single database, so vendor abstractions won’t be an issue. You might want to consider having Oracle format a date for you in a variety of ways, rather than trying to massage dates in PHP, as the following query suggests:

SELECT
    ename,
    TO_CHAR(hiredate, 'YYYY') AS hired_year,
    TO_CHAR(hiredate, 'YYYYMM') AS hired_month,
    TO_CHAR(hiredate, 'DD Mon, YYYY') AS hired_pretty,
    TO_CHAR(hiredate, 'DD Mon, YYYY', 'NLS_DATE_LANGUAGE=GERMAN') AS hired_german
FROM
    emp
ORDER BY
    hiredate

Alternatively (or in addition), returning a UNIX timestamp as part of the result fits nicely with PHP’s date() function (see below). Some of Oracle’s format masks, such as “Month”, pads the output with space characters so using date() in such instances may mean fewer lines of code.

Converting Oracle DATE types and Unix Timestamps. The following two Oracle functions implement this for DATE types.

To convert a UNIX timestamp into an Oracle DATE type:

CREATE OR REPLACE
    FUNCTION unixts_to_date(unixts IN PLS_INTEGER) RETURN DATE IS
        /**
         * Converts a UNIX timestamp into an Oracle DATE 
         */
        unix_epoch DATE := TO_DATE('19700101000000','YYYYMMDDHH24MISS');
        max_ts PLS_INTEGER := 2145916799; -- 2938-12-31 23:59:59
        min_ts PLS_INTEGER := -2114380800; -- 1903-01-01 00:00:00
        oracle_date DATE;

        BEGIN

            IF unixts > max_ts THEN
                RAISE_APPLICATION_ERROR(
                    -20901,
                    'UNIX timestamp too large for 32 bit limit'
                );
            ELSIF unixts < min_ts THEN
                RAISE_APPLICATION_ERROR(
                    -20901,
                    'UNIX timestamp too small for 32 bit limit' );
            ELSE
                oracle_date := unix_epoch + NUMTODSINTERVAL(unixts, 'SECOND');
            END IF;

            RETURN (oracle_date);

    END;

The following PHP script shows how this might be used. Note that this script requires PHP 5.x+, as it uses the new OCI extension function names:

<?php
$conn = oci_connect('scott', 'tiger');

$sql = "
    SELECT
        *
    FROM EMP
    WHERE
        hiredate
    BETWEEN
        unixts_to_date(:startdate)
    AND
        unixts_to_date(:enddate)
    ORDER BY
        hiredate
    DESC
    ";

$stmt = oci_parse($conn, $sql);

// Bind a UNIX timestamps to :startdate and :enddate
oci_bind_by_name($stmt, ":startdate", mktime(0,0,0,1,1,1981));
oci_bind_by_name($stmt, ":enddate", mktime(0,0,0,1,1,1990));

oci_execute($stmt);

print "NAME  : HIREDATE\n";
while ( $row = oci_fetch_assoc($stmt) ) {
   print "{$row['ENAME']} : {$row['HIREDATE']}\n";
}
oci_free_statement($stmt);

oci_close($conn);
?>

In reverse, the following function returns a UNIX timestamp given an OracleDATE type:

CREATE OR REPLACE
    FUNCTION date_to_unixts(oracle_date IN DATE) RETURN PLS_INTEGER IS
        /**
         * Converts an Oracle DATE to a UNIX timestamp
         */
        unix_epoch DATE := TO_DATE('19700101000000','YYYYMMDDHH24MISS');
        max_date DATE := TO_DATE('20380101000000','YYYYMMDDHH24MISS');
        min_date DATE := TO_DATE('19030101000000','YYYYMMDDHH24MISS');
        unix_ts PLS_INTEGER;

        BEGIN

            IF oracle_date > max_date THEN
                RAISE_APPLICATION_ERROR( -20902,'Date too large for 32bit UNIX timestamp' );
            ELSIF oracle_date < min_date THEN
                RAISE_APPLICATION_ERROR( -20902,'Date too small for 32bit UNIX timestamp' );
            ELSE
                unix_ts := (oracle_date - unix_epoch) / (1/86400);
            END IF;

            RETURN (unix_ts);

        END;

The following query shows how it might be used:SELECT
    ename,
    TO_CHAR(hiredate, 'YYYY') AS hired_year,
    TO_CHAR(hiredate, 'YYYYMM') AS hired_month,
    TO_CHAR(hiredate, 'ddth Mon, YYYY') AS hired_pretty
    date_to_unixts(hiredate) AS hired_unixts
FROM
    emp
ORDER BY
    hiredate

It’s now easy to convert the timestamp into a formatted date, using thedate() function as you loop through the result set.

Conclusion

You have now been introduced to (or reminded of) the date time functionality available in both Oracle and PHP. You should now have a foundation for working with dates and times in your Oracle / PHP applications. You should also have a gained a fair idea of the design and implementation decisions you’ll face when handling dates.

[Ref: http://www.oracle.com/technetwork/articles/fuecks-dates-098686.html]

 

How to Install Android Apps to the SD Card by Default & Move Almost Any App to the SD Card

image

Android apps install to the internal storage by default, but you can also set the SD card as your default install location. This trick allows you to move almost any app to the SD card – no root access required.

This tweak requires Android 2.2 or later. To change the default install location, you’ll need to use the ADB, or Android Debug Bridge, utility included with Google’s Android SDK.

Enable USB Debugging

First, you’ll need to enable USB debugging on your Android device. Open the Settings screen, tap Applications, and select Development.

Tap the USB Debugging checkbox to enable it. This will enable debug mode, allowing you to change the settings on your Android device from your computer. You may want to disable debug mode after completing this process.

Install the Android SDK

You’ll need to download and install Google’s Android SDK on your computer. If you don’t already have Oracle’s Java JDK installed on your computer, you’ll have to download and install it before installing the Android SDK.

After you’ve installed both the JDK and Android SDK, launch the SDK Manager from your Start menu.

The ADB utility isn’t installed by default. It’s included in the Android SDK Platform-tools package – select this package and click the Install button to download and install it.

After the process completes, connect your Android device to your computer with its included USB cable. Windows should locate the device and install the appropriate drivers automatically. If it doesn’t, you may have to download and install the appropriate drivers from your Android device’s manufacturer. Do not mount the device after connecting it – just plug it in.

Using ADB

Open a Windows Explorer window and navigate to the android-sdk\platform-tools folder. On Windows, you’ll find this folder at C:\Program Files (x86)\Android\android-sdk\platform-tools by default. Check C:\Program Files\Android\android-sdk\platform-tools if you’re using a 32-bit version of Windows.

Launch a Command Prompt window in this folder by pressing and holding the Shift button, right-clicking in the folder, and selecting Open command window here.

Run the adb devices command and you should see your connected Android device.

Run the following command to set the default install location to your SD card:

adb shell pm setInstallLocation 2

If you want to revert this change later and install apps to the internal storage by default, run this command:

adb shell pm setInstallLocation 0

0 represents your device’s internal storage, and is the default. 2 represents the external storage, whether it’s an SD card or USB storage.

Moving Apps to SD Card

Apps that refused to leave your system storage can now be moved to the external storage. For instance, below you’ll see screenshots of the Slacker Radio app. Before the change was made, the Move to USB Storage button was grayed out. After the change was made, the button is enabled and the app can be moved.

To move an app to the SD card, open the Settings screen, tap Applications, and select Manage Applications. Select the app you want to move and tap the Move button on its details screen.

A Warning

Some apps shouldn’t be installed to your SD card and should remain installed on the internal storage. The external storage is unavailable when your Android device is mounted on your computer, so apps that remain running all the time should be left on your internal storage. Widgets, launchers, animated wallpapers, and anything you want to use while your Android’s SD card is mounted on your computer should be left on the internal storage.

[Ref: http://www.howtogeek.com/114667/how-to-install-android-apps-to-the-sd-card-by-default-move-almost-any-app-to-the-sd-card/]

 

How to Setup Hotmail Push Email via Exchange ActiveSync on Android (with HTC Fix)

Android invasion, Sydney, Australia
Android invasion, Sydney, Australia (Photo credit: Pranav Bhatt)

Windows Live Hotmail has been enabling and supporting push email through Exchange ActiveSync (EAS) protocol. With push email, user can sync email messages, contacts and calendar between mobile device and Windows Live cloud, and any update such as new incoming email in Hotmail will be automatically pushed to the phone for instant notification.

Here’s the guide on how to setup and configure a Hotmail account with push email support on Android mobile phone device, through Exchange ActiveSync service. The guide works perfectly for smartphone running Android 2.2 and above, i.e. Android Gingerbread 2.3 and Android Honeycomb 3.0 or 3.1.

Note that HTC Mail that comes with smartphone such as HTC Desire, HTC Desire HD, and HTC Incredible S has known issue when setting up Hotmail through Exchange protocol. At the final step when adding a Hotmail Exchange account, HTC Mail app will return “Failed to create the account. Please try again later.” error. So far, only HTC Mail is known to have incompatibility issue with and does not work properly with Hotmail via EAS. Other Android mobile phone which comes with stock Android Mail app such as Google Nexus One and Google Nexus S should not facing such error.

To workaround the HTC Mail limitation, download and install the APK below, which is based on stock email app for Android Froyo 2.2:

Original Android Froyo FRG22 Email app 2.2: Mail.apk
Email app 2.2.1 (from CyanogenMod 6.1.1): Email.apk
Email app modified to bypass Exchange security: Email (Bypass Exchange Security).apk
Email app modified to support Exchange 2010 SP1: Email (Exchange 2010 SP1).apk

An alternative for which can be downloaded from Android Market, also for Android 2.2 Froyo phone, isImproved Email, though it’s unofficial app but similar with stock default email app on Android.

How to Setup Hotmail via Exchange for Push Email Support

  1. On Android device, open Email app.
  2. Enter the MSN/Windows Live Hotmail email address and password.
  3. Tap on Manual setup.

4.  Select Exchange as type of account.

5.  Configure the following information for Server settings:

Server: m.hotmail.com
Domain: <leave blank>
Username: <full email address>
Use secure connection (SSL): Enable
Accept all SSL certificates: Enable

In other version of Email app, Domain and Username fields are combined into one as “DomainUsername”. In this case, enter your Windows Live/MSN Hotmail emaill address into the field preceded by a “” (backslash). For example, [email protected]

Tap Next when done.

6.  You can then configure various Account options for the just added Hotmail account. To enable push email, set Email check frequency to Automatic (Push).

Tap Next when done.

Note: If your mobile phone is running on Android version 2.1 or below, do not sync contacts and calendar which is not fully compatible with older versions of Android.

7.  Enter a name for the account, such as Hotmail or Windows Live Hotmail, and tap Done.

New incoming emails will have notification alerts appear in the notification bar and/or through sound alerts.

[Ref: http://gadgets5.com/2011/05/how-to-setup-hotmail-push-email-via-exchange-activesync-on-android-with-htc-fix/]

Going Google-Free: The Best Alternatives to Google Services on the Web

Going Google-Free: The Best Alternatives to Google Services on the Web Face it: Google runs your life. The search giant turned web ecosystem owns your email, calendar, and even your voicemails. Your most important data lives on Google’s servers. What you may not realize is that, despite the quality of Google’s products, someone else is doing it better—and placing all your eggs in Google’s basket isn’t necessarily the best thing. Here’s a look at alternative services you can use in place of Google’s webapps.

Photo remixed from originals by Jan Kranendonk (Shutterstock) and Alfonso de Tomas (Shutterstock).

You might want to move away from Google entirely, whether you’re tired of things like the Google Plus-ification of your search results or the fact that Google’s mining ridiculous amounts of data and selling you to advertisers, or maybe you’re just plain tired of Google creating services it doesn’t actually improve over time. You may scoff at the idea of using Bing or other less popular competitors, but they’re quite good—sometimes even better—than Google. We’ve just become too entrenched to notice.

If you want to take a serious look at the alternatives, we did some digging and a lot of experimentation to find the best alternatives to Google’s most popular services (and we also asked you guys to share your favorites). Most of these services are still from big companies, like Microsoft or Yahoo!, but we’ve tried to include a few services off the beaten path as well. The fact of the matter is just that the highest quality services around are going to be from the companies with the most resources. Below, we’ve listed the best Google alternatives in each category, as well as a few runners-up we think are worth checking out.

The Best Search Alternative: DuckDuckGo

Going Google-Free: The Best Alternatives to Google Services on the WebGoogle Search, while great, isn’t without some big annoyances. From the new Google+ results on your search page to the Instant Preview layout to its constant desire to change your search terms to what it thinks is better, you might just be ready to switch to something new. Our favorite alternative is DuckDuckGo, a search engine that focuses on your privacy, while also packing itself with great features for power users, like searching specific sites with a bang (e.g. !lifehacker jailbreak iphone), keyboard shortcuts that help you navigate your results, and even integration with other services like Wolfram Alpha for quick answers to certain things (like unit conversions, calculations, and other facts).

Of course, DuckDuckGo falls short in a few areas. For all the engine’s cool features, it still doesn’t have some of the basic features other popular search engines will give you, like the ability to narrow your search down by date. If you find that DuckDuckGo isn’t giving you what you need, you can try one of the more traditional search engine alternatives below.

Other Alternatives: Bing, which offers related searches and your search history in the sidebar; Yahoo!, which offers links to the cached version of a page; and Ask, which can answer a lot of other questions without the need to sift through results (such as release dates for movies and video games). Of course, you could also try choosing your search engine based on what you’re searching for.

The Best Gmail Alternative: Hotmail

Going Google-Free: The Best Alternatives to Google Services on the WebGmail, frankly, is far and away our favorite web-based email. But if you’re truly committed to ditching Google—even your precious Gmail account—you could do much worse than Hotmail.. We’ve compared the two before, and not much has changed since last year. Hotmail has some pretty cool features, like one-click filters, SkyDrive integration for attachments, and embedded content, not to mention some Gmail favorites like conversation view and a great spam filter. Even its Bing-powered email search is very good, offering suggestions for certain operators but offering a ton more (many of which are the same as Gmail’s). It also has a great set of keyboard shortcuts, just like Gmail, that let you control the interface without touching your mouse. Also like Gmail, you can use it to manage your other, non-Hotmail mail accounts. If we weren’t in love with Gmail, this is the first place we’d go to host our email.

Other Alternatives: Yahoo! Mail, which requires a paid account for things like POP access or email forwarding; iCloud for seamless syncing with your iPhone; or Zoho Mail, which is ad-free and has a more desktop client-like interface but doesn’t support saved searches or advanced filters.

The Best Google Calendar Alternative: Zoho Calendar

Going Google-Free: The Best Alternatives to Google Services on the WebZoho Calendar is the only calendar application that can really stack up to Google Calendar. It has everything we love about GCal, like a “smart add” feature that lets you add events with one line of text, the ability to search your calendars, an “agenda” view that shows you just your upcoming events without the grid, and more. The interface is very similar to Google, so migration is dead simple, and sharing your calendars with others is as easy as copying a given calendar’s link.

That said, we want to give a shout out to our other favorite: simple pen and paper calendars. When we asked you guys what your favorite Google alternatives are, many of you noted that you’d use a paper planner over Google Calendar, and we don’t blame you. Paper calendars are about as quick and simple as they come: it’s easy to add events, and super quick to browse through your months (even easier than digital calendars, really). Alternatively, if you still want a digital calendar, you can always just use a calendar app on your phone and store it locally. There’s no reason you have to sync it to the web if you always have your phone with you.

Other Alternatives: Hotmail Calendar, which has a beautiful interface and Hotmail integration but doesn’t have a search feature (seriously); AOL Calendar, which surprisingly has a nice interface and a fair amount of features, and 1Calendar, which is light on advanced features like sharing but has a very nice interface, Facebook integration, and an upcoming mobile app. Yahoo! Calendar is not really worth your time due to its frustratingly bad interface.

The Best Google Maps Alternative: Bing Maps

Going Google-Free: The Best Alternatives to Google Services on the WebAs much as I hate having three services from the same company in this list, I couldn’t find anything I liked better than Bing Maps. Its interface is not only clean, but smooth as heck—even smoother than Google Maps—and its Streetside view is arguably even better than Google’s Street View, too. It’s super easy to use, and the images are all very high-res, meaning you can find what you’re looking for quite nicely (though it also has a 360 view if you prefer something more akin to Google Street View). It also has live traffic views, satellite images, and great pages for businesses that you find via the Maps search. And, of course, you can save places you want to visit later, as well as find driving, public transit, or walking directions to just about anywhere. Zooming in with the mouse wheel is a bit overagressive, but if you can get past that, it’s a fantastic alternative to Google Maps—in fact, I might even like it better.

Other Alternatives: Mapquest, which has a cool “MQ Vibe” feature that helps you find the best restaurants, shopping, and other activities in a specific area (but only works in the US); OpenStreetMap, which is community-driven and has lots of plugins for things like directions and 3D views; and Yahoo! Maps, which frankly isn’t worth your time compared to other service, and lacks in a lot of basic features like public transit directions and saving your home location.

The Best Google Reader Alternative: NetVibes

Going Google-Free: The Best Alternatives to Google Services on the WebEven if you aren’t looking to ditch Google Reader, you should check out NetVibes. You can add and read feeds just like Google Reader, though it also has a really cool widget view that turns your RSS feeds into a more visual, newspaper-like layout in your browser. You can give higher preference to certain sites, see the top stories, and (as with the feed view) see how many articles you haven’t read. It’ll also link you up with the Twitter accounts of the sites you add, so you can see what they’re saying there too. It’s also got a bunch of different snazzy themes to choose from, and sharing features coming out of its nose, for sending articles by email, through Facebook and Twitter, and more.

Other Alternatives: NewsBlur is another great alternative to Reader, with a similar (but very desktop client-like) interface, though it could stand to be a bit cleaner. Other than that, there aren’t a ton of good, browser-based online RSS services out there, but you can always store your RSS feeds locally on your desktop or phone instead. Feedly is a very popular service worth mentioning, but it does sync with Google, so you aren’t truly escaping Google by using it.

The Best Picasa Web Alternative: Flickr

Going Google-Free: The Best Alternatives to Google Services on the WebThis one’s a no-brainer: Flickr is one of the most popular photo sharing sites on the net, and that’s because it’s very well put together. While Picasa has Google integration and 1GB of free space, Flickr lets you license the photos as you see fit, and has a bunch of really cool social features that get you in touch with like-minded photographers (and gives others the chance to see your work). It also has a built-in image editor for you to tweak your photos, which is pretty great.

Other Alternatives: SmugMug, which provides a beautiful, customizable interface for viewing your photo collection, though lacks the community that makes Flickr so strong; and Dropbox, which is not only a dead simple way to get your photos in the cloud, but also offers a barebones album view for showing them to your friends.

The Best Google Docs Alternative: Office Web Apps

Going Google-Free: The Best Alternatives to Google Services on the WebThis is another area that Google wouldn’t win even if it were in the picture. Microsoft’s Office Web Apps let you edit documents, spreadsheets, and presentations from its web interface, designed after the Office desktop programs. It has the ribbon, built-in support for Microsoft SkyDrive, and tons of collaboration features for working on documents with your friends and co-workers. Plus, since it’s made by Microsoft, compatibility with Office documents is top-notch, which you won’t get with Google Docs.

Other Alternatives: Zoho Docs, which has some neat formatting features, collaboration features, and a ribbon-less interface (if you aren’t a Microsoft fan); and Evernote, which isn’t an Office suite per se, but a webapp that you guys mentioned was your first go-to for online document editing.

The Best Google Voice Alternative: Phonebooth

Going Google-Free: The Best Alternatives to Google Services on the Web There is no true Google Voice alternative on the market. When you look at the feature set and the price, Google Voice is really the only service of its type, and once you use it, it’s hard to pull away. If you absolutely must, though, the most comparable is probably Phonebooth. They have a free service that gives you a local phone number for free, lets you forward calls to your different phones, and transcribe voicemails, just like Google Voice. The free version gets you 200 minutes of inbound calling per month, with extra minutes costing 3¢ each. You can’t record any of your calls, nor can you make any outbound calls on the free service. You also can’t send SMS messages from that number or from your browser (though you could always use a service like DeskSMSinstead). You can also upgrade Phonebooth to the paid, PKR1,915/month plan which includes unlimited minutes, outgoing calls, and more business-oriented features.Other Alternatives: Google Voice has no true alternatives. You can try some similar, but not equal, services like Line2, which adds a second line to your mobile device and can forward your calls for PKR957 a month; or RingCentral, which is pretty expensive and only available for iPhone (and also doesn’t include an SMS service).


This is far from a comprehensive list of Google’s services or the alternatives out there, but these were our favorites after lots of testing. We wish there had been a few more independent services worth featuring, but they’re surprisingly hard to find (that is, if you care about a good feature set). Of course, if you want to see even more, check out our previous Ask the Readers on the subject, or share your own favorite alternatives in the comments below.

Ref: http://lifehacker.com/5876794/going-google+free-the-best-alternatives-to-google-services-on-the-web]

Windows 8 Release Preview now available!

Microsoft has recently released Windows 8 Release Preview. This is much better version than the Consumer Preview, but still there are lots of questions, but time will tell. Anyway, you can download Windows 8 Release Preview directly from Microsoft site here.

I’ll post some updates and reviews on Windows 8 Release Preview. So come back soon 🙂

Installing MS Web Deploy on different port

Web Deployment is a tool from Microsoft to simplify migration, management, and deployment of IIS web servers, web applications, and web sites. When you install Web Matrix it is installed by default. When installed it listens on port 80. If you are using other server like Apache on your system that also listens on port 80 then you won’t be able to start Apache due to conflict in the port. The solution is either use a different port for Apache like 8080. If you want to do that then other solution is to remove the web deploy and install it from command line. Here are the steps of doing this.

1. Uninstall Web Deploy from Add/Remove programs.

2. Download Web Deploy from

v2: http://www.iis.net/download/webdeploy

v3: http://www.microsoft.com/download/en/details.aspx?id=27430

3. Run the command prompt in Administration mode.

4. Run the following command:

#> msiexec /I <msi filename> /passive ADDLOCAL=ALL LISTENURL=http://+:<port>/MsDeployAgentService2/

e.g #> msiexec /I WebDeploy_x86.msi /passive ADDLOCAL=ALL LISTENURL=http://+:85/MsDeployAgentService2/

Thats it. Now you can use Apache on port 80 and Web Deploy will use the different port.

Installing Windows 8 Consumer Preview experience

The new Windows 8 Start Screen, making use of ...
Image via Wikipedia

Few months back Microsoft launched Windows 8 Developer Preview. Majority of people try to install beta or pre-launch versions on virtual machines. So did I, but there were lot of issues in installing Windows 8 Developer Preview and I posted a solution at http://mjawaid.wordpress.com/2011/09/15/windows-8-installation-error-hal_initialization_failed/.

On Feb 29 2012, Microsoft launched Windows 8 Consumer Preview. And again I tried to install it on a virtual machine and this time no errors 🙂 . While I was expecting some issues as there were issues before and this time Microsoft mentioned that installing on virtual machine could have problems so install on real system. But fortunately all things went fine and it seems Microsoft has improved a lot in this latest version. As I wasn’t really impressed with the developer preview, but consumer preview seems to be better.

I installed consumer preview using VMWare Player 4.0.2 build-591240 on a 64 bit machine. And I downloaded the 64-bit version of consumer preview. I am not sure if people trying on 32-bit are having issues. But I will try to install it on my home laptop. See how that goes?