Monday 1 November 2010

Time Difference problem in PHP and MySQL and its solution

Time Difference problem in PHP and MySQL and its solution
Author: Abinash Grahacharya
In many projects we need to generate the time difference between the current date and the date the record was created. For example, suppose you want to get the date difference of number of comments related to present date and time. What possibilities come to your mind ? First I thought of getting the date time from the field of the table and call a function which will compare it with the present date and time and return the date difference string to show. But the results I got were not correct. Why ? Because the value in the database was in yyyy-mm-dd hr:min:sec format. So, with PHP function we have to generate the current time in the same format to calculate the difference.
In php to get present time in yyyy-mm-dd hr:min:sec format
To get date in the format we have to use the date function like date('Y-m-d H:i:s');
 
NOTE : Y is for year in 4 digit format, m for month, d for days, H for hours,i for minutes and s for seconds- For different time stamp the H value will give different results so you can not get the correct H value always. So to get time difference in php is difficult and sometime buggy.
 
To get the difference it is better to get it through a MySQL query and call the function to return the difference string
 
Lets the rules be
1 - if there is no minutes value and no hr value means if hour and minutes is 0 show second else dont show seconds
2 - if days more then 0 days do not show the hours and minutes or seconds
3 - if months be more then 0 show months and days
4 - if years more then 0 show years, months and days
 
 
Main M?YSQL query part
Suppose your Field name is `CreatedDate` and you want to generate the difference on this field which is in datetime format ( yyyy-mm-dd hr:min:sec) and suppose the table name is Comments
 
Your Query will be :
 
$result = mysql_query("SELECT *,TIMEDIFF(NOW(),`CreatedDate`) as dataDif,TIMESTAMPDIFF(YEAR,`CreatedDate`,NOW()) as years ,(TIMESTAMPDIFF(MONTH,`CreatedDate`,NOW()) - (TIMESTAMPDIFF(YEAR,`CreatedDate`,NOW()) * 12)) as months,(TIMESTAMPDIFF(DAY,`CreatedDate`,NOW()) - (TIMESTAMPDIFF(MONTH,`CreatedDate`,NOW()) * 30)) as days FROM `Comments`
WHERE -------------  your conditions ------------- ");
 
you can see there is select * to select all fields [ Do it if you need all fields of the table else the required fields with comma separated form ] and after that 4 cluses
 
1 - TIMEDIFF(NOW(),`CreatedDate`) as dataDif
2 - TIMESTAMPDIFF(YEAR,`CreatedDate`,NOW()) as years
3 - (TIMESTAMPDIFF(MONTH,`CreatedDate`,NOW()) - (TIMESTAMPDIFF(YEAR,`CreatedDate`,NOW()) * 12)) as months
4 - (TIMESTAMPDIFF(DAY,`CreatedDate`,NOW()) - (TIMESTAMPDIFF(MONTH,`CreatedDate`,NOW()) * 30)) as days
 
By these 4 different cluses i  am generating 4 different columns called dataDif,years,months,days 
Using  the while loop you can get these values one by one  :
 
//php part
 
/*******************************************************************************/
while($rst_results = mysql_fetch_array($results))
{
     //showinf the difference string by passing 4 values
     echo dateTimeDiff($rst_results['dataDif'],$rst_results['years '],$rst_results['months'],$rst_results['days']);
}
/*******************************************************************************/
 
 
You can see the php part we are calling the function dateTimeDiff with 4 parameters that we are getting from the Query : i will write the function below before that i want to tell you the format and about the 4 cluses
 
1 - TIMEDIFF(NOW(),`CreatedDate`) as dataDif
 
TIMEDIFF is a mysql function we are passing NOW() [ a mysql function generate present time in yyyy-mm-dd hr:min:sec format ] and CreatesDate which is the fields value - it will generate a new columns as dateDif in hours:min:seconds format hours can be 234 hours between 2 days
 
2 - TIMESTAMPDIFF(YEAR,`CreatedDate`,NOW()) as years
 
TIMESTAMPDIFF is also a mysql function in which we can generate diference date , month or years by passing first parameter
here you can see the first parameter is YEAR so it will just return the number of YEARS difference.
 
3 - (TIMESTAMPDIFF(MONTH,`CreatedDate`,NOW()) - (TIMESTAMPDIFF(YEAR,`CreatedDate`,NOW()) * 12)) as months
 
After years i need to get the remaining months in difference so here i have generate the MONTHS as TIMESTAMPDIFF(MONTH,`CreatedDate`,NOW())
which will generate the months difference between 2 dates and after that subtracting the number of months of years i got
 
means suppose you got 2 years so if - TIMESTAMPDIFF(MONTH,`CreatedDate`,NOW())  is giving you 28 months of 2 dats difference then you need to show only 4 months as for 2 years 12*2 = 24 months subtracted so the string will be : 2 years 4 months
 
 
4 - (TIMESTAMPDIFF(DAY,`CreatedDate`,NOW()) - (TIMESTAMPDIFF(MONTH,`CreatedDate`,NOW()) * 30)) as days
 
In the same way we need to generate the left days so : number of days - (months*30) . (TIMESTAMPDIFF(DAY,`CreatedDate`,NOW())  will return the number of days and TIMESTAMPDIFF(MONTH,`CreatedDate`,NOW()) will return the number of months , So in this way we can get the left days
 
 
 
dateTimeDiff Function in PHP
function dateTimeDiff($datadiff,$years,$months,$days)
 {
  $string = '';
  if($years != 0)
  {
   $string = $string.$years." years ";
  }
  if($months != 0)
  {
   $string = $string.$months." months ";
  }
  if($days != 0)
  {
   $string = $string.$days." days ";
  }
  if($days == 0)
  {
   $datadiff = explode(":",$datadiff );
   $hr  = $datadiff[0];
   $min = $datadiff[1];
   $sec = $datadiff[2];
   if($hr != 0)
   {$string = $string.",".$hr." hours "; }
   if($min != 0)
   {$string = $string.$min." minuts "; }
   if($min == 0)
   {$string = $string.$sec." Seconds "; }
  }
  $string = $string." ago ";
  return $string;
 }
 
/* According to your requirement for date difference strin you can change this function to get your formated string*/
 
I think this will help you to get the correct format of date difference in PHP / MYSQL :)

Sunday 26 September 2010

Installing Samba on Ubuntu 10.04

1. Installation


The first step is to install the samba package. From a terminal prompt enter:

sudo apt-get install samba

That's all there is to it; you are now ready to configure Samba to share files.


2. Configuration

The main Samba configuration file is located in /etc/samba/smb.conf. The default configuration file has a significant amount of comments in order to document various configuration directives.


Not all the available options are included in the default configuration file. See the smb.conf man page or the Samba HOWTO Collection for more details.


First, edit the following key/value pairs in the [global] section of /etc/samba/smb.conf:


workgroup = EXAMPLE

...

security = user

The security parameter is farther down in the [global] section, and is commented by default. Also, change EXAMPLE to better match your environment.



Create a new section at the bottom of the file, or uncomment one of the examples, for the directory to be shared:



[ananta_samba_server]

comment = Ubuntu File Server Share

path = /home/ananta

browsable = yes

read only = no


comment: a short description of the share. Adjust to fit your needs.

path: the path to the directory to share.


browsable: enables Windows clients to browse the shared directory using Windows Explorer.

read only: determines if the share is read only or if write privileges are granted. Write privileges are allowed only when the value is no, as is seen in this example. If the value is yes, then access to the share

3. There are two steps to creating a user. First we’ll run the smbpasswd utility to create a samba password for the user.




sudo smbpasswd -a



Next, we’ll add that username to the smbusers file.



sudo gedit /etc/samba/smbusers



Add in the following line, substituting the username with the one you want to give access to. The format is = “”. You can use a different samba user name to map to an ubuntu account, but that’s not really necessary right now.



= “

ex.
ananta='ananta'

--------------------------------------------------------------------------------





Where is /etc/init.d/samba in 10.04?




Two things have happened - "upstart" has replaced the old way of starting services and the "samba" service has been replaced by the old way of separating the smbd and nmbd daemons.


So the way you need to restart samba is now this way:


sudo service smbd restart

sudo service nmbd restart


Samba installation is done. Go to Windows , to Map Network Drive
file://ip/ananta_samba_server

:)

Friday 9 July 2010

sub-process usr bin dpkg returned an error code 1 on ubuntu

Please try the following command sequence:


sudo dpkg --configure -a

sudo apt-get -f install

sudo apt-get --fix-missing install

sudo apt-get clean

sudo apt-get update

sudo apt-get upgrade

sudo apt-get dist-upgrade

sudo apt-get clean

sudo apt-get autoremove

sudo aptitude update

sudo aptitude install sysvinit-utils

source: https://answers.launchpad.net/ubuntu/+question/53098

Tuesday 4 May 2010

What Steeve Jobs Says???

'You've got to find what you love,' Jobs says




This is the text of the Commencement address by Steve Jobs, CEO of Apple Computer and of Pixar Animation Studios, delivered on June 12, 2005.



I am honored to be with you today at your commencement from one of the finest universities in the world. I never graduated from college. Truth be told, this is the closest I've ever gotten to a college graduation. Today I want to tell you three stories from my life. That's it. No big deal. Just three stories.



The first story is about connecting the dots.



I dropped out of Reed College after the first 6 months, but then stayed around as a drop-in for another 18 months or so before I really quit. So why did I drop out?



It started before I was born. My biological mother was a young, unwed college graduate student, and she decided to put me up for adoption. She felt very strongly that I should be adopted by college graduates, so everything was all set for me to be adopted at birth by a lawyer and his wife. Except that when I popped out they decided at the last minute that they really wanted a girl. So my parents, who were on a waiting list, got a call in the middle of the night asking: "We have an unexpected baby boy; do you want him?" They said: "Of course." My biological mother later found out that my mother had never graduated from college and that my father had never graduated from high school. She refused to sign the final adoption papers. She only relented a few months later when my parents promised that I would someday go to college.



And 17 years later I did go to college. But I naively chose a college that was almost as expensive as Stanford, and all of my working-class parents' savings were being spent on my college tuition. After six months, I couldn't see the value in it. I had no idea what I wanted to do with my life and no idea how college was going to help me figure it out. And here I was spending all of the money my parents had saved their entire life. So I decided to drop out and trust that it would all work out OK. It was pretty scary at the time, but looking back it was one of the best decisions I ever made. The minute I dropped out I could stop taking the required classes that didn't interest me, and begin dropping in on the ones that looked interesting.



It wasn't all romantic. I didn't have a dorm room, so I slept on the floor in friends' rooms, I returned coke bottles for the 5¢ deposits to buy food with, and I would walk the 7 miles across town every Sunday night to get one good meal a week at the Hare Krishna temple. I loved it. And much of what I stumbled into by following my curiosity and intuition turned out to be priceless later on. Let me give you one example:



Reed College at that time offered perhaps the best calligraphy instruction in the country. Throughout the campus every poster, every label on every drawer, was beautifully hand calligraphed. Because I had dropped out and didn't have to take the normal classes, I decided to take a calligraphy class to learn how to do this. I learned about serif and san serif typefaces, about varying the amount of space between different letter combinations, about what makes great typography great. It was beautiful, historical, artistically subtle in a way that science can't capture, and I found it fascinating.



None of this had even a hope of any practical application in my life. But ten years later, when we were designing the first Macintosh computer, it all came back to me. And we designed it all into the Mac. It was the first computer with beautiful typography. If I had never dropped in on that single course in college, the Mac would have never had multiple typefaces or proportionally spaced fonts. And since Windows just copied the Mac, its likely that no personal computer would have them. If I had never dropped out, I would have never dropped in on this calligraphy class, and personal computers might not have the wonderful typography that they do. Of course it was impossible to connect the dots looking forward when I was in college. But it was very, very clear looking backwards ten years later.



Again, you can't connect the dots looking forward; you can only connect them looking backwards. So you have to trust that the dots will somehow connect in your future. You have to trust in something — your gut, destiny, life, karma, whatever. This approach has never let me down, and it has made all the difference in my life.



My second story is about love and loss.



I was lucky — I found what I loved to do early in life. Woz and I started Apple in my parents garage when I was 20. We worked hard, and in 10 years Apple had grown from just the two of us in a garage into a $2 billion company with over 4000 employees. We had just released our finest creation — the Macintosh — a year earlier, and I had just turned 30. And then I got fired. How can you get fired from a company you started? Well, as Apple grew we hired someone who I thought was very talented to run the company with me, and for the first year or so things went well. But then our visions of the future began to diverge and eventually we had a falling out. When we did, our Board of Directors sided with him. So at 30 I was out. And very publicly out. What had been the focus of my entire adult life was gone, and it was devastating.



I really didn't know what to do for a few months. I felt that I had let the previous generation of entrepreneurs down - that I had dropped the baton as it was being passed to me. I met with David Packard and Bob Noyce and tried to apologize for screwing up so badly. I was a very public failure, and I even thought about running away from the valley. But something slowly began to dawn on me — I still loved what I did. The turn of events at Apple had not changed that one bit. I had been rejected, but I was still in love. And so I decided to start over.



I didn't see it then, but it turned out that getting fired from Apple was the best thing that could have ever happened to me. The heaviness of being successful was replaced by the lightness of being a beginner again, less sure about everything. It freed me to enter one of the most creative periods of my life.



During the next five years, I started a company named NeXT, another company named Pixar, and fell in love with an amazing woman who would become my wife. Pixar went on to create the worlds first computer animated feature film, Toy Story, and is now the most successful animation studio in the world. In a remarkable turn of events, Apple bought NeXT, I returned to Apple, and the technology we developed at NeXT is at the heart of Apple's current renaissance. And Laurene and I have a wonderful family together.



I'm pretty sure none of this would have happened if I hadn't been fired from Apple. It was awful tasting medicine, but I guess the patient needed it. Sometimes life hits you in the head with a brick. Don't lose faith. I'm convinced that the only thing that kept me going was that I loved what I did. You've got to find what you love. And that is as true for your work as it is for your lovers. Your work is going to fill a large part of your life, and the only way to be truly satisfied is to do what you believe is great work. And the only way to do great work is to love what you do. If you haven't found it yet, keep looking. Don't settle. As with all matters of the heart, you'll know when you find it. And, like any great relationship, it just gets better and better as the years roll on. So keep looking until you find it. Don't settle.



My third story is about death.



When I was 17, I read a quote that went something like: "If you live each day as if it was your last, someday you'll most certainly be right." It made an impression on me, and since then, for the past 33 years, I have looked in the mirror every morning and asked myself: "If today were the last day of my life, would I want to do what I am about to do today?" And whenever the answer has been "No" for too many days in a row, I know I need to change something.



Remembering that I'll be dead soon is the most important tool I've ever encountered to help me make the big choices in life. Because almost everything — all external expectations, all pride, all fear of embarrassment or failure - these things just fall away in the face of death, leaving only what is truly important. Remembering that you are going to die is the best way I know to avoid the trap of thinking you have something to lose. You are already naked. There is no reason not to follow your heart.



About a year ago I was diagnosed with cancer. I had a scan at 7:30 in the morning, and it clearly showed a tumor on my pancreas. I didn't even know what a pancreas was. The doctors told me this was almost certainly a type of cancer that is incurable, and that I should expect to live no longer than three to six months. My doctor advised me to go home and get my affairs in order, which is doctor's code for prepare to die. It means to try to tell your kids everything you thought you'd have the next 10 years to tell them in just a few months. It means to make sure everything is buttoned up so that it will be as easy as possible for your family. It means to say your goodbyes.



I lived with that diagnosis all day. Later that evening I had a biopsy, where they stuck an endoscope down my throat, through my stomach and into my intestines, put a needle into my pancreas and got a few cells from the tumor. I was sedated, but my wife, who was there, told me that when they viewed the cells under a microscope the doctors started crying because it turned out to be a very rare form of pancreatic cancer that is curable with surgery. I had the surgery and I'm fine now.



This was the closest I've been to facing death, and I hope its the closest I get for a few more decades. Having lived through it, I can now say this to you with a bit more certainty than when death was a useful but purely intellectual concept:



No one wants to die. Even people who want to go to heaven don't want to die to get there. And yet death is the destination we all share. No one has ever escaped it. And that is as it should be, because Death is very likely the single best invention of Life. It is Life's change agent. It clears out the old to make way for the new. Right now the new is you, but someday not too long from now, you will gradually become the old and be cleared away. Sorry to be so dramatic, but it is quite true.



Your time is limited, so don't waste it living someone else's life. Don't be trapped by dogma — which is living with the results of other people's thinking. Don't let the noise of others' opinions drown out your own inner voice. And most important, have the courage to follow your heart and intuition. They somehow already know what you truly want to become. Everything else is secondary.



When I was young, there was an amazing publication called The Whole Earth Catalog, which was one of the bibles of my generation. It was created by a fellow named Stewart Brand not far from here in Menlo Park, and he brought it to life with his poetic touch. This was in the late 1960's, before personal computers and desktop publishing, so it was all made with typewriters, scissors, and polaroid cameras. It was sort of like Google in paperback form, 35 years before Google came along: it was idealistic, and overflowing with neat tools and great notions.



Stewart and his team put out several issues of The Whole Earth Catalog, and then when it had run its course, they put out a final issue. It was the mid-1970s, and I was your age. On the back cover of their final issue was a photograph of an early morning country road, the kind you might find yourself hitchhiking on if you were so adventurous. Beneath it were the words: "Stay Hungry. Stay Foolish." It was their farewell message as they signed off. Stay Hungry. Stay Foolish. And I have always wished that for myself. And now, as you graduate to begin anew, I wish that for you.



Stay Hungry. Stay Foolish.



Thank you all very much.



Source: http://news-service.stanford.edu/news/2005/june15/jobs-061505.html

Mystries of Life

There were about 10 people in a room. I knew all of them. They were mine close friends. We were having some kind of discussion. There was a table on the corner of the room where one of us was sitting. There were some books on the corner and that person who was sitting on the table picked a book from the pile and opened. He read the book and said this book tells the future of every person. Every person's life was written in that book. We read one person's life. It was very short. As it was written on that book the person died same way two three days before.




Everyone choked and feared. I wanted to know what’s on my future. But I was also afraid what if i am also dying soon. But I wanted to see. I couldn't read myself so I asked that person to tell what’s on my future. I didn’t want to see everything of my future. I thought about many things that I wanted to do in my life. I have so many hopes and aims. I also have some responsibility for my family. I want to get married and see my children growing. I thought I have to do more and I can’t die soon. Then I wanted him to look for one thing only. I don't know why I asked this question to him. But I guess it’s the first step of my life that I have to do in future. I asked him to see if my girl whom I love will be in my life or not. I wanted to know whether we will be together or not. He read and said you will get married soon. I was happy. I could feel the joy. But still somewhere beneath I was feeling something was wrong. The joy was mixture of happiness and a little of dismay.



He spoke again "Wait there is something more you may not like it. You will be together for few years then because of your habit you guys will get separated. Then after like 10 -12 years you guys will be together again. I wonder what kind of habit is that. What would make her leave me? And then I decided to change myself. I thought I would change myself according to what she wants. And we would be together always. So everyone in the room got happy with my decision. But the person looked at the last page of the book there was one note. He read that note and said "Oh NO". Then we all get attention to that person He said “whoever reads this book, His future changes from what is written here to different one and he dies within a week"



We all were looking at him not knowing what we should say to comfort him. Actually in this situation there is nothing to say or to give comfort. He said again “at least you got benefit from this book as you got chance to change yourself to be together with your wife on the other hand I am going to die soon. I am paying for that. Everybody was silent and the environment was tense.



We all started to think whether the person who reads that book dies or all other person who also listen to that book die. We all got confused whether only that person die or we all who listen to that book die. I was also thinking same thing. Am I going to die soon? Then suddenly I felt something on my neck. Something was stuck on my neck I was worried was it the end of my life is this cause of my death, this is too early am i going to die soon then I got suffocated and I wake up.

Sunday 21 March 2010

Do i believe in astrology?

Well im not sure if i believe in astrology or not but sometimes i prefer to look for it. Today i was just surfing the net there was a column about the astrology on msn.com I clicked the link and found following content about Aries, being a Aries i read it kind of like it. If you want to know more about Aries then you can go through the following content that i got from the site.....

As the first sign of the Zodiac, the presence of an Aries almost always indicates the beginning of something energetic and boisterous. Not much holds this sign back. They're eager, dynamic, quick, and competitive. When it comes to getting the ball rolling, an Aries is the best. Pioneering everything from work-related projects to parties with friends, these folks go for the gusto.


Friends and Family

"Activity" is the key word for this sign, and wow, can they ever go! The Aries is on the go constantly. When it comes to Aries' friends, the more variety, the better. It takes a range of different personalities to complete Aries' circle of friends. Quick and easy to get along with, an Aries native makes an incredible amount of connections in a lifetime. Long-term friends are something altogether different, though. Only those who are equally as energetic and able to keep up are apt to make it in the long run.

Independent and ambitious, Aries natives make their own way as early in their lives as possible. While staying in touch with family can leave much to be desired, these loved ones are always in Aries' heart. A direct and forthright approach can be expected almost always, and when a sentiment is expressed, it's bound to be sincere.

Career and Money

This is the area of life where Aries is apt to shine the brightest. Ambitious, creative, and often driven by the need to be the best they can be, the workplace can be the perfect platform. Born leaders, this sign is far more comfortable taking charge than taking orders. Their ability to envision allows the steps to fall naturally into place. All the Aries has to do is follow his or her own lead.

When faced with a challenge, Aries will quickly assess the situation and arrive at a solution - whatever it takes to get the plan off the ground! Competition only makes this fire sign burn brighter. Aries people truly move through life with their own agendas, which are always going to be their primary focal point. Careers that are strong choices include real estate agent, salesperson, manager, conductor, and business owner or entrepreneur.

Even though the Aries is wise enough to save for a rainy day, this isn't often the case. Because they prize excitement, shopping, gambling, and playing the market are far more appealing. They aren't focused on the future. In fact, living for the moment is the true Aries philosophy. Money is rarely scarce because of the love of working, but it can be spent almost as quickly as it's made. The one thing you can be absolutely sure of is that an Aries will have as much fun as possible!

Love and Sex

This wildly flirtatious fire sign certainly takes the initiative when it comes to romance. They're quick to move when someone catches their eye. But to keep an Aries' attention, the person needs to be as energetic and as exciting as they are. This is a passionate sign that loves adventure. When a fire burns, it really burns! Whirlwind romances are common for the Aries personality. But once love sets in, it's generally for life. As long as there's plenty of spice and excitement to keep the blood pumping, the relationship will be strong and long-lasting.

ARIES TIDBITS

Health

Each sign has a part of the anatomy attached to it, making this the area of the body that is most sensitive to stimulation. The anatomical areas for Aries are the head, face, brain, and upper teeth.

Ruling Planet

The ruling planet for Aries is Mars. This powerful planet rules ambition, force, power, competition, animal nature, desire, sexual energies, war, tools, violence, and courage.

Color

The color of choice for Aries is red.

Lucky Numbers

Aries' lucky numbers are 1 and 9.

Compatibility

Aries natives are most compatible with fellow Aries, Leo, and Sagittarius individuals.


Opposite Sign

The opposite sign of Aries is Libra.

The Perfect Gift

A sporty car, metal jewelry, a nice steak, high-tech gadgets

Likes

Comfortable clothes, taking the lead, physical challenges, individual sports

Dislikes

Inactivity, delays, work that doesn't use one's talents

Famous Aries

Russell Crowe, Sarah Jessica Parker, Matthew Broderick, Mariah Carey

Best travel destinations

England, France, Italy (especially Naples and Florence)

Strengths

Courage, determination, self-confidence, enthusiasm

Weaknesses

Impatience, silly arguments, allowing fear to limit choices

Charismatic marks

Athletic body, youthful attitude, a need to take the lead

Best environment

Any situation that requires action, courage in the face of fear, competition, and freedom of choice. Aries individuals are better outside being active than staying close to home.

Monday 22 February 2010

Deleting GPT protected Partition

It's time to transfer all my files from Lab's Computer to my New (yes i said new) Seagate Portable Hard Drive. But i am using Microsoft's antique operating system Windows XP which do not allow us to write when the disk has GPT protection. So i had to look through the web to find out how trespass the protected disk. I found some does commands from the blog of Paul Gu.
We actually can convert a GPT disk to MBR by using the clean command in DiskPart, which will remove all data and partition structures from the disk.
The steps we need to follow are as follows:
In  DOS command prompt type “DiskPart” in command line.
c:\ diskpart
you will see
DISKPART>
then type “list disk” 
DISKPART>list disk
then select disk which has GPT protection 
DISKPART>select disk 1
you will see 
disk 1 is selected
DISKPART>
then type "clean" command to remove GPT disk from the current in-focus disk by zeroing sectors.
DISKPART>clean
Go  to Disk Management, Right click on disk info, choose “Initialize Disk”.