Monday, 23 February 2015

Difference Between Equi, Inner and Natural Join

L join clause is used to to retrieve data from two or more database tables. In previous article, I have explained theDifferent Types of SQL Joins. In this article, I would explain the difference among inner join, equi join and natural join.

Inner Join

This is the most used join in the SQL. this join returns only those records/rows that match/exists in both the database tables.

Inner Join Example

  1. SELECT * FROM tblEmp JOIN tblDept
  2. ON tblEmp.DeptID = tblDept.DeptID;
  3. Inner Join Result
    tblEmp.Name
    tblEmp.DeptID
    tblDept.Name
    tblDept.DeptID
    Ram
    1
    HR
    1
    Raju
    2
    IT
    2
    Soya
    2
    IT
    2
    Sam
    3
    ADMIN
    3
    In the join condition, you can also use other operators like <,>,<>.

Equi Join

Equi join is a special type of join in which we use only equality operator. Hence, when you make a query for join using equality operator then that join query comes under Equi join.

Equi Join Example

  1. SELECT * FROM tblEmp JOIN tblDept
  2. ON tblEmp.DeptID = tblDept.DeptID;
  3. --Using Clause is not supported by SQL Server
  4. --Oracle and MySQL Query
  5. SELECT * FROM tblEmp INNER JOIN tblDept USING(DeptID)
Equi Join Result
tblEmp.Name
tblEmp.DeptID
tblDept.Name
tblDept.DeptID
Ram
1
HR
1
Raju
2
IT
2
Soya
2
IT
2
Sam
3
ADMIN
3

Note

  1. Inner join can have equality (=) and other operators (like <,>,<>) in the join condition.
  2. Equi join only have equality (=) operator in the join condition.
  3. Equi join can be an Inner join, Left Outer join, Right Outer join
  4. The USING clause is not supported by SQL Server and Sybase. This clause is supported by Oracle and MySQL.

Natural Join

Natural join is a type of equi join which occurs implicitly by comparing all the same names columns in both tables. The join result have only one column for each pair of equally named columns.

Natural Join Example

  1. --Run in Oracle and MySQL
  2. SELECT * FROM tblEmp NATURAL JOIN tblDept
  3. Natural Join Result
    DeptID
    tblEmp.Name
    tblDept.Name
    1
    Ram
    HR
    2
    Raju
    IT
    2
    Soya
    IT
    3
    Sam
    ADMIN
    In the above join result we have only one column "DeptID" for each pair of equally named columns.

Note

  1. In Natural join, you can't see what columns from both the tables will be used in the join. In Natural join, you might not get the desired result what you are expecting.
  2. Natural join clause is not supported by SQL Server, it is supported by Oracle and MySQL.
References: http://support.microsoft.com/ and http://en.wikipedia.org/

Friday, 20 February 2015

How To Use Caching with the Yii Framework To Improve Performance

How To Use Caching with the Yii Framework To Improve Performance

Amongst the many features that the incredible Yii framework offers, a cache management system is something that couldn't have been missing.
Yii framework allows us to save both static data and your SQL/Active Record queries, which -if used wisely- can lead to a lot of page loading time saving.
In particular, in this tutorial we are going to learn how to cache Data and Queries.
So here's how we enable cache in Yii.

Activate the Cache Component

The first step consists in activating the cache component. Just open your configuration file (located under protected/config/), go to the components array, and add the following code right within the array:
'cache'=>array( 
    'class'=>'system.caching.CDbCache'
)
By doing so, we are choosing to use CDbCache, which is just one of the Caching Components available with Yii. This particular one stores the cached data in a SQLite database, which makes it extremely easy to set up. And while not being the best choice in terms of performance, it will still make our web application slightly faster.
Another viable and more powerful option is to use the CApcCache component, which makes use of APC, the built-in caching system that comes with the newest versions of PHP.
Since all these Cache components are based on top of the CCache class, you can easily switch from a cache component to another by changing the name of the component (e.g. system.caching.CApcCache), while not having to change any code throughout your application.

Simple Data Caching

The first and simplest way to use cache is by storing variables. To do that, Yii's cache component gives you two functions: get() and set().
So we start by setting a value to be cached. To do so, we will also have to assign it a unique ID. For example:
// Storing $value in Cache
$value = "This is a variable that I am storing";
$id    = "myValue";
$time  = 30; // in seconds

Yii::app()->cache->set($id, $value, $time);
The last value, $time, is not required, although useful in order to avoid storing a value forever when it's not necessary.
Getting the stored value is trivial:
Yii::app()->cache->get($id);
Should the value not be found (because it does not exist or because it did expire before), this function will return a false value. Thus, for example, a nice way of checking if a certain value is cached would be:
$val = Yii::app()->cache->get($id);
if (!$val):
    // the value is not cached, do something here
else:
    // the value is cached, do something else here
endif;

Delete a cached value

To delete a value that is stored in cache, we can call:
Yii::app()->cache->delete($id);
If what we need is to clean everything, we will just write:
Yii::app()->cache->flush();

Query Caching

Built on top of the Data Caching system, this is a very useful feature, especially for heavy apps that rely intensely on a Database.
The concept of this feature is fairly easy but pretty solid.
Firstly, what we have to do is to define a dependency query. In other words, we define a much simpler and lighter Database Query that we will call before the one that we really need. The reason for doing that is to check if anything has changed since the last time that we executed that query.
If, for example, the data we want to retrieve is a list of Book Authors, our dependency query might well be:
SELECT MAX(id) FROM authors
By doing so, we will be able to see if any new author has been added since the last time we checked. If no new author has been added, Yii's Cache component will take the Authors list directly from the cache, without executing again our big query, which could be something like:
SELECT authors.*, book.title 
FROM authors 
JOIN book ON book.id = authors.book_id

Yii Query Builder

To use Query Caching with the Yii Query Builder, this is what we have to write [using the Authors' example showed before]:
// big query
$query = ' SELECT authors.*, book.title 
FROM authors 
JOIN book ON book.id = authors.book_id';
// dependency query 
$dependency = new CDbCacheDependency('SELECT MAX(id) FROM authors'); 
// executing query using Yii Query Builder
$result = Yii::app()->db->cache(1000, $dependency)->createCommand($query)->queryAll();
The arguments passed to Yii::app()->db->cache() are, respectively, the amount of seconds that the result should be stored for and the dependency query.
As explained before, when running this code, Yii will check for the result of the dependency query before anything else. Should it not find anything, or a different value from the one stored before, it will execute the big query and store the result in cache. Otherwise it will extract the big query result from the cache.

Active Record

It is also possible to cache the result of a query made using Active Record. The concept remains the same as explained before; but with a different syntax, of course:
$dependency = new CDbCacheDependency('SELECT MAX(id) FROM authors');
$authors = Author::model()->cache(1000, $dependency)->with('book')->findAll();

Things to keep in mind

It's pretty obvious that an application that makes intensive use of caching would need to be well designed in advance, since the risk of serving inconsistent data to the user will increase inevitably.
Also, don't forget that each caching component might have limits on the amount of data that can be stored. It's thus a good practice to find out in advance the limit of your caching system.

Limitations

Query caching does not work with query results that contain resource handles. For example, when using theBLOB column type in some DBMS, the query result will return a resource handle for the column data.
Some caching storage has size limitation. For example, memcache limits the maximum size of each entry to be 1MB. Therefore, if the size of a query result exceeds this limit, the caching will fail.

Difference between port and socket

A port is part of the address in the TCP and UDP protocols. It is used to help the OS identify which application should get the data that is received. An OS has to support ports to support TCP and UDP because ports are an intrinsic part of TCP and UDP.
A socket is part of the interface the OS presents to applications to allow them to send and receive network data. Most socket implementations support many protocols beyond TCP and UDP, some of which have no concept of ports. An OS does not have to support sockets to support TCP or UDP; it could provide a different interface for applications to use. A socket is simply one way of sending and receiving data on a specific port.
Think of your machine as an apartment building:
  • A port is an apartment number.
  • A socket is the door of an apartment.
  • An IP address is the street address of the building

A computer has an IP address that identifies it as a separate entity on the network. We add an additional number to that to allow us to differentiate between connections to that computer. This is the port number. On the OS side of the connection you need buffers, connection state, etc. This logical object is the socket.

A socket is a communication path to a port. When you want your program to communicate over the network, you have given it a way of addressing the port and this is done by creating a socket and attaching it to the port. Basically, socket = IP + ports Sockets provide access to the port+ip

S is a server: let's say it's an HTTP server, so it'll use the well-known port number for HTTP, which is 80. I run it on a host with IP address 10.0.0.4, so it will be listening for connections on 10.0.0.4:80(because that's where everyone will expect to find it).
Inside S, I'm going to create a socket and bind it to that address: now, the OS knows that connections coming into 10.0.0.4:80 should be routed to my S process via that particular socket.
  • netstat output once socket is bound:
    $ netstat --tcp -lan
    Active Internet connections (servers and established)
    Proto Recv-Q Send-Q Local Address               Foreign Address            State
    tcp        0      0 0.0.0.0:80                  0.0.0.0:*                  LISTEN
    
    NB. the local address is all zeroes because S doesn't care how its clients reach it
Once S has this socket bound, it will accept connections - each time a new client connects, acceptreturns a new socket, which is specific to that client
  • netstat output once a connection is accepted:
    $ netstat --tcp -lan
    Active Internet connections (servers and established)
    Proto Recv-Q Send-Q Local Address               Foreign Address            State
    tcp        0      0 0.0.0.0:80                  0.0.0.0:*                  LISTEN
    tcp        0      0 10.0.0.4:80                 10.0.0.5:55715             ESTABLISHED
    
    • 10.0.0.4:80 represents S's end of the connection, and is associated with the socket returned by accept
    • 10.0.0.5:55715 is the client's end of the connection, and is associated with the socket the client passed to connect. The client's port isn't used for anything except routing packets on this TCP connection to the right process: it's assigned randomly by the client's kernel from the ephemeral port range.
Now, S can happily go on accepting more client connections ... each one will get its own socket, each socket will be associated with a unique TCP connection, and each connection will have a unique remote address. S will track client state (if there is any) by associating it with the socket.
So, roughly:
  • the IP address is for routing between hosts on the network
  • the port is for routing to the correct socket on the host
    • I nearly said correct process, but it's actually possible to have multiple (usually child) processes all accepting on the same socket ...
    • however, each time one of the concurrent accept calls returns, it does so in only oneprocess, each incoming connection's socket is unique to one instance of the server
  • the socket is the object a process uses to talk to the OS about a particular connection, much like a file descriptor
    • as Dirk says, there are plenty of other uses for sockets that don't use ports at all: for examplesocketpair creates a pair of sockets connected together that have no addressing scheme at all - the only way to use that pipe is by being the process which called socketpair, being a child of that process and inheriting one, or being explicitly passed one of the sockets from that process

Thursday, 19 February 2015

UBUNTU Interview questions

1) Explain why Ubuntu is safe and not affected by viruses?
  • It does not support malicious e-mails and contents, and before any e-mail is opened by users it will go through many security checks
  • Ubuntu uses Linux , which is a super secure O.S system
  • Unlike other O.S, countless Linux users can see the code at any time and can fix the problem if there is any
  • Generally, Malwares and viruses are coded to take advantage of weakness in Windows
2) Explain what is Unity in Ubuntu ? How can you add new entries to the launcher?
In Ubuntu, Unity is the default windows manager.  On left side of the Ubuntu it introduces the launcher and Dash to start programs.
In order to add new entries to the launcher you can create a file name like .desktop and  then drag file on the launcher.
3) Whether your video card can run Unity how would you know?
When you use command /usr/lib/nux/unity_support_test-p it will give detailed output about Unity’s requirements and  if they are met, then your video card can run unity.
4) Explain how to enable root loging in Ubuntu?
The command which enables root loging is
#sudo sh-c ‘echo “greater-show-manual-login=true” >>/etc/lightdm/lightdm.conf’
Ubuntu
5) Explain how to enable startup sound in Ubuntu?
To enable startup sound in Ubuntu
  • Click control gear and then click on Startup Applications
  • In the Startup Application Preferences window, click Add to add an entry
  • Then fill the information in comment box like Name, Command and Comment
/usr/bin/canberra-gtk-play—id= “desktop-login”—description= “play login sound”
  • Logout and then login once you are done
6) Explain how you can reset Unity Configuration?
To reset the unity configuration the simplest way to do is to hit open a Terminal or hit Atl-F2  and run the command # unity –reset
7) Explain how to access Terminal?
To access terminal , you have to go under Application Menu -> Accessories -> Terminal .
You can also open it with shortcut key Ctrl+Alt+T. 
8) Explain how you can create a folder in Ubuntu using Terminal?
To create a folder in Ubuntu, you have to use command mkdir.  It will be something like these :  ~$ mkdir Ubuntu_rules
9) Explain how you can view the text file in Ubuntu using Terminal?
To view the text file in Ubuntu, go to the specific folder where the text files are located by using the commandcd and then type less filename.txt.
10) Explain how to enable curl on Ubuntu LAMP stack?
To enable curl on Ubuntu , first install libcurl, once done use following command sudo/etc/init .d /apache2 restart or sudo service apache2 restart.
11) Explain how you can find a file in Ubuntu using Terminal?
To find a file in Ubuntu you have to use command, find . –name “process.txt” .  It will look for the current directory for a file called process.txt.
12) What is the quicker way to open an Ubuntu terminal in a particular directory?
To open Ubuntu terminal in a particular directory you can use custom keyboard short cut. To do that, in the command field of a new custom keyboard , type genome – terminal – – working – directory = /path/to/dir.
13) Explain what is the meaning of “export” command in Ubuntu?
Export is a command in Bash shell language, when you try to set a variable, it is visible or exported to any subprocess started from that instance of bash.  The variable will not exist in the sub-process without the export command.
14) Explain how to uninstall the libraries in Ubuntu?
To uninstall the libraries in Ubuntu, you can use command sudo apt – get remove library_name
15) How you can run an Ubuntu program in the background simultaneously when you start your Ubuntu Server?
By using nohup.  It will stop the process receiving the NOHUP signal and thus terminating it you log out of the program which was invoked with.  & runs the process in the background.
16) Explain how you can get the current color of the current screen on the Ubuntu desktop?
You can open the background image in The Gimp (image editor) and then use the dropper tool to select the color on the specific point. It gives you the RGB value of the color at that point.
17) Explain what is the purpose of using libaio package in Ubuntu?
Libaio is Linux Kernel Asynchronous I/O (A/O).  A/O allows even a single application thread to overlap I/O operations with other processing, by providing an interface for submitting one or more I/O requests in one system call without waiting for completion.  And a separate interface to reap completed I/O operations associated with a given completion group.
18) Explain how you create launchers on desktop in Ubuntu?
To create launchers on desktop in Ubuntu you can use
ALT+F2 then type “ gnome-desktop-item-edit –create-new~/desktop “,  it will launch the old GUI dialog and create a launcher on your desktop
19) Explain how to color the Git console in Ubuntu?
To color the Git console in Ubuntu you can use the command git config—global color.ui auto.  In the command, the color.ui variable sets the default value for variable such as color.diff and color.grep.
20) How you can append one file to another in Ubuntu Linux?
To append one file to another in Ubuntu Linux you can use command cat file2 >> file 1.  The operator >> appends the output of the named file or creates the file if it is not created.  While another command cat file 1 file 2 > file 3 appends two or more files to one.
21) What is the use of behaviour tab in Ubuntu?
Through behaviours tab you can make many changes on the appearance of desktop
  • Auto hide the launcher : You can use this option to reveal the launcher when moving the pointer to the defined hot spot.
  • Enable workspaces:  By checking this option you can enable workspace
  • Add show desktop icon to the launcher: This option is used to display the desktop icon on the launcher
22) What is the command to calculate the size of a folder?
To calculate the size of a folder use the command du –sh folder1.
23) What is a folder in Ubuntu ?
There is no concept of Folder in Ubuntu. Everything including your hardware is a FILE
24) How can you find status of a process using Ubuntu ?
Use the command
ps ux
25) How can you check the memory status ?
You can use the command
free -m  to display output in MB
free -g  to display output in GB