Little jQuery.extend gotcha

jQuery.extend() is a very powerful function for merging two objects or for extending jQuery with custom plugins.

There is but one little gotcha to think about: as in most function calls the order of parameters matters 🙂

Following two fragments of code yields different objects

var a = {
  aa : '1'
  , bb : '2'
  , cc : '3'
};

var b = {
  aa : '11'
  , bb : '22'
  , dd: 3
};

var result_a = $.extend({}, true, a, b);
var result_b = $.extend({}, true, b, a);

The result will be this:

Notice that I use $.extend({}, true, a, b) instead of $.extend(a, b). The first parameter (which is optional) is the target which should receive merged properties. If none is given than the first object is extended automatically.

Criticism of AmWay, HerbaLife and Kiyosaki’s followers in general

Motto “Man speaks about what he doesn’t live”

I am reading Kiyosaki’s famous book Rich Dad, Poor Dad and I find it very inspiring. Kiyosaki is also the author of board game Cashflow. Both book and game are very good. But to play the game I had to find someone who has it. I met a group of people studying Kiyosaky’s books. They were members of some company but I did not find the actual name. I was told that the name is changing quite often, and that there is no single company but whole family of companies. They claim not to be AmWay or HerbaLife, because of the bad name these two companies gained in the past, but the principle behind this one is very similar.  For simplicity’s sake I will call these people Kiyosaky’s followers.

These people have one thing in common: They all dream about getting rich effortlessly. They promise you that your income will double in a few years for just one or two hours work a day. They promise it will not be just double, but multiple times higher than it is now. That’s very tempting, isn’t it? Who would not want it? But it is just an illusion. I think that most people from HerbaLife-like companies will never get rich. Here is why.

Bad Motivation

HerbaLife people want to get rich without actually creating anything valuable. They dream about driving a fancy car, getting up at 10 o’clock and living in Hawaii in a financial freedom. The don’t dream about running a startup, inventing something useful, building an killer app or contributing to the world. They are in fact just lazy dreamers.

Premature Satisfaction

You will be told on their meetings to tell your dreams aloud. I advise you not to do it. Because if you do and people will like your dream, they will tell you how great your dream is and how high-potential person your are. But you have not yet created anything and yet you have already received some kind of satisfaction. This will decrease your motivation to actually pursue your dream and full fill it. It is better if you just (humbly) write your dream down only for your self. Make a personal commitment  and follow it daily. Only after you have kept doing it for lets say half a year, and feel strong enough, tell someone about it. But only to small group of good friends who know you really trust. Don’t go public too early.

Creating money out of nothing

This is one of the things I don’t like about Kiyosaki. In one chapter he explains how he created lot of money out of nothing by buying confiscated house for a fraction of its price and selling it shortly afterwards for full price. He earned about 60 000$ in 5 hours. At the risk of being old fashioned I think this is kind of immoral. I understand that if he had not done than someone else would have. I am not naive, this world is hard and it will always be. But is it right to get rich on someone else’s misfortune? Do you have the stomach for it? If you do you are likely to become a rich asshole.

 

In general I agree with most of what Kiyosaki says, especially with his opinion on our educational system, but I just cant buy his idea of “creating money out of nothing”. Money comes out of people’s labour. Even if you invest in stocks or own a company. If you just create money (read “make money”), you are not creating something valuable but only green papers.

 

Convert local time to UTC time in Javascript

This might come in handy. Simple function which converts local time to UTC (Universal Coordinated Time). It accepts single argument of type Date.

//converts local time to UTC (Universal Time)
function toUTC(/*Date*/date) {
    return Date.UTC(
        date.getFullYear()
        , date.getMonth()
        , date.getDate()
        , date.getHours()
        , date.getMinutes()
        , date.getSeconds()
        , date.getMilliseconds()
    );
} //toUTC()

Proposal for WordPress plugin – customScript


You will only see the demo animation if you click link to this post

Motivation

For this blog I am using WordPress and I am quite happy with it, but I miss one feature – the ability to add
custom javascript code to given post. I do not want to have separate demo pages when I am want to demostrate
some piece of code or something. Sometimes I need it to modify the Html structure of page, or add a simple
animation or for whatever just crosses my mind:) I’ve tried to write my own wordpress plugin for this, but I don’t have enough time to finish it. I have already
spent three evenings on it. Writing a WP plugin proved to be much more difficult task than I thought it to be.
So I deciced to crowdsource the idea. Hopefully someone will read this and write the plugin 🙂 Anyway, there is a workaround, but it is not very convenient. And it requires access to file system, so it will
not work on wordpress.com hosting.

Workaround

If you really need to add custom javascript to some Worpress code, use this workaround:

  • install Single Post Template Plugin by Nathan Rice
  • create your own template page for single post
  • it must contain
  • on the first lines:
  • /* Single Post Template: [Descriptive Template Name]
  • Description: This part is optional, but helpful for describing the Post Template */
  • wp_enqueue_script( ‘jquery’ );
  • Write your post
  • Choose the template you have created (see above)
  • Write the Javascript code you wish to run on this post in some editor
  • Minify it.  JSMinifier
  • Switch to HTML view
  • Add <code class=”customscript” style=”display:none;”>Replace-with-your-code</code>
  • Switch back to Visual view
  • Replace text in <code> with your minified javascript code. If you don’t minify it, you risk that WordPress will replace new lines with <br/> and breaks your code.
  • Go to Preview of your post. The javascript code in <code> should run.

Important notice

If your script needs some special HTML structure (as a placeholder or a container – as in my case), make sure you back it up somewhere. WordPress deletes empty html elements on save! Don’t forget that not everything you write in HTML view will actually stay there.

Summary

I am looking for someone who will write this WP plugin 🙂 Please.

The moving thing below is created via custom script. I do need a WP plugin for such demos.

PS: The animation is taken from RaphaelJS demos.

Problem with printing background images

I have recently wasted almost two hours trying to figure out why some HTML based report wont display logo in its header. I am quite sure this will make someone else’s life easier, so I am sharing it. The problem is that most browsers ignore background-image and background-color. So whatever I did I could only set border, width, heights etc but not the image. At first I thought the problem was in wrong path to background image.  It wasn’t but I found that it is not possible (at least as I know) to inspect DOM elements in print-preview. Something like Firebug but for print-preview. There is nothing like that.

How do you print images without using background-image?

Simply return to the good old <img> tag 🙂

Or if you need two different images for screen and print version then you have add them both to your page and set display via css. Like this.

<div class="header">
  <img src="bigImage.jpg" class="defaultImage"/>
  <img src="smallImage.jpg" class="printThisImage"/>
</div>
@media screen {
  .defaultImage {
    display:block;
  }

  .printThisImage {
    display:none;
  }
}

@media print {
  .defaultImage {
    display:none;
  }

  .printThisImage {
    display:block;
  }
}

Click here to see the demo.

Amazon Kindle – personal review

I’ve bought Amazon Kindle about a month ago, so it is about time to write some review. Generally I am very satisfied with it. I don’t think I should  repeat all the positive reviews available on the Net, it would be quite unnecessary. So just to sum it up: Buying books to Kindle from Amazon with it’s “one-click” feature is awesome and very convenient. In less then five minutes I had the book in my Kindle.  Then I plugged in my headphones, turned on the “text to speech” function, put my baby in the pram and started walking. As for me this “text to speech” is a killer feature. It really saves my time.  I can listen to books I intended to read but did not have time to do so.

That’s what I like. Let’s talk now about the features I miss. First of all: text-to-speech is good enough but still far from perfect. The voice doesn’t make a pause when it should, like i.e. at the end of a paragraph or headline. It reads a book as it were one big chunk of text. It makes correct pause at the end of a sentence, it even pronounce questions as questions, but it just can’t make a pause between paragraphs. I don’t think it would be that difficult to program. I hope Amazon will fix in the next version of firmware.

Another “not-a-bug-but-a-feature” is that one can’t install other language or font or screen saver without having to jailbreak Kindle. There is a lot of people wanting to have images of living animals or other funny stuff  instead of long dead authors (nothing against them thought) or install their local language. Not everyone speaks English, there is about 6000 languages in the world :).

Nice-to-have feature

Remote control. It would be great to have it. When I walk and listen to Kindle I sometimes wish to pause it, return to previous paragraph or skip one. It is not possible at all. What I wish is to have some kind of remote control on headphones. Would it be nice? But I guess that will never be implemented… 🙁

So, is the world really faster?

Every now and then I hear people complaining that the world is now much faster than it used to be in time of our grandparents. But is it really so? Did people complain about that very fact in their time? Another common complain is that parents now have less time for their children or their partners. I don’t agree with this. I think that generally we work less now, don’t we have 8 hours long work day? Problem is that we have now too many options to choose from. It is difficult to choose and be happy with your choice, when choosing one option means saying no to all other tempting options. We have twitter and facebook statutes, google reader, rss.. and so on and so on. The amount of information is so overwhelming, that we always miss something. We just can’t catch up on it all. Therefore the world seems so fast. It’s not that much about the progress and innovation pace but about the number of small choices and distractions you face every day.  So why not just slow down and enjoy simple (offline!) things?

As a programmer I tend to follow what’s going on in the industry. I love learning new stuff. So I read about new technologies, I try them, dream about using them. And I often feel kind of guilty that I can’t learn them all. I always feel quite behind. Incapable of following. I guess that lot of people have similar problem of trying to do too much.

After reading that sleep is more important then food I decided to try to slow down and really sleep more. Yes, it does help :). I don’ t always manage to get those recommended 8 hours per day, but when I do, I can tell the difference. I just focus much better when I am fully rested (surprise:) ).  One of the requirements to get more sleep and feel better is to drop something off. Make more free time for yourself. Then your world will be slower again as it should be.

Environment and productivity

What kind of environment is best for work? Do you work in such? When I worked for IBM I was confined in a cubicle in a big open-space.  It was an experience I don’t want to go through again. The environment was “noisy by default”, there was a continuous sound-spam of chatting people. It was really difficult to concentrate and be productive.  The only way how to avoid it was to put on headphones and listen to some music.  But still I was disturbed by IM notifications and other crap.

Now I work in a small office in a team of five people and I am totally happy.  Most of the time nobody talks and if then it is mostly work related.  There is often silence, the only thing you hear is fingers tipping the keyboard.  I guess I sound quite nerdy, but I really like it this way. I believe this is the only way how to be really productive. Talk little, avoid being disturbed (if possible) and focus on the task at hand.  Then take a break, read some short article, have a cup of tea, or a little walk in the office.  That helps. If I deliver nice code, I am happy. If I don’t then I don’t like myself. Really.  I am far from being a perfectionist, but I like good work. I find it satisfactory 🙂

What helps me focus and create something is good music.  I can not play any musical instrument but I am an enthusiastic listener. I am particularly fond of jazz music. I know it may sound as a contradiction because jazz is often difficult to listen to, but it helps me to write code. Jazz is so full of energy and surprising ideas, that it lifts me up. It inspires me.  I love Pat Metheny for example. Listen here. Is it beautiful?

So .. this is the kind of music I listen to when I code. Or when I need to get new ideas. Or just to sit back and relax 🙂

What kind of music do prefer to listen to when you work? Or do you prefer silence?

I’ve started using Memolane

Recently I have stumbled across an interesting startup called Memolane. It is an unorthodox aggregator of various social media sites, YouTube, RSS feeds et cetera. I find it very useful. We all publish and share bits of our life to various sites, with different groups of friends, and Memolane collects them all back together, so everything is lucid and “defragmented”.  Everything on one place. You can see what you did in the past, how your interest changed, or what things have influenced you on your way…. Your tweets are there, facebook statuses, favourite videos, everything.  And their UI is simple and intuitive, as a user and programmer I appreciate that. It is quite challengig to make things simple 🙂

PS: See my Memolane here.

Look at the stars … and see code

starryNight plugin API

This is an update to my previous post. I wrote nice to look at animation on top of jQuery called starryNight. It takes a <div> element and add moving stars on top of it.  Stars are slowly floating across the sky, and when they finally flow out of the sky (or <div> in our case), they are automatically reborn on the other side on some random position.  That sounds pretty straightforward, and indeed it was until I complicated it by adding slider, more on that later.  Now to the API.

Basic HTML structure – provided by you – should look something like this

<style>
 #starryNightExample {
  background: url('/path/to/your/image_of_starry_sky.jpg') no-repeat;
  width: 500px;
  height: 400px;
 }
</style>

<div id="starryNightExample"></div>

I think that’s quite self explanatory. Without specifying width, height and background image it will look just ugly 🙂

Once you have your HTML structure ready just call .starryNight() to get the stars moving.

$(function() {
  $('#starryNightExample').starryNight();
});

The public API methods are:

  • count (int) – sets number of stars
  • addStars (int)
  • removeStars (int)
  • generateSlider (bool) – whether UISlider should be generated

Both addStars() and removeStars() are called internally by count() and all three of them accept positive integers only.

The methods are called like this:

$('#starryNightExample').starryNight('count', 150);

So that’s basically it … Next time I’ll write something more serious, I promise 🙂

See the live demo here.