Thursday, September 29, 2011

Reference Types In Java - Part 1


Lately, I have been learning a thing or two about the JVM internals. And one of the most interesting things that I came to know about was, the existence of different types of references in Java.

To go about it, there are actually 4 kinds of reference types in Java.

  1. Strong references.
  2. Soft references.
  3. Weak references.
  4. Phantom references.

These references are different solely because of the existence of a garbage collection mechanism in the JVM. That is because, the decision of reclaiming memory from the object heap depends not only on the fact that there are active references to an object, but also on the type of reference to the object.

Lets try to see how each of them differ from one another.




Strong references

As a normal programmer(that is, if you consider programmers to be 'normal'), we are most likely to encounter only the most ubiquitous form of references - Strong references. The name of this reference type should by itself give you an idea of the importance of the reference in the opinion of the garbage collector. Any object with an active strong reference to it, will never be garbage collected(except in rare circumstances, such as cyclical references).

Say, for example, when you create a class Employee, and you create a reference to a new employee object like this

Employee emp = new Employee();

you are actually creating a strong reference. An object to which a reference is created in this way will be eligible for garbage collection only when the reference is to it is pointed to null.
So, if you write this

emp=null;


and there are no more references created to this object until the garbage collector runs again, this object will become eligible for garbage collection, and is most likely to be garbage collected.

So, strong references are pretty simple to understand, probably because most of the code that you commonly write mainly consists of strong references. And we let the smart garbage collector take care of cleaning up the memory for us.

However, there might be cases where you need more control over the lifetime of an object. What if you want to keep some kind of a pool of objects, but still want it to be garbage collected if your JVM is running out of memory? In such cases although you may want a reference to the object most of the time, you are willing to let go of a memory reference for a better JVM performance, when times are crucial. This is where the other kinds of references come into the picture.

The 3 remaining Reference types that I discuss here are subclasses of an abstract class Reference.




Soft references

The soft reference class is used to create a soft reference to an existing object that is already referred to by a strong reference. The actual object on the heap that is being referred to is called the referent.

In order to create a SoftReference to an object, you first need to create a strong reference to that object and then pass that object as a parameter to the constructor of the SoftReference object, as shown in the code below.

Employee emp = new Employee(); //1

SoftReference<Employee> softRef = new SoftReference<employee>(emp);

In the above code, a few interesting things have happened.

  • In line #1,a (referent)object is created and allocated memory on the heap that represents the Employee object.
  • Again, in line #1, a strong reference is created to the newly created employee object. We call this reference 'emp'.
  • In line #2, a new SoftReference object is created and allocated memory on the heap. This is a special object because it contains an internal reference to the (referent) object passed to it in the constructor, i.e. in our case, the actual Employee object on the heap.
  • Again in line #2, a strong reference is created to the SoftReference object on the heap. We call this reference 'softRef'.


So, in total, we have 2 strong references created. And the object that represents the soft reference, internally holds a reference to the actual employee object.

So what is it that makes soft references useful? Soft references are considered to be a special kind of reference by the garbage collector. Let us assume that at a later point of time, we nullify the 'emp' reference as follows and no new strong references were created to this emp object.


emp=null;


Now lets assume that the garbage collector decides to run at this point of time. What it will see is that the current employee object only has a soft reference pointing to it, and no strong references. The garbage collector may optionally choose to reclaim the memory occupied by the employee object. But what makes soft references even more special is the fact that the garbage collector will always reclaim the memory of objects that have only soft references pointing to them before it throws an OutOfMemory Error. This gives the garbage collector some sort of a last chance to save the life of the JVM.

At any given point of time, if the garbage collector has not yet reclaimed the memory of the actual referent object, you can get a strong reference to the referent via the get method.


Employee resurrectedEmp = softRef.get();


The above code resurrects the employee object in the sense that the garbage collector will not consider it a candidate for garbage collection because it now has a Strong Reference pointing to it.

This makes soft references highly useful in creating object pools, where the size of the pool needs to be dynamic. If you do not know the size of a pool when you begin, or choose not to set a minimum or a maximum size on the object pool, instead you want it to grow dynamically, and at the same time, you want to give the JVM a chance to cleanup unused objects, in that case SoftReferences are a perfect fit.




Weak References

Weak references are even more awesome. Thats because seemingly the garbage collector has no regard for an object that only has a week reference. What that means is that the garbage collector will make it eligible for garbage collection because object only has a week reference pointing to it. Not only is that awesome and useful, but desirable as well in some scenarios.

For example, let  us assume that you need to maintain some metadata related to a user per database connection. In such a case you will be tempted to use a hashmap where you can store the database connection as the key and the user metadata as the value. However, this approach has one drawback. When the database connection has been cleaned up by some other part of the application, then you need to ensure the removal of the connection from the hashmap as well. If you forget to do such a thing, a reference to the connection will remain in the hashmap thereby preventing it from being garbage collected. This means that over a period of time, you are bound to end up with a very large hashmap, a clear indication of a memory leak. And the JVM will eventually spit out a OutOfMemoryError.

So, what do you do in such cases? Oh, of course, Weak referencnes to the rescue!

You can simply create a weak reference to the object, in the same way that we created a soft reference.


DBConnection emp = new Employee(); //1

WeakReference<DBConnection> weakRef = new WeakReference<DBConnection>(emp);



This creates a weak reference to the DBConnection object. This means that if at any future point in of time during the execution of the program, if the garbage collector detects that the only reference to the actual DBConnection object is a Weak reference, then it will mark the object for garbage collection.

Weak references are primarily used in conjuction with a WeakHashMap. This is a special kind of hashmap where the keys are all made of weak references. So, in our database example, we could effectively create a weak reference of the Database connection and store it in the WeakHashMap and the metadata of the user as the value in the hashmap. In this way, when the application no longer holds a strong reference to the Database connection, the only reference to the database connection object will be the one that we have via the WeakReference entry in the WeakHashMap. When the garbage collector detects this, it will mark the object for garbage collection. When the object is garbage collected, the entry from the WeakHashMap will be removed. And then, finally, we can all go home and rest in peace.

So, colloquially speaking, this is what the Soft reference and the Weak reference tell us about themselves.

Soft Reference : Hey! I am a soft reference. Ill take your shit as long as the JVM has patience. When it begins running out of patience(i.e. about to throw an OutOfMemoryError), i take no more. Your object will be gone. And then you simply have to create a new object.

Weak Reference : Hey! You know what. I am even cooler than the WeakReference. Coz I wont take your shit at all. The moment you lose me, if the JVM detects that you're no longer around, am gonna punch you in the face and run away! (i.e. Marked for garbage collection). Can you dig it sucka!

As you see, our two awesome friends, Softy and Weaky, certainly have some ego there. But they are pretty useful, at crucial times.

Before I proceed any further, there is one more puny lil thing that you might need to know. Oh! Did i just say 'might'. Oh no.. I meant, you should know. And that is ReferenceQueues. ReferenceQueues are some sort of a queue where the JVM can store objects of type reference once it has decided to take some action on the objects to which they refer.

What I mean to say is, let us suppose you have a weak reference which points to an object in the heap. And that object has been left lonely and desolate by the rest of the application.i.e. No strong references to it. And the garbage collector detects this object during its garbage collection cycle. Since this object only has a weak reference to it, the garbage collector will mark it for garbage collection. But at the same time, it looks if there is a reference queue associated with the weak reference that points to this object. If yes, it puts this weak reference in the reference queue to indicate that the object has been marked for garbage collection. The subtle point to be noted here is that even though the object has been marked for garbage collection, garbage collection may not have happened yet. This may be because the object has a finalize method, which the JVM needs to execute before reclaiming memory.

This also means that you can, but should not,unless deemed necessary, resurrect an object in the finalize method and create a strong reference to it. But when you do that, the weak reference still remains en-queued in the ReferenceQueue. Overriding the finalize method to resurrect an object is a rare case, but since it is one of the options that the JVM supports, it is therefore something that needs to be considered. Nevertheless, when you do such things, its almost equivalent to artificially manipulating the life of an object. That's because the second time when the object becomes eligible for garbage collection, the finalize method wont run, which is a good thing because if you run it again, its simply gonna revive itself. So, practically speaking, an object in the JVM has only one spare life. You get just one medical kit at the max. And thats it. You screw up again, and ur doomed. Your object will be on mars, having a boss fight with the garbage collecting thread of the JVM, which will eventually win, and reclaim the memory of the object.

The same facts about the reference queue hold true for Soft references as well.

In order to associate a weak or a soft reference with a reference queue, you can use the 2 argument constructor as shown below.


Employee emp1 = new Employee();
Employee emp2 = new Employee();

ReferenceQueue softQueue = new ReferenceQueue();
ReferenceQueue weakQueue = new ReferenceQueue();

SoftReference softRef = new SoftReference(emp1, softQueue);
WeakReference softRef = new WeakReference(emp2, weakQueue);




Now, aint that simple? Yes of course it is.
Then again, you haven't met the Phantom yet, have ya?

The phantom reference is a place where it gets all the more interesting.




Phantom References

Phantom references tell a long tale themselves and its a topic that warrants a blog post of its own. However, in this blog post, ill give a brief idea about what they are. Phantom references are quite similar to Strong and Weak references in the sense that the garbage collector will collect the referent object if the only reference to it is the phantom reference. But that's where the similarity ends. 

What makes Phantom references are unique is the way in which they are used along with a reference queue. A phantom reference is always associated with a references queue during construction time. This is because phantom references are enqueued in the queue only when the the object is about to be garbage collected, after the finalize method(if any) has been executed on it. Calling a get() on the Phantom reference always returns null. And that is quite appropriate because the finalize function has already run on the referent object. So, there should be no 'legal' way of resurrecting the object (resurrecting i.e. creating a strong reference). This may at first seem to make no sense, since, what use is a phantom reference if we cant extract the referent from it? But on giving it a deep thought, you would realize that this is not the reason why phantom references are meant to be useful in the first place. It is the time at which the JVM puts a phantom reference in the reference queue that makes its use so intuitively amazing.

That's something that I will be discussing in more detail in the next post. So stay tuned, because, it might just turn out to be a weird crazy experiment. And of course, its possible that some so called 'laws' will be violated. I am still working on it right now. Ill put it up sooner or later.

So folks, see you on the other side! (Hint : That's what phantom references say too).

Happy Programming :)
Signing Off
Ryan

Thursday, August 25, 2011

Dissecting CSS3 gradients - Part 2

Hello everyone :)

This post is a continuation of my previous article on CSS 3 gradients. If you are completely new to CSS 3 gradients, you might want to take a look at it.

In my previous blog post, we learnt about the basics of CSS 3 gradients. We also learnt about the different types of CSS 3 gradients and understood their basic syntax to get things up and running. And then lastly we saw a few examples demonstrating the use of the syntax.

In this post, we will take things a bit further, frankly because, it CAN be taken further! It seems like the simple CSS 3 gradient syntax that we saw recently can be used in a myriad of different ways that sometimes makes it hard to believe it is in fact CSS 3 gradients that are being used behind the scenes.

In this blog post, I will be trying to answer the following questions.

  1. How to use multiple CSS 3 gradients?
  2. How to use CSS 3 gradients with other CSS 3 properties?
  3. How to use CSS 3 gradients to create Patterns?
  4. Cross Browser CSS 3 gradients.
  5. Where to find resources that smartly generate cross browser CSS 3 gradients for you?


So, lets not waste any more time and get to the point.





1) How to use multiple CSS 3 gradients?

CSS 3 gradients are awesome. And when one gradient is awesome, just imagine what adjective you would have to use if you had more than one gradient(If you manage to come up with the proper word, tell me in a comment!). Adding multiple CSS 3 gradients is a pretty simple task. Instead of passing only one gradient function in the background image, you can pass multiple, comma separated list of gradient functions as the background image. However, while doing so, you would have to keep a few things in mind. Since a gradient is much like a background image, having multiple gradients is almost conceptually equivalent to having a stack of multiple background images. And that means, if you want to be able to see the colors of the gradient that is at a lower level in the stack, you will have to use a transparent color on the upper level of the stack.

So, the two new features that should come to your mind when using multiple backgrounds are


  1. Stacking level of gradients.
  2. Usage of Transparency while making gradients.


Lets understand the stacking level of gradients by using a simple example where we use 2 gradients layers in the gradient stack.

Sample 1




Css Code

background-image: linear-gradient(0deg,#000000 50%,#ffffff 51% ),
radial-gradient(50% 50%, circle , #000000 40%,#ffffff 41% );


As you can see in the code above, I have applied 2 gradients in the background image property. One is a linear gradient, and the other is a radial gradient. The linear gradient covers half of the block width with black, and the other half with white. The radial gradient is used to create a sharp circle. However, we are not able to see the circle on the browser. That's because of the fact that the order in which you specify the gradient functions is the order in which the stack is created and this stack grows downwards, i.e. the gradients that are specified first appear as the topmost layers, and the gradients that you specify later appear below them. Since in our example, the radial gradient was specified after the linear gradient, and because all the colors in linear gradient were opaque, we were unable to see the underlying radial gradient.

Now lets make use of transparency in the gradient function and see how things change.

Sample 2




Css Code

background-image: linear-gradient(0deg,#000000 50%,transparent 51% ),
radial-gradient(50% 50%, circle , #000000 40%,#ffffff 41% );


As you see, in the above code, I made use of transparency in linear gradient function instead of using a white color. And we were able to see the underlying black color circle.

So, this is a tip. If you are making use of multiple CSS 3 gradients, you can make shapes by mixing and merging the gradient colors with transparency.







2) How to use CSS 3 gradients with other CSS 3 properties?

CSS 3 gradients are a terrific feature. But what makes them even more terrific is that when you use multiple background images, you can also use them with other CSS 3 properties and create something really amazing. The two other CSS 3 properties that I find outstandingly helpful are

background-position
background-size

First lets take a look at the background size property. The background size property is used to define the size of the background. What makes this interesting when using multiple gradients is that instead of supplying one value for the width and height of the background, you can now supply a list of comma separated values of the background size, each of which will be applied to the respective gradient.

What I mean to say is this

background-image : gradient1, gradient2, gradient3;
background-size:gradient1-size, gradient2-size, gradient3-size;


Lets take a look at some code in action. We will make use of the same gradients that we used in the previous example. But we will add a background size property this time and see what happens.

Sample 3





Css Code

background-image: linear-gradient(0deg,#000000 50%,transparent 51% ),
radial-gradient(50% 50%, circle , #000000 40%,#ffffff 41% );
background-size: 100% 100%, 50% 50%;

In the above CSS, I specified 2 background gradients and two corresponding background sizes. For the second background size, I specified it to be 50 percent of the width and height of the element. Because the background is being repeated, the second background gets repeated across the dimensions of the element and you are able to see two circles in the image. If I were to make the linear gradient fully transparent, you would be able to see 4 circles in the element instead of 2. At present those two are being hidden by the linear gradient layer.

Now lets take a look at the effect of background position on gradients.


Sample 4




Css Code

background-image: radial-gradient(50% 50%, circle , #000000 40%,#ffffff 41% );
background-size: 50% 50%;
background-position:50% 0%;

As you see in the sample code, I just shifted the background position of the gradient in the horizontal direction by 50%.

However there are some quirks when using the background position property along with multiple gradients with different browsers as of this writing. So you would want to be careful when trying it out on your own.





3) How to use CSS 3 gradients to create Patterns?


Now gradient patters are an interesting feature that come into play when you begin to mix and merge multiple gradients and the background-size property.

To start with, lets make a very simple gradient pattern.


Sample 5




Css Code

background-image: linear-gradient(0deg,#000000 50%,transparent 51% ),
radial-gradient(50% 50%, circle , green 40%,#ffffff 41% );
background-size: 10% 10%, 25% 25%;

As you see in the code, the the gradient is the same, I just changed the color of the circle to green. But the main thing that I changed was the size of the gradient. And as you see, the effect is quite surprising.

Okey, lets try something else.


Sample 6




Css Code

background-image: linear-gradient(45deg,#000000 50%,transparent 51% ),
radial-gradient(50% 50%, circle , green 40%,#ffffff 41% );
background-size: 50% 10%, 25% 25%;


Pretty Cool eh?

One more??


Sample 7




Css Code

background-image: linear-gradient(45deg, #000000 25%, transparent 26%,transparent 75%, #000000 76%),
radial-gradient(50% 50%, circle , green 40%,#ffffff 41% );
background-size: 50px 50px, 25px 25px;


How about one more??


Sample 8





Css 3 Code

background-image: 
linear-gradient(45deg, #000000 25%, transparent 26%,transparent 75%, #000000 76%),
linear-gradient(45deg, #000000 25%, transparent 26%,transparent 75%, #000000 76%),
radial-gradient(50% 50%, circle , green 40%,#ffffff 41% );
background-size: 50px 50px, 25px 25px;


A point to be noted in the above example is that although I have specified 3 gradients, I have specified the size of only 2 gradients. Since the third size parameter is not specified, the first parameter of 50px 50px is applied to the third gradient.

Well, I can go on and on and on and endlessly keep creating patterns. Its just a question of playing with the parameter values (or rather playing with your grey matter until they burn and char and turn into dark matter).

For now, Ill stop here as I believe that you've got my point, and that is - CSS 3 gradients are powerful. So lets move ahead and address a more important question.





4) Cross Browser CSS 3 gradients.

As with most CSS 3 properties, browser support is not available unless you add browser specific prefixes to your css code. In case you don't already know the prefixes, these are the prefixes that you may have to use to make the gradient function work on different browsers

Firefox : -moz-
Webkit : -webkit-
Opera : -o-
IE : -ms-

For support in any other browsers, you can obviously check out their documentation to determine what prefix they use.




5) Where to find resources that smartly generate cross browser CSS 3 gradients for you?

Well, this is one of the most important questions to be addressed. That's because, although CSS 3 can be used to make patterns and many other things, you are most likely to find yourself using simple gradients to style your buttons or other elements to create subtle effects much more than anything else. And you're definitely gonna want to make it cross browser, as much as possible, and have a decent fallback color if your site is not going to opened in modern browser with gradient support.

That said, there are a few tools out there than can help you by generating CSS 3 gradients for all the browsers, i.e. with the same effects using all the prefixes for major browsers.

Below are a few links to gradient tools that I prefer to use when trying to make simple gradients. If you are aware of better sites, let me know about them in the comments. Ill take a look, and maybe add it to the main post as well.








To conclude, CSS 3 are a great feature and open up new dimentions of thinking for developers and web designers without having to turn to a graphic design tool every-time they change their mind about a particular color. As time will pass, standards compliant browsers are bound to have more support for the new CSS 3 properties. And CSS 3 gradients are definitely going to be an important part of every web designer's toolkit in the time to come.


Happy Programming :)

Signing Off
Ryan

Dissecting CSS3 gradients - Part 1


One of the features in CSS 3 that I find to be the most intriguing is the application of gradients via simple css rules. The reason why I find it so awesome is because while designing pages, I have usually had to insert dummy placeholder images in the background, or leave the backgrounds as colorless while writing the html and css. So, even when I am almost done with the design, I always have a second task to open up an image editing software, most likely GIMP, and the create the images as per the sizes of my html elements.

Interesting as it may seem, the main problem arises is when I dont like what I see. When you amalgamate all the colors on a website, its highly possible that you dont like the color scheme. This then inevitably brings you back to your image editing software to tweak with the colors to get it right. And this can happen several times, especially when you are prototyping to give a client a demo of what you want things to look like. You will find yourself switching several times between your html editor and your image editor. This is exactly where CSS 3 gradients fit into the picture like cheese fits into a burger. It was just the missing ingredient. So, in this blog post, I am going to cover the following topics that will help you get a better understanding of CSS 3 gradients.

In this two part series, I will be covering all the essentials to get you up and running with CSS 3 gradients.

In this first part of the series, we will try to answer the following questions.

  1. What are CSS 3 gradients? - the basic concepts
  2. What are the types of CSS 3 gradients?
  3. How to use CSS 3 gradients? - elements of design

In the second part of this series, we shall see a bit more advanced usage of CSS 3 gradients and try to answer questions, such as

  1. How to use multiple CSS 3 gradients?
  2. How to use CSS 3 gradients with other CSS 3 properties?
  3. How to use CSS 3 gradients to create Patterns?
  4. Browser issues when using CSS 3 gradients.
  5. Where to find resources that smartly generate cross browser CSS 3 gradients for you?

So, lets get started :)





1) What are CSS 3 gradients? - the basic concepts

If you are graphic designer at any level, I am sure that you are aware of what gradients are. Making gradients in graphic tools like GIMP or Photoshop are pretty easy. But now, using CSS 3, you can create gradients with almost the same ease.

The most important thing to note about CSS 3 gradients is that they are applied as part of the 'background-image' css property.i.e. CSS 3 gradients does not require a new css property, it just adds a new function that can be added to the already existing 'background-image' property. It makes quite a lot of sense to add a css gradient as a part of the background, because that is exactly the way images are used - to lie in the background of an html element.

The next important thing to note is that you can add multiple background gradients, using a comma separated list of gradient functions on the same background css property.

Now lets move on to the next section and learn about the various types of CSS 3 gradients.





2) What are the types of CSS 3 gradients?

There are two types of CSS 3 gradients.
  1. Linear Gradients
  2. Radial Gradients

Linear Gradients :

Linear gradients are the simplest and the most common of all. Let us see the syntax and then see how it works.

linear-gradient( [<point> || <angle>,]? <stop>, <stop> [, <stop>]* )

I just have to say this right now. Linear gradients are HOT!

I totally love them. Instead of breaking down the syntax and explaining the various terms, lets me try to explain the concept of gradients in a way that I see it.

Let us assume that you want to create a linear gradient. What that means is that you want to move from one shade of color to another in a linear fashion. Now lets try to break down our own thought process when we visualize gradients.

Q :What do we need to create a simple linear gradient??
A : At least 2 colors. (ya, i know that was simple).

Q : How do you know what the 2 colors are used for?
A : You define one of the colors as the start of the gradient, and the other color as the end of the gradient. These are called as you color stops. Since(for now) you have just 2 colors, you have 2 color stops.

Q : What is the direction of the gradient?? Is it a horizontal gradient? Is it a vertical gradient? Or is it at a certain angle??
A : We need a direction for our gradient. Mathematically, directions are defined by drawing a vector, from one  start point to the other point, with an arrowhead indicating the direction of the vector. So when you draw any such line on a sheet of paper, you obviously will be drawing a line such that it makes an angle with the horizontal axis of the sheet of paper. This angle is the measure of the direction of the vector. Hence, we need a way to specify an angle when specifying a gradient in CSS 3.

So, now we have our three main ingredients to cook our CSS 3 gradient.

  1. A start color.
  2. An end color.
  3. An angle.


Lets put these three together in the gradient syntax.


linear-gradient( angle, start-color, end-color);

Now it looks pretty simple, doesn't it?

Although there is another syntax, I feel that this syntax is not only easily readable, but also gives you an immense amount of flexibility in defining the options. In the sections that follow, we will use colors and create a few linear gradients to see this form of defining gradients.


Radial Gradients :

The other type of gradient is radial gradients. Now radial gradients are quite similar to linear gradients. You have almost the same three main ingredients.


radial-gradient( [<position> || <angle>,]? [<shape> || <size>,]? <stop>, <stop>[, <stop>]* )

This looks pretty scary, doesn't it? Well it does to me. So, lets try to break it down in the same way that we broke down the syntax for linear gradient.

Apart from the three important ingredients, the new important ingredient in the radial gradient is the 'shape' of the gradient. We know that a radial is something like a circle. In CSS 3, you can define the radial to be one of two shapes - circle, ellipse.

While using the radial gradient, there is one property that is somehow more interesting than the angle. And that is, the coordinates of the center of the radial (circle or ellipse).

The radial gradient has many more options as compared to the linear gradient and therefore we can have several more permutations and combinations of the syntax, which thereby makes it completely impossible for me to cover radial gradients in this blog post. So we will only see the basics and then you can explore the various other options at your own leisure once you have a better understanding of the underlying concepts.

To capitulate, the important ingredients of a radial gradient are

  1. The coordinates of the center of the radial.
  2. The shape of the radial
  3. A start color (which becomes the color of the center).
  4. An end color (which becomes the color of the outer edge of the radial).

Lets put these three together in the gradient syntax.


radial-gradient( center-coordinates, shape , start-color, end-color);

This syntax can be used to define the most basic form of a radial gradient. And we shall see in the upcoming examples, how they can be applied to style the background of an html element.




3) How to use CSS 3 gradients? - The Elements Of Design

So far, we have seen what CSS 3 gradients are. And we also learnt the most basic form of their syntax. Now comes the most interesting part of this post and that is, the part where we demo the various CSS 3 gradients in use.

For the purpose of our demo, I will be making use of an HTML div element having dimensions 200px X 200px and apply the various gradients to it.

Linear gradients

Sample 1:

This one shows a simple gradient from black to white.



Css Code

background-image:linear-gradient(0deg, black, white);

The css code is very simple. You want a horizontal gradient (hence the 0 degrees), the starting color is black, the ending color is white and the gradient effect spreads across the dimention of the entire html element.


Sample 2:





Css Code

background-image:linear-gradient(45deg, black, white);

In this example, we have simply rotated the axis by 45 degrees. As you might have noticed, the axis rotates about the center of the html element. So when you rotate the axis by 45 degrees anticlockwise, the start color automatically starts at the left bottom and the end color ends at the right top, thereby giving you a gradient of 45 degrees about the center of the html element. This is a very important point to note about linear gradients. The following image (that I created using Inkscape, not CSS 3) should be able to give you a better idea of the angle calculation.



The axis/vector representing the direction of the gradient rotates about the center of the html element to which the gradient it applied.


The next example demonstrates using three colors in a gradient. It is similar to the previous two examples, the only difference being the additional parameter that describes the third color.


Sample 3





Css Code

background-image:linear-gradient(45deg, black, white, green);


In this example you see that the gradient started normally from the lower left corner, then it gradually changed to white when it reached the middle and then it gradually changed to green when it reached the upper right corner. This means that the gradient rendering algorithm tried to evenly distribute the area over which the gradient was to be rendered between the three colors that we specified.

In the next example, we will try a tiny variation of the above


Sample 4





Css Code

background-image:linear-gradient(45deg, black 20%, white 50%,green 80%);

As you see in the above code, this is a slight variation of the previous example. I have specified percentage values along with the color. To understand what this percentage means, you need to keep one thing in mind - the direction vector of the gradient. As you move along the direction vector of the gradient, the start of the vector is 0 percent. The end of the vector is 100%. So, when you specify the a percentage along with a color stop when using gradients, you are actually saying that at a given percent distance along the vector, I want my color to be #some-color. i.e. you are defining the position of the color stop along the direction vector. In the above example, I declare black to be the color at 20 percent distance from the start of the direction vector, white to be the color at 50 percent distance from the gradient direction vector, and green to be the color at 80 percent of the distance from the gradient direction vector. Since before 20%, no color is specified, hence the origin color(i.e. black in our case) is used from 0 t 20 percent. And since no color is specified after 80%, hence green is used as the color after 80 percent. So, we see that our gradients in this background are between 20 percent and 80 percent. The remaining parts are fixed colors.

Radial Gradients

In this section we will see a few examples that make use of the simplest form of radial gradients.


Sample 1





Css Code

background-image: radial-gradient(50% 50%, circle , #000000,#ffffff );

In the above example, you can see that the first parameter is used to set the x and y coordinates of the center of the radial. And I have set i to be 50% from the left and 50% from the top. The next parameter specifies the shape of the radial, which in our case is 'circle'. The next parameter gives the start color of the circle from the center. The fourth parameter is used to specify the end color of the radial, which in our case happens to be white. So, we have a simple gradient, starting from black at the center to white at the edges of the element.

Now this may not seem so interesting at first. But when you perform a few tweaks on the parameters, you can create something really cool. Check out the next sample.


Sample 2



Css Code

background-image: radial-gradient(50% 50%, circle , #000000 50%,#ffffff 51% );

As you see in the above code, we were easily able to create a circle with a sharp boundary using gradient parameters. In the syntax above, we have specified a percentage alongside each color value. To understand how this percentage applies, think of it in this way - You have a circle with its center set at the center of your html element. Now Since its a circle, it has a radius. When you specify #000000 50% as the first color, what you are actually saying is that upto 50 percent of the radius, starting from the center, you want the color to be #000000. In the next color parameter, when you say #ffffff 51%, you are saying that from 51 percent of the radius onwards, you want the color to be #ffffff. Since there is only a 1 percent difference between the two colors, you get a nice sharp boundary instead of a gradient between the two colors. If however you were to increase the difference in the percentage, as in the below example, you would get a gradient.


Sample 3






Css Code

background-image: radial-gradient(50% 50%, circle , #000000 50%,#ffffff 71% );

As you see in the css code above, I increased the percentage value of the color #ffffff to 71 percent. So we were able to see a gradient effect from the color #000000 to the color #ffffff between 50% and 70% of the radius of the circle, which looks like a nice halo.

The wonderful thing about radial gradients is that just like linear gradients, you can also add more color stops. So lets try to make a much more realistic halo effect using radial gradients.


Sample 4






Css Code

background-image: radial-gradient(50% 50%, circle , #000000 40%,#FFFF00 41%,#ffffff 71% );

As you see in the above code, creating a halo was just a matter of adding another color stop to the radial gradient function and setting the proper percentage values. Beautiful, is'int it? Kinda looks like a scary eclipse, but still beautiful. Probably because it hardly required any effort to create.





Well, that's the beauty of CSS 3 gradients.

Now that we have a basic idea of CSS 3 gradients, in the next part of this series we will see how we can mix and merge gradients to create something even more powerful, and of course, beautiful, such as creating gradient patterns and using the gradient property with other CSS 3 properties.

Excited anyone? !!

Happy Programming :)

Signing Off
Ryan

Sunday, July 24, 2011

Drupal Begins

I sometimes feel that I have an uncanny affinity for problems. Almost nothing that I do, seems to work on the first go.

Lets take for instance, Installing and creating Drupal on my local machine.

I am using Drupal 7.4.4.

I got this cool error when I tried to import drupal.


Error

The website encountered an unexpected error. Please try again later.

Error message

PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') ORDER BY fit DESC LIMIT 0, 1' at line 1: SELECT * FROM {menu_router} WHERE path IN () ORDER BY fit DESC LIMIT 0, 1; Array ( ) in menu_get_item() (line 445 of D:\personal\drupal\drupal-7.4\includes\menu.inc).



Now that is frickin cool because, I dont know head or tail of drupal and I was simply following instructions from a video tutorial from you tube. And it seemed to work out quite nicely there.



So, what I did was, when trying to import, i changed the sub domain name and the database name to REMOVE the underscore.

Now, i really like underscores. They work well in linux and in windows. Since using spaces for directory names in windows is one of the worst habits that you can have as a developer, underscores became kind of my closest friends.

But oh no, this damn thing wont accept underscores. Anyways, so I had to simply do it without the underscore and now the hostname looks like a congested orgy of characters. I guess Ill just have to deal with it that way!

So, if you have this same problem, you now know how to deal with it.

If it still does not work our for you, take a peek at this


E8AQWDSMUMYU

Happy Programming :)
Signing Off

Ryan

Sunday, June 12, 2011

Simple theming in Struts 2

I was just designing a page in struts. I had already designed the structure of the page using a text editor and also setup the necessary css and javascript for the layout.

But when I introduced a struts tag into the page by replacing the elements with struts tag, somehow the entire layout turned into a huge mess.

Reason? My page contained a form, and struts automatically applies a theme to the form that causes the elements to be rendered in the form of tables. I was like, WTF! When i saw my perfectly looking page utterly distorted coz of no mistake of my own.

If you are facing the same issue, you can simply resolve it by using the simple theme instead of whatever theme struts is using.

In my case, I did the following in my struts form.



Yea, that works. Piece of cake. I guess there should be a way to default the theme for the entire project instead of doing it one form at a time, especially since I like to do the styling of the web pages by myslef. Will have to check that.

Happy Programming :)
Signing Off
Ryan

Saturday, May 21, 2011

Demystifying Web Colors : The HSV color scheme

Colors always fascinated me. After all, they are present in everything that we see around us. As I write these lines, I feel a bit sad about those who are color blind and for those among us who are completely blind. Makes me realize how fortunate most of us are to be able to experience all the beauty that surrounds us.

And we as programmers and web designers spend most of our waking hours staring at computer screens and interacting with a myriad of colors. Just like 'real life', colors are omnipresent on the web as well, most of them in the form of images. But with newer and better browsers, its becoming increasingly possible to create absolutely amazing coloring effects even without the use of images. Yes, you guessed it right, I am talking about the various new ways in which colors are entering the landscape of web designers by adapting the new CSS 3 specification.

I believe that almost every web designer is quite familiar with the RGB color scheme. However due to some (INSANELY BIZZARE) circumstances you are not aware of this scheme, then of course you need to google a bit, because a basic understanding of this scheme is a must if you want to enjoy making and delivering a design.

Working on the web has made us quite used to the RGB scheme. However, as most of us might know, there are also a few other popular color schemes called the CMY and the HSV color scheme. CMY is used in the print industry. And HSV is important solely because I am going to be discussing about it in this post.

Ok ok, that's not the only reason why HSV is important. HSV is a very important color scheme, and in fact in my opinion, even more important than the RGB scheme, because this is the scheme that represents the way we actually perceive light and colors. When I say light, what I mean to say is 'wavelenghts', because after all, that is exactly what light is. And the HSV scheme speaks of colors in terms of wavelengths.

In this article, I am going to walk you through the HSB color scheme and its relationship with the RGB color scheme.

My intention is that after reading this article, if anyone tells you the HSV values of a color, you should be able to make a mental picture of the color and then almost be able to guess the RGB values for the HSV colors. I believe that the more you do it, the better you will get at guessing and your accuracy may also improve.

Sounds like a fun thing to do, is'int it? Well then, lets get started.

In the RGB scheme , R stands for Red, G for Green and B for Blue. Whereas HSV stands for Hue, Saturation and Values. However, for an easier understanding in this article, i am going to replace the V with a B. B for Brightness. So, while the actual color scheme is HSV, throughout this article, i will be referring to it as HSB, where B is nothing but the Brightness Value.

The RGB scheme is popular because it is the first thing that comes to our mind when we write our CSS. However, almost all color pallete's also give us an option to select a color based upon the HSB scheme.

First the Basics
In the RGB scheme, each color can be represented within a range of 0 to 255.
The value of R represents strength of the color Red in a given color combination of Red, Green and Blue. The same holds true for Green and Blue. So, you can say that the RGB scheme is like an artist's coloring palette where he can mix the three colors to create all the other colors.

The HSV schema differs because it organizes colors in the order of wavelengths. I believe that when you think of HSV, you can think of yourself standing and staring at a colorful circle. This circle can be divided into three equal arcs of 120 degrees wherein each arc represents the most dominant color withing that degree range. The three dominant colors in the HSV circle are Red, Green and Blue. These dominant colors are also called primary colors.

For now, you can imagine your circle to be something like the below image. You can call it your color wheel.



But in reality, in the actual color wheel, within each dominant section, the color varies across the radius and circumferenece to produce an effect as follows.



Lets understand how our colors vary in the color wheel.

I will need you need to first imagine yourself shrinking all of a sudden and finding yourself standing at the edge of the color wheel. I am going to ask you stand at an an angle of 0 degrees on our color wheel, which is the mid point of the red zone on the circumference as depicted in the image above. Now I ask you to take a stroll along the circumference of the circle in the anticlockwise direction, i.e in the increasing order of the angle. As you were to walk and note the values of the colors that your come across, you would make the following observations.

From 0 to 60 : red stays 255 , green 0 changes from 255 , blue stays 0

From 61 to 120 : red changes from 255 to 0 , green stays 255 , blue stays 0

From 121 to 180 : red stays 0 , green stays 255 , blue changes from 0 to 255

From 181 to 240 : red stays 0 , green changes from 255 to 0 , blue stays 255

From 240 to 300 : red changes from 0 to 255 , green stays 0 , blue stays 255

From 300 to 360 : red stays 255 , green stays 0 , blue changes from 255 to 0

Hue
There are a few things that you need to know about your stroll.
  1. As you walked along the circumference, ie at a fixed distance from the center of the circle, you observed the color change. Such a color change that takes place with an increase in the angle is known as the HUE of the color. Hence one could say that at a fixed distance from the center, the HUE of a color is based solely upon the angle. Hence, the value of HUE ranges from 0 to 360, which is just as expected.
  2. You were walking at a fixed distance from the center.
  3. The intensity of the various colors varied from a min of 0 to a max of 255.
  4. Within a given 120 degrees of a dominant color, no other color had a value greater than that of the dominant color at any point of the stroll.
  5. Graphically, the dominant range and the zero range lie opposite to each other on the circle and they span 120 degrees each.

Take a moment and make a note of the following patern
For any given color there is a range where the color is dominant. That range covers and angle of 120 degees. The most important point to be noted is that the intensity of a dominant color remains constant and is the highest in its dominant range as compared to the other colors.
  • Red : 300-0/360-60 : Total : 120 degrees, i.e. The intensity of Red color in this range is a FIXED_HIGH, and is always greater than or equal to the other colors.
  • Green : 60-120-180 : Total : 120 degrees, i.e. The intensity of Green color in this range is a FIXED_HIGH, and is always greater than or equal to the other colors.
  • Blue : 180-240-300 : Total : 120 degrees, i.e. The intensity of Blue color in this range is a FIXED_HIGH, and is always greater than or equal to the other colors.

Then, for the next 60 degrees after its dominant range, the intensity of the dominant color gradually drops to 0 from its current value.
Red : 60-120 : Red value drops from FIXED_HIGH to 0.
Green : 180-240 : Red value drops from FIXED_HIGH to 0.
Blue : 300-0/360 : Red value drops from FIXED_HIGH to 0.

After a color drops to 0, it remains in a steady zero state for the next 120 degrees.
Red : 120 - 240 : Red stays 0
Green : 240 - 360/0 : Green stays 0
Blue : 0/360 to 120 : Blue stays 0

Hence the trend followed by all the colors in the circle is :
  • Rise to the FIXED_HIGH over a range 60 degrees.
  • Then stay at the FIXED_HIGH over the next 120 degrees.
  • Then fall to 0 over the next 60 degrees.
  • Then stay at 0 over the nenxt 120 degrees.

Note that in the above statements I have made use of the term FIXED_HIGH, and not a value of '255'. That is what takes us to the next step where we discuss the other components of colors - namely saturation and brightness.

Brightness
Brightness determines the value of the strength of the color, which in our case is the variable FIXED_HIGH. The range of the brightness value is from 0 to 100 in the HSV scheme.
Taking our stroll analogy, if we consider our color wheel to have a radius of 255 units, a brightness of 100 means you are waking at 100 percent of the radius, i.e. 255.
A brightness value of 50 indicates that you are walking at 50 percent of the radius , hence the FIXED_HIGH is 128.
A brightness value of 25 indicates that you are walking at 25 percent of the radius , hence the FIXED_HIGH is 64.

So ho do we calculate the RGB for a given hue and brightness ?
First determine the RGB value based on the hue. i.e. the degrees of the arc.
Then the actual RGB at a given brightness = X percent RGB where X is the value of Brightness.

Let us see a few examples to see how this is done.

At 30 degrees, you get a color of orange which is composed of Red and Green but no blue.

Case 1 : At Brightness/FIXED_HIGH of 100 %
Red : 255 , Green : 128 , Blue : 0 (Red is the dominant color, Green is the secondary color, Blue is 0 at 30 degrees)

Case 2 : At Brightness/FIXED_HIGH of 50 %
Red : 128 , Green : 64 , Blue : 0 (Red is the dominant color, Green is the secondary color, Blue is 0 at 30 degrees)

That covers brightness.

Saturation
Saturation determines the amount of non-dominant colors with respect to the dominant colors.
Saturation is applied to the non dominant colors only, that too only after Brightness has been applied to the original combination.

I like to think of saturation as a way of saying how pure a mixture of colors is. The more the saturation, the less is the presence of the non dominant colors, and hence more is the purity of the mixture.

The value of saturation varies from 0 to 100 just like Brightness.

So, how to we calculate the RGB based upon a hue, saturation and brightness level? The algorithm is pretty simple.
First determine the RGB based on the hue.
Then calculate the RGB based upon the brightness : RGB = X percent RGB where X is the value of Brightness.
Determine the difference between the dominant color's value and the non dominant color's value for each color.
For each percentage DECREASE in the saturation, INCREASE the color of the non dominant's by the same percentage of the calculated difference.

The above algorithm should become clear with the example below:

At 30 degrees, you get a color of orange which is composed of Red and Green and no Blue.

Case 1 : At Brightness of 100 %
Red : 255 , Green : 128 , Blue : 0 (Red is the dominant color, Green is the secondary color, Blue is 0 at 30 degrees)
Here saturation is 100 percent. i.e. This is a 100 percent pure form of the color at maximum brightness.

Case 2 : At Brightness of 50 %
Red : 128 , Green : 64 , Blue : 0 (Red is the dominant color, Green is the secondary color, Blue is 0 at 30 degrees)
Here saturation is 100 percent. i.e. This is a 100 percent pure form of the color at 50 percent brightness.

Now lets modify the saturation to 50 percent and see

When we say 50 percent saturation, what we mean is that as compared to the color at a given brightness, the quantity of the non dominant colors have increased by an amount of 50 percent of the difference between their current value and the dominant color's value.

Case 3 : At Brightness of 50 % and saturation 50 percent
Red : 128 , Green : 96 , Blue : 64 (Red is the dominant color, Green is the secondary color, Blue is 0 at 30 degrees)
This is a 50 percent pure form of the color at 50 percent brightness.


To do the Math for case 3.
Initially assume saturation 100%

Step 1 : Identify dominant color
Dominant Color at 30 degrees : Red

Step 2 : Determine the mix at 30 degrees and At Brightness:100%
At Brightness:100%, RGB = R:255, G:128, B:0

Step 3 : Determine mix at 30 degrees and At Brightness:50%
At 50 percent brightness, RGB = R:128, G:64, B:0

Step 4 : Now, consider the saturation for the non dominant colors
(Red value) minus (Green value) at 100 % saturation = (128) - (64) = 64
50 % saturation means = 50 % of 64 = 32
Final value of Green at 50 percent saturation : 64 + 32 = 96

Similarly, we calculate the final value for Blue as

(Red value) - (Blue value) at 100 % saturation = (128) - (0) = 128
50 % saturation means = 50 % of 128 = 64
Final value of Blue at 50 percent saturation : 0 + 64 = 64

Now we are finally done with our HSV scheme. So, the next time that you find yourself playing with a color palette, and you decide to fiddle with the HSV values, I believe that this article would help you have a better understanding of what changes in the color you can expect when you make changes to the respective HSV values. And moreover you should be easily able to tell the RGB colors based upon you HSV colors by doing some mental maths.

Hope you had fun!

Signing Off
Ryan