Maven Installation

 Search Maven package  
 apt-cache search maven  

 Install it  
 sudo apt-get install maven  

 Verification  
 mvn -version  

 Where is Maven installed  
 The command apt-get install the Maven in /usr/share/maven  
 The Maven configuration files are stored in /etc/maven  

Installation of Tomcat7 : using port 80

 Installation Tomcat using apt-get  
 sudo apt-get install tomcat7  

 Install the package using apt-get  
 sudo apt-get install tomcat7-docs  
 sudo apt-get install tomcat7-examples  
 sudo apt-get install tomcat7-admin  

 The above instruction is more than enough to install the tomcat. If any error happened please follow the below the instructions.  
 Setup the JDK path for Tomcat   
 sudo nano /etc/default/tomcat7 : add the JDK path inside the file  
 Set the path   
 sudo nano ~/.bashrc  
 export CATALINA_HOME=/usr/share/tomcat7  

 Stop Server:  
 sudo /etc/init.d/tomcat7 stop  

 Start Server:  
 sudo /etc/init.d/tomcat7 start  

 Folder locations of tomcat :  
 Tomcat bin and lib file location :  
 /usr/share/tomcat7  

 Tomcat xml file :  
 /etc/tomcat7  

 Tomcat config and webapp files:  
 /var/lib/tomcat7/  

 Tomcat JDK and Path Setup   
 sudo nano /etc/default/tomcat7  

 To Run Tomcat on port 80  
 <Connector port="8080" protocol="HTTP/1.1"  
 connectionTimeout="20000" redirectPort=  
 "8443" />  
 Change 8080 to 80 in /config/server.xml file  
  AND  

 Remove the comment using :  
 sudo nano /etc/default/tomcat7 and   
 change #AUTHBIND=no  
 as AUTHBIND=yes  

 To remove all the files   
 sudo apt-get purge libtomcat7-java tomcat6 tomcat6-admin tomcat6-docs tomcat6-examples tomcat7 tomcat7-admin tomcat7-common tomcat7-docs tomcat7-examples tomcat7-user  
 To check what are the process running on port 80  
 netstat -tulpn | grep :80  
 Server.XML user name and password  
 <role rolename="manager-gui"/>  
 <user username="Dhanu" password="" roles="manager-gui"/>  
 <role rolename="admin-gui"/>  
 <user username="Dhanu" password="" roles="admin-gui"/> 
 
 NOTE:  
 Change the Heap memory in tomcat :  
 sudo nano /etc/default/tomcat7 and change the line on -Xms value  
 JAVA_OPTS="-Djava.awt.headless=true -Xmx2048m -XX:+UseConcMarkSweepGC"  
 In Default It’s limited to 128MB.   

Difference between Process and Thread

Process

  • An executing instance of a program is called a process.
  • Some operating systems use the term ‘task‘ to refer to a program that is being executed.
  • A process is always stored in the main memory also termed as the primary memory or random access memory.
  • Therefore, a process is termed as an active entity. It disappears if the machine is rebooted.
  • Several process may be associated with a same program.
  • On a multiprocessor system, multiple processes can be executed in parallel.
  • On a uni-processor system, though true parallelism is not achieved, a process scheduling algorithm is applied and the processor is scheduled to execute each process one at a time yielding an illusion of concurrency.
  • Example: Executing multiple instances of the ‘Calculator’ program. Each of the instances are termed as a process.

Thread

  • A thread is a subset of the process.
  • It is termed as a ‘lightweight process’, since it is similar to a real process but executes within the context of a process and shares the same resources allotted to the process by the kernel (See kquest.co.cc/2010/03/operating-system for more info on the term ‘kernel’).
  • Usually, a process has only one thread of control – one set of machine instructions executing at a time.
  • A process may also be made up of multiple threads of execution that execute instructions concurrently.
  • Multiple threads of control can exploit the true parallelism possible on multiprocessor systems.
  • On a uni-processor system, a thread scheduling algorithm is applied and the processor is scheduled to run each thread one at a time.
  • All the threads running within a process share the same address space, file descriptor, stack and other process related attributes.
  • Since the threads of a process share the same memory, synchronizing the access to the shared data withing the process gains unprecedented importance.

What is Java thread


A thread is a thread of execution in a program. The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.

Every thread has a priority. Threads with higher priority are executed in preference to threads with lower priority. Each thread may or may not also be marked as a daemon. When code running in some thread creates a new Thread object, the new thread has its priority initially set equal to the priority of the creating thread, and is a daemon thread if and only if the creating thread is a daemon.

Difference between “implements Runnable” and “extends Thread” in java

In java language, as we all know that there are two ways to create threads. One using Runnable interface and another by extending Thread class.

There has been a good amount of debate on which is better way. Well, I also tried to find out and below is my learning:

1) Implementing Runnable is the preferred way to do it. Here, you’re not really specializing or modifying the thread’s behavior. You’re just giving the thread something to run. That means composition is the better way to go.

2) Java only supports single inheritance, so you can only extend one class.

3) Instantiating an interface gives a cleaner separation between your code and the implementation of threads.

4) Implementing Runnable makes your class more flexible. If you extend thread then the action you’re doing is always going to be in a thread. However, if you extend Runnable it doesn’t have to be. You can run it in a thread, or pass it to some kind of executor service, or just pass it around as a task within a single threaded application.

5) By extending Thread, each of your threads has a unique object associated with it, whereas implementing Runnable, many threads can share the same runnable instance.

6) If you are working on JDK 4 or lesser, then there is bug :

Crop Image Using Java

 import java.awt.image.BufferedImage;  
 import java.io.File;  
 import java.io.IOException;  
 import javax.imageio.ImageIO;  
 public class test {  
      public static void main(String[] args) throws IOException {  
           test t = new test();  
           t.getCropImage();  
      }  
      public void getCropImage() throws IOException {  
           int widthOfNewImage = 100;  
           int heightOfNewImage = 100;  
           int offsetFromLeft = 10;  
           int offsetFromTop = 100;  
           String path = "input.gif";  
           String newPath = "newImage.png";  
           String imageFormat = "png";  
           BufferedImage image = ImageIO.read(new File(path));  
           int height = image.getHeight();  
           int width = image.getWidth();  
           System.out.println("Height : " + height + "\nWidth : " + width);  
           BufferedImage out = image.getSubimage(offsetFromLeft, offsetFromTop,  
                     widthOfNewImage, heightOfNewImage);  
           ImageIO.write(out, imageFormat, new File(newPath));  
      }  
 }  

Import CSS and JQuery files in JSP

 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
 <link type="text/css" rel="stylesheet"href="${pageContext.request.contextPath}/css/bootstrap.min.css" />  
 <script type="text/javascript"src="//ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>  
 <title>Concept Extractor</title>  
 <script type="text/javascript">  
  $(document).ready(function() {  
  alert("asdf");  
  });  
 </script>  

How to change eclipse background Theme

Installation

If you are on Eclipse 3.6 (Helios), the easiest way to install the plugin is from the Eclipse Marketplace. Go to Help→Eclipse Marketplace..., then search for Eclipse Color Theme and install it.
If you are on Eclipse 3.5 (Galileo), go to Help→Install New Software..., press Add Site and enterEclipse Color Theme as the name and http://eclipse-color-theme.github.com/update as the URL. Then select the new entry from the select box labeled Work with, mark Eclipse Color Theme for installation and proceed.
Please note: If you are using a version of the plugin lower than 0.6, please uninstall and reinstall it following the instructions above. Update site and plugin ID have changed.

Usage

After the installation, go to Window→Preferences→General→Appereance→Color Theme to change the color theme.
If you have a feature request, create an issue or a pull request on GitHub.

Is it possible to get HTML of an iframe - CAN'T

You are trying to access content of iframe which points to webpage from another domain. You cannot access content of iframe if the src of that iframe is not pointing to the domain on which your current parent page is. This is called cross domain policy

You will have to use server side language that will grab the html of given url and return it to your index page to display in any div or whatever.

Let me give you an example to explain why javascript cannot have cross domain access.
  • Suppose i have FB like box on my website inside an iframe
  • now whenever any user comes on my website i will trigger a click to the like box which is inside the iframe of like box.
  • This way my FB page will have lakhs of likes.
  • But because of cross domain policy this cannot be done.

Deployment of Apache Tomcat 7 in Amazon server


 Before Installation Check your java Jdk installed or not.  
 Step 1:  
 Download the Apache tomcat 7 from the bellow link,  
 Step2:  
 md5sum apache-tomcat-[#].tar.gz  
 Next, extract the package:  
 tar xvzf apache-tomcat-[#].tar.gz  
 And move the extracted folder into a dedicated directory:  
 sudo mv apache-tomcat-[#] /usr/local/apache  
 Step3: Set the path   
 vi ~/.bashrc  
 export CATALINA_HOME=/usr/local/apache  
 Log out and log back into bash to have your changes take effect.  
 Step4: Start tomcat  
 sudo /usr/local/apache/bin/startup.sh  
 Step 5 : Check  
 Go to web browser and type ,  
 http://localhost:8080  

How to remove sudo password :



For the administrative password using sudo and sparing any lectures on why one would not want this...
Edit the sudoers file:  sudo visudo

Find this line:%sudo ALL=(ALL) ALL

Change the line:%sudo ALL=(ALL) NOPASSWD: ALL

Save and Exit. Voila! (Dont' shoot yourself in the foot, now. ;) By the way, you can become root and just type the password once.sudo su -  Now you ARE the root user, seeing no more password prompts. When you see guides referring to commands such as sudo some_command, just remove the "sudo" portion. In this way, you can choose to leave the security intact yet bypass it as you see fit.

If you are writing about your user account:

Open System Settings. Click on the User Accounts tile. Click the Unlock button and enter your password. Set the auto-login slider to the "on" position by dragging it to the right. Then click "Lock" to apply your changes.

Install Oracle java using terminal

sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java7-installer

Deployment of Glassfish In amazon server

GlassFish is an open-source application server project started by Sun Microsystems for the Java EE platform and now sponsored by Oracle Corporation. The supported version is called Oracle GlassFish Server. GlassFish is free software, dual-licensed under two free software licences: the Common Development and Distribution License (CDDL) and the GNU General Public License (GPL) with the classpath exception.

GlassFish is the reference implementation of Java EE and as such supports Enterprise JavaBeans, JPA, JavaServer Faces, JMS, RMI, JavaServer Pages, servlets, etc. This allows developers to create enterprise applications that are portable and scalable, and that integrate with legacy technologies. Optional components can also be installed for additional services.




 Step 1:   
 Connect the Amazon server through terminal using DNS and the KEY.  
 To connect with amazon server:  
 ssh -i <key_path> <username>@<ip_adress_server>  
 First of all we need to check the java dependencies.  
 sudo apt-get update  
 sudo apt-get remove openjdk-6-jre-headless  
 sudo apt-get install sun-java6-jdk sun-java6-jre sun-java6-javadb  
 sudo apt-get autoremove  
 Step 2:  
 go to terminal in Ubuntu  
 go to your home directory in terminal   
 enter wget http://download.java.net/glassfish/4.0/release/glassfish-4.0.zip to download the glassfish in to your server.  
 Step 3:  
 Configure and change default port for Glassfish if tomcat already use port 8080.Because usually it use the port 4848.If you need as default please avoid thid Step 3.  
 vim glassfishv3/glassfish/domains/domain1/config/domain.xml  
 <network-listeners>  
 <network-listener port="8081" protocol="http-listener-1" transport="tcp" name="http-listener-1" thread-pool="http-thread-pool" />  
 <network-listener port="8181" protocol="http-listener-2" transport="tcp" name="http-listener-2" thread-pool="http-thread-pool" />  
 <network-listener port="4848" protocol="admin-listener" transport="tcp" name="admin-listener" thread-pool="http-thread-pool" />  
 </network-listeners>  
 Step 4:  
 Running by Glassfish  
 ./glassfishv3/glassfish/bin/asadmin start-domain --verbose  
 Step5:  
 Go to your-domain:8081 to see web page and your-domain:4848 for administrator pages  
 Glassfish Controls :  
 Create domain  
 Start and Stop Domain  
 Delete Domain  
 Enable secure Admin  

 Error may occur:  
 Solution:  
 http://charleech.wordpress.com/2012/03/23/glassfish-version-3-1-2-secure-admin-must-be-enabled-to-access-the-das-remotely/  
 http://coders-kitchen.com/tag/secure-admin-must-be-enabled-to-access-the-das-remotely/  

Super Html 5 Demos

http://hakim.se/experiments

Send message to specific user using socket.io

If we want to pass the message for a specific user who is in active. we need to get the socket Id of the specific user. By using the ID we can emit to single user. code is mentioned bellow.

io.sockets.socket(<ID of the user>).emit(<function name>,<variable>,<variables>);

Java Questions : 1

Problem I You are provided with a series of numbers as the input. You have to print a series of characters containing x and o depending on the value of each number. For each odd number, the printed pattern must end with an x. For even numbers, the pattern should end with an o. An empty line should be printed for the number zero.

Write a program to print a pattern looking at the examples given below.

All numbers will be integers (whole numbers) between 0 and 100. Sample Input The program would be run using command line parameters as shown below.

*Java:-** * java yourprogram 2 3 5 6 1

The output is shown below as it is accepted by the system.
*

xo
xox
xoxox
xoxoxo
x

*Sample Input 2 The program would be run using commandline parameters asshown below.

*Java:-** * java yourprogram 5 10 6 4 2 9
The output is shown below as it is accepted by the system.

*

xoxox
xoxoxoxoxo
xoxoxo
xoxo
xo
xoxoxoxox

*

handling Object in Javascript

A JavaScript object has properties associated with it. A property of an object can be explained as a variable that is attached to the object. Object properties are basically the same as ordinary JavaScript variables, except for the attachment to objects. The properties of an object define the characteristics of the object. You access the properties of an object with a simple dot-notation:

objectName.propertyName

Like all JavaScript variables, both the object name (which could be a normal variable) and property name are case sensitive. You can define a property by assigning it a value. For example, let's create an object named myCar and give it properties named make, model, and year as follows:

var myCar = new Object();
myCar.make = "Ford";
myCar.model = "Mustang";
myCar.year = 1969;


Properties of JavaScript objects can also be accessed or set using a bracket notation. Objects are sometimes called associative arrays, since each property is associated with a string value that can be used to access it. So, for example, you could access the properties of the myCar object as follows:

myCar["make"] = "Ford";
myCar["model"] = "Mustang";
myCar["year"] = 1969;


An object property name can be any valid JavaScript string, or anything that can be converted to a string, including the empty string. However, any property name that is not a valid JavaScript identifier (for example, a property name that has space or dash, or starts with a number) can only be accessed using the square bracket notation. This notation is also very useful when property names are to be dynamically determined (when the property name is not determined until runtime). Examples are as follows:

var myObj = new Object(),
str = "myString",
rand = Math.random(),
obj = new Object();

myObj.type = "Dot syntax";
myObj["date created"] = "String with space";
myObj[str] = "String value";
myObj[rand] = "Random Number";
myObj[obj] = "Object";
myObj[""] = "Even an empty string";

console.log(myObj);



Reference : 

Install Apache 2 In Linux


Apache is the web server piece of our puzzle. From within your terminal window issue the command:

sudo apt-get install apache2

If, by chance, you are using a distribution that does not use Sudo, you will need su to the root user and issue the above command without the sudo command.
Depending on your OS installation, the above command might need to pick up some dependencies. If so, okay those dependencies. At the end of the installation, Apache should automatically start. If it doesn't, issue the following command:

sudo /etc/init.d/apache2 start

You can now open up a browser and point it to the IP address (or domain) of the server to get the famous "It works!" page. You are ready to move on to PHP.

Ready For Interviews (Summary)

After spending couple hours of time i came up with summary of the Software interview question .I hope it will help full to you.

Tell me about yourself.
A good answer to this question is about two minutes long and focuses on work-related skill s and Accomplishments. Tell the interviewer why you think your work-related skills and Accomplishments would be an asset to the comp any. Do not describe yourself with tired old cliché s such as "I am a team player," "I have excellent communication skill s," unless you u can prove it

Why should we hire you?   
Take several minutes to answer this question, incorporating your personality traits, strengths, and experience in to the job you're applying for. A good answer is to focus on how you can benefit the company. 

As I understand your needs, you are first and foremost looking for someone who can manage the sales and marketing of your book publishing division. As you’ve said you need someone with a strong background in trade book sales. This is where I’ve spent almost my entire career, so I’ve chalked up 18 years of experience exactly in this area. I believe that I know the right contacts, methods, principles, and successful management techniques as well as any Person can in our industry.

What do you worry about?
Redefine the word ‘worry’ so that it does not reflect negatively on you. 
Example: “I wouldn’t call it worry, but I am a strongly goal-oriented person. So I keep turning over in my mind anything that seems to be keeping me from achieving those goals, until I find a solution. That’s part of my tenacity, I suppose.”

What is your greatest strength (or strengths)?
I have the ability to train and motivate people. At Acme Co., employee turnover was very high. Intelligence...management "savvy". 
Honesty...integrity...a decent human being. 
Good fit with corporate culture...someone to feel comfortable with...a team player who meshes 
well with interviewer's team. 
Likeability...positive attitude...sense of humor. 
Good communication skills. 
Dedication...willingness to walk the extra mile to achieve excellence. 
Definiteness of purpose...clear goals. 
Enthusiasm...high level of motivation. 
Confident...healthy...a leader.

What is your greatest weakness s (or weaknesses)? 
Don't answer by claiming that you have no weaknesses. Confess a real weakness that you have, but choose one that isn't particularly relevant to the job you're seeking. Does n o t answer with phony weaknesses such as "I'm a slave to my job" or "I'm a workaholic?" Just state the weakness, tell the interview how it has harmed you in your work life, and what steps you have taken to improve it. A good step one can take to improve a weakness is to read self-help books on the subject. 



“Nobody's perfect, but based on what you've told me about this position, I believe I' d make an outstanding match. I know that when I hire people, I look for two things most of all. Do they have the qualifications to do the job well, and the motivation to do it well? Everything in my background shows I have both the qualifications and a strong desire to achieve excellence in whatever I take on. So I can say in all honesty that I see nothing that would cause you even a small concern about my ability or my strong desire to perform this job with excellence.” 

Instead of confessing a weakness, describe what you like most and like least, making sure that what you like most matches up with the most important qualification for success in the position, and what you like least is not essential.

Do you work better alone or as part o f a team?
If the position you're applying for require s you to spend lots of time alone, then of course, you should state that you like to work alone and vice versa.

Do you consider yourself to be a risk -taker? 
How you answer this question depends on the type of company it is. If it is a start-up company or within a highly-competitive industry, then they are probably looking for those more willing to take risks. If you believe the company is this type, then offer an example of a risk you've taken in business. If the company is a well-established industry leader, risk takers are not as highly valued. Of course, no comp any is looking for employee s who are foolish in their risk-taking behavior r, so a good rule of thumb is to place yourself f somewhere in the middle -- you are neither too foolish nor overly cautious . 

What salary are you expecting?  
You should do some research before the job interview so that you don't ask for too much o r too little. You might be asked to justify why you are worth the salary you are asking, so be prepared with an answer (i.e., tell them how your skills and experience will benefit the company so much that your salary will be a bargain for them.)

Who is your favorite boss?
These are two of the most difficult interview questions to answer unless you understand what the interviewer wants to hear, and if you realizes at you can answer both questions with basically the same answer. Employers are looking for employees who are interested in contributing to the comp any, improving their job skill and making a contribution. So, instead of insulting o r d e meaning your past bosses by telling the interviewer that he was always "hogging all the crew d it" or was "totally in competent",

When can you start?
It is customary for most employees to give at least two weeks’ notice to their current employer. Those in management positions are expected to give long r notice. You will not earn points if you express disrespect toward your current employer by telling the interviewer that you plan to q u it your present job without giving sufficient notice. He will assume you will show his company the same amount of disrespect . It is also a good idea to tell the interviewer you plan to start learning about your n e w position / employ r on your off-hours (i.e., reading employee training manuals, etc.) Telling the interviewer you can't begin work for a few month s b e cause you want to take some time-off is not a good idea

How long can you commit to work with us?
I like new challenges and a chance to grow. As long I keeping getting these, I don’t think I’ll need to switch over. I’d like to believe that this Relationship lasts for many years. However, I haven’t set a time limit as such.

You seem to be drawing a good salary. Will you be OK in taking a salary cut?
I believe that at one point of time in career salary becomes secondary and self-actualization become more important. While taking up any new job, it will be my priority to ensure that the work culture, chances to contribute and grow are sufficient along with the money I am paid. I also believe that any good company who cares about its employees ensures that they are paid well

What do you do to improve your knowledge?
The field of IT is very revolutionary. It is extremely important to keep yourself abreast with the new technological developments and this needs you to take some time out of your work schedule so that you can keep sharpening your saw. To answer this question, you can tell the recruiter about the forums which you keep visiting, blogs which you keep reading. It will be an advantage if you are a member of some local user group

What is more important to you: the money or the work?
Money is always important, but the work is the most important. There is no better answer.

What qualities do you look for in a boss?
Be generic and positive. Safe qualities are knowledgeable, a sense of humor, fair, loyal to subordinates and holder of high standards. All bosses think they have these traits. 

Do you have any blind spots?
Trick question. If you know about blind spots, they are no longer blind spots. Do not reveal any personal areas of concern here. Let them do their own discovery on your bad points. Do not hand it to them.

Can you perform under pressure?
Most of the times, the job of software development is that of working under pressure. Sometimes, it will be the pressure of delivering on time while it can be that of a bug that has sprung all of a sudden in your code. So, expect pressure in everything you do. It is important to maintain your performance and develop strategies to deliver under pressure. You can then go ahead and talk about your way of dealing with pressure and performing under it\

Tell us some of your weaknesses?
The best way to answer this question will be to turn one of your strengths as a weakness and say that others accuse you of having this weakness but you think it is important to work in this manner. For e.g.: “My colleagues accuse me of paying too much attention to syntaxes but I believe it is important when you are writing the code to avoid spending too much time on finding and fixing the bugs later on.”

You do not have all the experience we need for this position?
It is not possible for a candidate to have all the experience an employer requires. Even if you match yourself up to the expectations on technical front, there will be some difference in the work environment. And, it is absolutely fine. 
The best way to deal with this question is to analyses the requirements of the position well and match your skills as close to them as possible. If something is still left untouched, offer your quick grasping power and ability to learn quickly as a solution & back it up with an example from the past. 

What irritates you about co-workers?
The purpose of this question is to see how well you can fit into a team. Basically, you should not have a problem with a person, although you can have a problem with the style of working. So, to answer this question you can simply say, “I understand that IT is about team work, so we can’t afford to problems with co-workers but if someone is not serious about their work or does a low quality work affecting the whole project, I definitely do not like it

For how long do you expect to stay with our organization?
You should ensure that you give an impression that you will pay back more than what you take from the company: 
-You can say I will stay here as far as I see an opportunity for growth, as I am looking for a stability in work place 
-If they stress on number of years say 3-4 years, and more if I can explore new challenges/growth opportunities

Why should we hire you?
-Here you should discuss the profile you have applied for and your strengths/experience with which you can add value to the job 
-Discuss your achievements at your previous job, and say that I have developed my skills to suit my current profile, but I want to develop myself further and face new challenges, and for that I need to change my job. 
- I will always be willing to change roles share responsibilities to suit company requirements

Do you have any questions? 
This question is usually the last one an interviewer will ask as it is a logical way to end the interview. Never go to an interview without preparing questions to ask beforehand. Avoid asking about salary, vacation time, employee benefits, etc. until you have asked a number of other questions that demonstrate your interest in working for the company. Good questions to ask the interviewer:

What is your idea of an ideal company?
Do not go over board and ask for, it might give an impression that you are too demanding, some of the answers could be:
-An ideal company provides maximum opportunities for growth of employees. 
-They provide comfortable and flexible work environment, so that employees can perform at their best and work towards company’s benefit. 
-A company that encourages learning 
-A company that encourages opens culture

Why is this position available?
Is this a new position? Ho w long has this position existed? 
How many people have held this position in the last two years? 
Who would be my supervisor? To whom would I report? 
Whom will I supervise? 
With whom will I be working most closely? 
What do you like about working for this company? 
What are the current plans for expansion or cutbacks? 
What kind of turnover rate does the company have? 
How financially sound is this company? 
What projects and assignments will I be working on? 
What happened to the person that held this position before? Was he promoted or fired? 
What is this company's culture, (i.e., is it rigid and formal or relaxed and flexible?) 
What are the current problems facing the company (or my department)? 
What do you like the most about working for this company? The least? 
What is the philosophy of the company? 
What do you consider to be the company's strengths and weaknesses? 
What are the company's long and short term goals? 
Describe the work environment. 
What attracted you (the interviewer) to this organization? 
Why do you enjoy working for this company? 
Describe the typical responsibilities of the position. 
What are the most challenging aspects of the position? 
Describe the opportunities for training and professional development. 
Will I receive any formal training? 
What is the company's promotional policy? 
Are there opportunities for advancement within the organization? 
When can I expect to hear from you?

Event - Driven Development


Traditional programming does input and output the same way as it does local function calls: Processing cannot continue until an operation finishes. This programming model of blocking when doing I/O operations derives from the early days of time-sharing systems in which each process corresponded to one human user.  Managing many processes places a big burden on the operating system — in memory and context switching costs — and the performance of these tasks starts to decay after a certain number is reached.

Multi-threading is one alternative to this programming model. A thread is a kind of light- weight process that shares memory with every other thread within the same process. Threads were created as an ad hoc extension of the previous model to accommodate several concurrent threads of execution. When one thread is waiting for an I/O operation, another thread can take over the CPU. When the I/O operation finishes, that thread can wake up, which means the thread that was running can be interrupted and eventually be resumed later. Furthermore, some systems allow threads to execute in parallel in different CPU cores.

This means that programmers do not know what set of threads is executing at any given time, so they must be careful with concurrent access to the shared memory state. They have to use synchronization primitives like locks and semaphores to synchronize access to some data.

The solution is, Event-driven programming is a programming style whereby the flow of execution is determined by events. Events are handled by event handlers or event callbacks. An event callback is a function that is invoked when something significant happens — such as when the result of a database query is available or when the user clicks on a button. 

This style of programming — whereby instead of using a return value you define functions that are called by the system when interesting events occur — is called event-driven or asynchronous programming. 

The event-driven programming style is accompanied by an event loop. An event loop is a construct that mainly performs two functions in a continuous loop — event detection and event handler triggering. In any run of the loop, it has to detect which events just happened. Then, when an event happens, the event loop must determine the event callback and invoke it.

Module publish in Node.js




To upload or module  to npm repository we need to create a user account
command : npm adduser

To push our own module in to npm repository  we need to create the package json file. For that we have to do some step to complete

1) Go to project folder using terminal and command
npm init

2) This will create a package.json Which contain all the details about the module. During the process fill the detail that system asks

3) After creation of the user upload using
command : npm publish

4)Tthen we can search the packate in npmjs.org location with our module name.

NOTE: The module can be updateable using the npm publish command .but now we have to change the version in package.json file. After the change of version simply update the module using npm publish

Write File with Sync and Async using Node.js



Writing the file using file system module. we have two options to process synchronous and asynchronous. Here we are testing on synchronous of the node.js. The sequence of code should wait until we write the sample txt file. For that waiting we are using writeFileSync class from File system module.

var file = require("fs");
console.log("Starting...");

var contents = file.writeFileSync("./write_file.txt", "Text to Write");
console.log(" done ...");

Here we are testing on asynchronous of the node.js. The sequence of code should not wait until we read the sample txt file. For that we are using callback function.

var file = require("fs");

console.log("Starting...");

var contents = file.writeFile("./write_file.txt", "Text to Write",
function(error){
console.log("written file");
}
);

console.log(" done ...");

Read the file sync and async using Node.js



Reading the file using file system module. we have two options to process synchronous and asynchronous. Here we are testing on synchronous of the node.js. The sequence of code should wait until we read the file sample txt file. For that waiting we are using readFileSync class from File system module.

var file = require("fs");
console.log("Starting...");

var content = file.readFileSync("./sample.txt");
console.log("Content : " + content);
console.log("Keep going ...");

If we run the file in node. First it will print the sample txt and after that only it will print the “Keep going” String. Because it is waiting for the read command finish.

Here we are testing on asynchronous of the node.js. The sequence of code should not wait until we read the sample txt file. For that we are using callback function.

var file = require("fs");
console.log("Starting...");

file.readFile("./sample.txt",
       function (error,data){
           console.log("Contents" + data);
});
console.log("Keep going ...");

This will not wait until read the file So it will print the “Keep going” first . After that only it will return the text file content.

Express module in Node.js


Express is the high performance and high class web development module package for Node . Which will process on top of the HTTP module and call the http class. Therefore we can create website with less of an effort and clean.

To install express module,
npm install express in linux terminal.

use npm list command to check what are the module listed in your on your project. Check the update of the module because according to the update the class calling method can be vary. For example,

Express older version: var app = express.createServer();
Express newer version: var app = express();

So this kind of change mentioned in module doc.

Sample Code :

var file = require("fs");
var config = JSON.parse(file.readFileSync("config.json"));
var host = config.host;
var port = config.port;

//include the express module
var express = require('express');
var app = express();

//check the original route path
app.use(app.router);

//express the static file location (Say if we have our html file in public folder)
app.use(express.static(__dirname + "/public"));

app.get("/", function(request, response){
//Sending the response to client
response.send('hello world');
});

/*Any URl come with /hello/ then we can redirect to our public directory here we print the text which is continue with /hello/ */
app.get("/hello/:text",
   function(request,response){
       response.send("hello" + request.params.text);
   }
);
//file format similar to JSON format
var users = {
       "1" : {
               "name" : "user 1",
               "Social" : "user 1 link"
               },
       "2" : {
               "name" : "user 2",
               "Social" : "user 2 link"
               }
};

/*Getting the user by ID. Here we search in broweer as 127.1.1.1:1336/user/1 because our host is 127.1.1.1 and port is 1336*/
app.get("/user/:id",
   function(request,response){
       var user = users[request.params.id];
       if(user){
        response.send("<a href://faceboo.com>" + user.Social + "view me " + user.name+"</a>");
       }else{
           response.send("Sorry! User not found",404);
       }

   }
);


app.listen(port,host);

1)run the .js file using node extension
2) call the user id with hello/id

NOTE:config.json file contain the host and port address .see the doc