Search

Content

Showing posts with label Interview Preparation. Show all posts
Showing posts with label Interview Preparation. Show all posts

Micro Services

How to create springboot app:

1.Using spring cli
2. https://start.spring.io/
3.Maven and dependencys




RestTemplate resttemplate = new RestTemplate();

resttemplate.getForObject(Stirng Url, Object out put Class);


Creating Bean in Spring boot


In Main method of spring

@SpringBootApplication
public  Main class{

@Bean
public RestTemplate getRestTemplate(){
    return new RestTemplate();
}

public void main method{
}


}

in Controller

@Autowired
RestTemplate reasttemplate;


resttemplate.getForObject()

Webclient vs Resttemplate

Webclint: Async requests
Resttemplate:  sync request


to handle web urls we have service discovery concept

client <----> service discovery <-----> service 1, service 2, service 3


download euraka server from start.spring.io.

and put dependency as Euraka Server

need to add below dependency for client and version


            <dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
and in properties add
            <spring-cloud.version>Greenwich.SR3</spring-cloud.version>


and add applicatoin name in application.properties.
spring.application.name=testapp


how to to discover the servec url

on @RestTemplate use  @LoadBalanced keyword and in the resttemplate url use application.name value to discover

Example
service application name->RBAC-SERVICE
resttemplate.getForObject("http://RBAC-SERVICE/getpermissions")








Expose localhost to the Internet with public URL

 

Signup at ngrok.com  and run the below command

Command: ngrok.exe http 8080


Collections


Collection:
A group of individual objects called as collection.

Why do we need collections in java?
               Array are not in dynamic nature. Once array size is defined we cannot modify the size and add the elements. A new array must be created with bigger sized and all the elements need to be copied to the new array.

Collection are used in situation where data is dynamic. Collection have default methods for search, sort…etc. so programmer no need to write functions.



Overview:
interface Collection<E> extends Iterable<E>{
}
interface List<E> extends Collection<E>{
//Only care about position of the object
//Elements can be added with specifying the index
//If position is not specified element will be added at the end of the list.
}
interface Set<E> extends Collections<E>{
               //Unique things only - No duplicates allowed
               //if obj.equals(obj2) than only one object will be available
}
interface Queue<E> extends Collection<E>{
               //Arranged in a order of processing
}
Interface Map<K,v>{
               //Contains key value pairs
               //things with unique keys.
}
What are the methods declared in Collection interface
interface Collection<E> extends Iterabale<E>{
boolean add (E e);
               boolean remove (Object o);

               int size();
               boolean isEmpty();
               void clear();

               boolean contains(Object o);
               boolean containsAll(Collection<?> c)

               boolean addAll(Collection<?> c)
               boolean removeAll(Collection<?> c)
               boolean retainAll(Collection c)
              
               Iterator<E> iterator();
}













Explain about List interface

Interface List<E> extends Collection<E>{
               boolean addAll(int position , Collection c)
              
               E get(int index)
               E set(int index, Object E)
              
               Void add(int position, Object E)
               E remove(int index)
               Int indexOf(Object O)
               Int lastIndexOf(Object o)
}

Class ArrayList   { /* implements List<E>, RandomAccess*/
//Implements RandomAccess, a market interface , means it supports faster fetching
//insertion and deletion is slower comparing to LinkedList
}
Class vector{/* implements List<E>, Random Access */
//Implements Random Access- a market interface, means its supports faster fetching
//Thread Safe – Synchronised
}
Class LinkedList{ /* Implements List<E>, Queue */
//Elements are doubly linked list – means forward and backwards – to one another
// Ideal choice to implement stack or queue
//Fast insertion and deletion
//Implements Queue interface so supports methods of pop, poll, remove
}



Interface Set<E> extends  Collection<E>{
//unique things only
//if obj1.equals(obj2) then only one object will be available in set
}
//maintains elements in sorted order
Interface SortedSet<E> extends collectin<E>{
SortedSet<E> subset(E fromElement, E toElement)
SortedSet<E> tailSet(E fromElement)
SortedSet<E> headset(E toElement)
E first()
E last()
}
Interface NavigableSet<E> extends SortedSet<E>{
E lower(E)
E floor(E)
E higher(E)
E ceiling(E)
E pollFirst()
E pollLast()
}
Class HashSet { /* implemnts set */
               //unorderd, unsorted – iteraterates in random order
               //uses hashCode
}
Class LinkedHashSet { /* Implemnts Set */
//order – iterates in insertion order
//unsorted
//uses hashCode
}
Class TreeSet{ /* implements navigableSet */
//sorted – natural order
//implements navigableset
}




Set/Hashset implementation:












Jira


1.      Why Jira?
               Jira is basically an issue & Project tracking toll which allows us to track any project related work by following proper workflow.
i)       1.able to track Project Progress
ii)      2.Users Project Management & bug Tracking feature implementation
2.      What is Referred as issues in Jira?
                              Any bug or Error
                              New Software Task
                              Resolving Ticket
                              Request processed from
3.      What type of charts we have in Jira?
                              Pie charts
                              Time Tracking
                              Resolution Time
                              User Work load
                              Resolved Vs Created Issues
4.      What does clining issue means?
It is the process of creating duplicate issue with original one in order to assign the issue to multiple users to resolve.
5.      How can you track time spent on issues ?
                              Blue Color           -              Estimated Time
                              Orange color      -              Remaining time to resolve
                              Green Color        -              Total Time to Resolve



Java Multi Threading

Java Multi Threading

1.Introduction
2.how many ways to define the thread
      by extending the thread class
      by implementing runnable interface
3. setting and getting name of threads
4.Thread priorites
5.the methods to prevent thread execution
     yield
     join
     sleep
6. Synchronization
7.Internal Thread Communication
8. Dead lock
9. Demon Threads
10.Multi Threading Enhancements


Multi Tasking
categorized into two types
   1.process based( where each task is different task and executed separately )
   2. Thread based( where single task is executed independently as process)

2. Defining a thread

We can define a thread 2 wasys.
1.by extending a thread the thread class.

     class mythread extends Thread{
        public void run(){
             sop ("child cthread")
        }
    }

p s v main(){
      mythred t = new mythread(); // instantiation 
     t.start(); // starting a thread


}

difference b/w t.start & t.run
t.start(): a seperated flow will be created.
t.run(): normal call as function

2.by implementing runnable interface.


Thread.start() internal implementation
1.thread schedular will register the thread
2. perferorm all other mandatory formalties
3.invoke run methdod






DOA Questions

  1. Reverse First K elements of Queue

put k elements in stack->s and poll the elements from queue->q.
take size of stack in variable size
add  stack elements into queue

public Queue<Integer> modifyQueue(Queue<Integer> q, int k)
    {
        Stack<Integer> stack = new Stack<>();
        int count = k;
        while (count > 0) {
            stack.push(q.poll());
            count--;
        }
        int size = q.size();
        while (!stack.empty()) {
            q.add(stack.pop());
        }
     
        while(size > 0) {
            q.add(q.poll());
            size--;
        }
     
        return q;
    }




GIT Source versioning System


Git:  Source versioning System

GitHub, Gitlab & Bitbucket are service providers for version Control

GitHub: Public and Open Source
GitLab: Private & to use for Organization

Git Commands:

Version: $git --version

Set User Name: $ git config --global user.name = "Lavakush"
Get User Name: $ git config --global user.name
Get all Global Config list:  $ git config --global --list
Check out Master: $ git checkout master
Pull latest changes: $ git pull origin master -u
Create Branch: $ git checkout -b "branch name"
Check the changes: $ git status
Add all files: $git add *
Store the changes : $ git commit -m "comment"
push the changes to remote repo: $ git push -u origin master



How GIT Works


  • Git is repository is a key-value object store all objects are indexed by SHA-1 hash value.
  • All commits & commented files different type of objects living in repository.
  • A git is large Hash table with no provision made for hash collection.
  • Git specifically works by taking shortstops of files 
LIST OF COMMANDS:-


1. Help
$ git help
2. Get help from help of config
$ git help config
3. Configure name
$ git config –global user.name= “Lavakush”
4. Configure email
$ git config –global user.email=Lokesh.nbp@gmail.com
5. Initiate git
$ git init
6. Add a file
$ git add filename.txt
7. To commit
$git commit -m “Comment”
8. To check the history of commits
$ git log
9. Different ways to add the add command and files
$ git add –all
$ git add “*.txt”
$ git add folder /
$ git add folder/*.txt
10. Check changes from last commit
$ git diff
11. To undo staging of the file add in staging
$ git reset head licence
12. Undo last commit & bring file to staging
$ git reset  -soft HEAD ^
13. Undo last commit & remove from staging
$ git rest -hard HEAD ^
14. To remove last 2 commits
$ git reset -hard HEAD ^^
15. REMOTE ADDRESS
$ git remote add origin “URL”
$ git push -u origin master
$ git clone URL

BRANCH

16. Create Branch
$ git branch testing
17. list all the branches
$ git branch
18. Check out a branch
$ git checkout testing
19. To merge testing branch with master
$git merge testing
20. Delete branch
$ git branch -d testing
21. PULL VS  FETCH
Git pull = Git Fetch + Git Merge

22. What is git Stash
If we are in middle of some task  and need to jump to another task we use stash
23. STAGING AREA OR INDEX
Is before competing the commits, it can formatted & reviewed in intermediate area known as Staging Area or Index

24. Git ARCHITECHTURE



Inter View Questions



  1. How many ways can we create object?
5 Ways we can create object in java
i)using new keyword
Test t = new Test();

ii) using clone method
Test t = new test();
Test t2  = (Test) t.clone();

iii)Class.ForName();
Class c = Class.forName("nameOfTheClass");
Test t = c.newInstance();

iv)Desensitization concept
FileInpputStream f =  new FileInputStream("filepath");
ObjectInputStream o = new ObjectInputStream(f);
Object o = (Test) o.readObject();

V) Using newInstance() method of constructor
Constroctor<Test> c =  Test.class.getDeclaredConstrocter();
Test t  = c.newInstance();

  1. Methods in object class?
  2. Implementation of contact list in mobile and searching algorithm?
  3. Which one is good to implement array list or HashMap and why?
  4. Write down deep cloning program.
  5. How to secure the RESTFUL webservices?
  6. Find the defect coin out of 72 coins in minimum steps using weighing scale.
  7. Write the program to find the max two product of a array with least time complexity. { 1,2,46,64,,43,3}  output-> 64*43.
  8. Write  a program to find the circular HashMap.
  9. How many ways we can send data from client?
  10. I want to send data as json format by GET request.How can I do?
  11. In how many ways I can send data in RESTFUL?
  12. How will u handle content of data send by client when u dony know which type of data client will send?
  13. I wanna build application without any xml file in spring fw ,how can I do?
  14. If I don’t wanna use xml then what are the ways to configure DispatcherServlet,Controller,HandlerMapping,View Reslver?
  15. What is path parameter & query parameter & matrix parameter?  If I wanna send 2 query parameter in same url on different path segment then how u will do?
  16.  
  17. How will u do form handling data in RESTFUL?
  18. Difference between spring 4 & 3
  19.  
  20. What is dfference between @Path ,@RequestMapping()?
  21. In RESTFUL IF I don’t wanna configure the ServletContainer in web.xml then what are the other options we can use?
  22. What is IOC container?
  23. What is setter &  constructor injection? How will u implement it in ur spring application?
  24.  
  25. Like RESTFUL we have @Path for handling the request ,if we create a servlet application then we can use @WebServlet for handling request uri,    so can I call servlet also as RESTFUL?
  26.  
  27. WHAT IS bean lifecycle?
  28. What is beanpostprocessor?
  29. What all types of hamdler mapping & use cases?
  30. What types ofview resolver, controller & use cases?
  31.  Spring mvc flow?
  32. How many approaches we have for using spring JDBC?
  33. HOW TO USE SPRING with Hibernate application?do spring provide hibernate related stuff for integrating it?
  34. Java 8 features?
  35. Concurrent collection?
  36. Executor framework?
  37. If I wanna use 2 databases at the same time in spring then what should I do?
  38. Difference between jdbc,hibernate?
  39. Pls write hibernate configuration file for MSSQL server database?
  40. What is DIALECT in hibernate?
  41. What is use of hbm2ddl.auto?
  42. What is SESSIONFACTORY in hibernate?
  43. How to use 2 database in hibernate in same congiguration? Is it possible? If not then how to implement it?
  44. If we don’t wanna configuration file in hibernate then how can we implwmnet hibernate ?
  45. What is mapping file in hibernate ?
  46. What are the annotation u used in hibernate ?
  47. What are inheritance mapping in hibernate?
  48. What is relationship in hibernate
  49. What is difference between get & load?
  50. Difference between save & persist?
  51. Difference between update & merge?
  52. What is criteria in hibernate?
  53. What is named query in hibernate?
  54. What is hql in hibernate ?
  55. Write hql for selecting all record from employee table
  56. Write hql for selecting id,name from employee table?

Algorithms for interview

>find number of given roman number?>Ex :XVI - 16, X1V - 14

solution:

function return_number($roman_char)
{
 switch($roman_char)
 {
 case 'I': return 1;beak;
 case 'V': return 5;break;
 case 'X': return 10;break;
 case 'L': return 50;beak;
 case 'C': return 100;beak;
 case 'D': return 500;break;
 case 'M' : return 1000;break;
 default:return 0; 
 }
}

function convertRomanToNumber($roman)
{
 $roman_arr = str_split($roman);
$sum = 0;
$prev = ;
for($i=count($roman_arr)-1;$i>=0;$i--)
{
  $current =  return_number($roman_arr[$i]);
  $sign = ($current<$prev?-1:1)
}
}

soap vs rest overview

Soap: simple object access protocol
Rest: Representational state transfer

1.soap is a protocol . rest is architechrial style.

2.soap cant use rest.  but rest can use soap webservices because it is concept of can use any protocols like http or soap.

3.soap uses interfaces to expose the business logic. but rest uses uri to expose business logic.

4.soap require more bandwidth comparing to rest.
 ex: <name>lokesh</name> vs "name": "lokesh"

5.soap uses xml data format. rest uses plain text, json, xml, html

6.soap is mainly used in banking projects. where as rest is used for public apis.



yii over view

1.what is yii?
yii is high performance component based 

java over view

What is Java?

Java is simple language
   easy to understand & based on c++
   Java removed many confusing & easrly used features.
            like:explicit pointers, operater overloading
   by default java provides Garbage collection automatically & memory management

Java is platform independent
Object oriented
Java is robust langulage: beacause it is used in consumer applicatoins, mission critical applications & navigation systems.


What is java Main method

public static void main (String[] args)

public-> so JVM can execute the method from anywhere
static-> method is to be called without object
void-> main method doesnt returns anything.
main()-> configured in JVM
String[]-> main method accepts a single arguments of an array of elements of type string.

System.out.println()

System->pre defined class
out->variable type output stream connected to console
println()-> method


is Main method is compulsory in Java?

<5 main method is not compulsory in java because static block was executed & doesnt need object to call method.

>=6 main method is compulsory .
     compilation is successful but we will get run time error as
"Erro main method not found in class test. Please define the main method as public static vooid main(String[] args)"

normal Interview Questions and answers

>write a program to check wheather given string is a plindrome or not?
ex: maaM -->true

code:

public class program{

public static void main(String... args)
{

System.out.println(isPalindrome(""Maam)) ;
}
 public boolean isPalindrome(String word)
  {
    word = word.toLowerCase();
    boolean result = false;
    String myword = "";
    for(int i = word.lenght()-1;i>=0;i--)
         {

             myword = myword + word.charAt(i);
          }

 if(word.equals(myword)
{ result = true;}
return result;
 }
}






Question:
User interface contains two types of user input controls: TextInput, which accepts all characters and NumericInput, which accepts only digits.
Implement the class TextInput that contains:
  • Public method void add(char c) - adds the given character to the current value
  • Public method String getValue() - returns the current value
Implement the class NumericInput that:
  • Inherits TextInput
  • Overrides the add method so that each non-numeric character is ignored
For example, the following code should output "10":
TextInput input = new NumericInput();
input.add('1');
input.add('a');
input.add('0');
System.out.println(input.getValue());
Answer:
class TextInput {
     String input = "";
     String output = "";
    public void add(char ch)
    {
        this.input = this.input+ch;
    }
    public String getValue(){
       
        return this.input;
   
    }
   
}

class NumericInput extends TextInput {
    public void add(char ch)
    {
       
        if(Character.isDigit(ch))
        {
            super.input = super.input + ch;
        }
    }
   
}

public class UserInput {
    public static void main(String[] args) {
        TextInput input = new NumericInput();
        input.add('1');
        input.add('a');
        input.add('0');
        input.add('0');
        input.add('h');
        System.out.println(input.getValue());
    }
}

Write a function that, given a list and a target sum, returns zero-based indices of any two distinct elements whose sum is equal to the target sum. If there are no such elements, the function should return null.
For example, findTwoSum(new int[] { 1, 3, 5, 7, 9 }, 12) should return any of the following tuples of indices:
  • 1, 4 (3 + 9 = 12)
  • 2, 3 (5 + 7 = 12)
  • 3, 2 (7 + 5 = 12)
  • 4, 1 (9 + 3 = 12)
answer
public class TwoSum {
    public static int[] findTwoSum(int[] list, int sum) {
        for(int i=0;i<list.length-1;i++)
        {
            for(int j=i+1;j<list.length;j++)
            {
                //System.out.println(i + " " +j);
                if(list[i]+list[j] == sum)
                {
                    return new int[] {i,j};
                }
            }
            //System.out.println(list[i]);
        }
        return new int[]{0,0};
    }

    public static void main(String[] args) {
        int[] indices = findTwoSum(new int[] { 1, 3, 5, 7, 9 }, 12);
        System.out.println(indices[0] + " " + indices[1]);
    }
}

Android over view

>what is android?
android is mobile plotform consist of operating system, middleware, key apps.

>what is os?
os is a abstraction b/w software and hardware.

>architecture of android?
key applications:[ developed in java, c++, .net] now only support for java
Middle ware :[ native library open gl], [ java.io, javanet,dvm(.class<>dex)]
Operating System: [memory management, power management, Driver management, Resource management]

>life cycle of an android?


                 [ 1.Doesnot Exist ]
  onDestroy                            onCreate
  onStop                                  onStart
  onPause                                onResume


                [ 2. Fore Ground  ]                --->onPause    
                                                                                   [ 3. Pause ]
                                                               <----- onResume

    onResume                                        
    onStart                                 onPause
    onRestart                             onStop
                [ 4. Background ]


>how to get IMEI number in android?
TelephonyManager mTelephonyManager = (TelephonyManager)
            getSystemService(Context.Telephony_Service);
Stirng st = mTelephonyManager.getDeviceId();

>how to call a new Intent in android?
    StartActivity(new Intent(this, subactivity.class).putExtra("key","value");
    to get intent values
   Intent it=  getIntent();
   it.getString("key")

>what are the major components in android?
1.Activity
2.Service
3.Broadcatst Receiver
4.Content Provider

1.activity:
  Every screen with ui component user will interect is called as an activity.
                       javacode
         actvity
                     xml
2. service:
A long running process without user interaction is called as service.
example: wifi avalibile if some wifi is there, media player, network status

3.Broadcast Receiver
 broadcast receiver is registered for system announcemnt
Example: headset plungin, charger connected/disconnected, power button pressed

4.Content Provider:
used to share data b/w applications
Example : whatapp is getting contacts from contacts application.

>how to define string or string array in values.xml
<string name="key">value</stirng>
<string-array name="key">
     <item>value</item>
</stirng-array>

>what is difference b/w dp, dip, px, sp?
dp / dip: density independent pixels
sp: scale independent pixels
      it is scaled by user font size preference

>what is uuid in android?
universally unique identifier standardised 128bit string for Bluetooth service.

>what are the different android storages?

1.sharedpreferences
2.internal storage
3.external storage
4.sqlite
3.webservices to cloud

1. sharedpreferences:
sharedpreferences pref;
SharedPreferences.Editor editor ;
pref =  getApplicationContext().getSharedPreferences("name", MODE PRIVATE);
editor = pref.edit();

set items:
 editor.putString("name", "Elena");
 editor.putInt("idName", 12);
 editor.commit();

get the data:
String id= pref.getString("Key", null);

remove data
pref.remove("key");
pref.commit();

clear shared preference
pref.clear();
pref.commit();

>how to know wheter out listview is end?
 boolean userscrolled= false;
listview.setOnscrollListenet(new onScrollListener(){
   public void onScrollStateChanged(AbsListview view,int scrollstate)
     {
        if(scrollstate==OnScrollListener.SCROLL_STATE_TOUCH_SCROLL)
           {
              userScrolled = true;
            }
      }
    public void onScroll(AbsListView view, int fistVisibleItem, int visibleItemCount, int totalItemCount)
             {
               if(userscrool==true && fistVistiblecount+ totalVisiblecount == totalItemCount)
                       {
                                 //  end of listview
                        }     
              }
}


>what is intent?
intent is used to invoke antother actitiy

>what is d/w imlicet intent and explicit intent?
 implecent intent: used to invoke system components
 example: send message email
 Explicit intent: used to invoke user defined activity.

>what is a fragment?
 fragment is used to show mutiple view in a single activity.






jquer over view

JQUERY is "write less do more" javascript library

basic syntax $(selector).action();
class->.
id->#

button click

$(document).ready(function(){

 $("button").onclick(function(){
          //operations
     });
});

jquery effects:

hide() / show() / toggle()

jqery fade
fadein
fadeout
fadeToggle
fadeTo (slow | fast | milliseconds, opacity 0-1 )

Jquery Slide
slideUp
slideDown
slideToggle

javascript callable function
 $("button").click(function(){

$("p"),hide(''slow',function(){
alert("hide sucessfully");
})
});

javascript chaining:
$("button").css('color','red').slideUp(100).slideDown(200)


jqery Add
append()
preappend()
after()
before()

jqery remove
div.remove() ->remove elemnt
div.empty() -> empty chile elements

get and set css classes
addClass()
removeClass()
toggleClass()

javascript over view

change html using javascrip
  document.getElementById("id").innserHTML = "html"
change html attributes using javasctip.
   documnet.getElementById("id").src= "src"
change html style
   doucument.getEelemnntById("id").style.fontsize ="12px"
                                                            .style.display = "none"
                                                            .style.display = "block"
javascript posibilities
1.alert
2.console
3.document.wirte
4.innerHTML

javascript bitwise operators

1.& (and)
2.| (or)
3.^ (xor)
4.<< (zero fill left shift)
5.>>(zero fill right sift)


javascript evalute expression (javascript evaluate expression form left to right)
var x = 5+"me" //output = 5me
var x = 5+5+"me" output = 10me
var x = "me"+5+5 output = me55

null vs undefined
type object - type undefined

null === undefineed //false
null == undefined //true

javascript events
1.onclick
2.onchnage
3.onMouseover
4.onMouseOut
5.onKeydown
6.onLoad

javascript strings
string.lenght
string.toUpperCase();
string.toLowwerCase();


Method used to debug
Console.log();

To Sennd Data to server
var myobj = {'key': 'value', 'Key1': "value2"}
to send server = var myobj = JSON.stringify(myobj)
to receive -> JSON.parse(myobj)
to get values -> myobj.name

storage in javascript
 localStorage.setItem(key,value)
localStorage.getItem(key)



javascript Ajax

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystateChange = function(){
                                if(this.readyState == 4 && this.status ==200)
                                  {
                                        //do operations
                                      }
                                  }
xmlhttp.open(get/post,url,true)
xmlhttp.send()


testdome questions

>Function appendChildren should add a new child div to each existing div. New divs should be decorated by calling decorateDiv.
<div id="a">
    <div id="b">
    </div>
  </div>
 
solution:
function appendChildren() {
  var allDivs = document.getElementsByTagName("div");

  for (var i = 0; i < allDivs.length; i++) {
    var newDiv = document.createElement("div");
    decorateDiv(newDiv);
    allDivs[i].appendChild(newDiv);
  }
}

// Mock of decorateDiv function for testing purposes
function decorateDiv(div) {}
 
> Fix the bugs in the registerHandlers function. An alert should display anchor's zero-based index within a document instead of following the link.
For example, in the document below, the alert should display "2" when Google anchor is clicked since it is the third anchor element in the document and its zero-based index is 2.
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Test page</title>
  </head>
  <body>
    In my life, I used the following web search engines:<br/>
    <a href="//www.yahoo.com">Yahoo!</a><br/>
    <a href="//www.altavista.com">AltaVista</a><br/>
    <a href="//www.google.com">Google</a><br/>
  </body>
</html>
 
solution:
function registerHandlers() {
  var as = document.getElementsByTagName('a');
  for (var i = 0; i < as.length; i++) {
    as[i].onclick =  (function(i){return function(){alert(i); return false;}}(i))
      
  }
}
 
 
> With the new HTML5 features, modify the form so that:
  • The formula input field has an autocomplete option with the following options: "sin", "cos", "tan" and "cot".
  • The iterations input field is a slider with possible values from 1 to 10.
  • The precision input field is a number picker with possible values from 1 to 100, where 50 is the default value.
solution:
Formula:
      <datalist id="op">
        <option value="sin">
          <option value="cos">
            <option value="tan">
              <option value="cot">
      </datalist>
      <input name="formula" list="op">
      <br /> Iterations:
      <input name="iterations" type="range" min="1" max="10" step="1" />
      <br /> Precision:
      <input name="precision" type="number" min="1" max="100" value="50" />
      <br />
 
 
 
 








php over view

PHP - Hyper Text Pre Processer

php is loosily coupled language.[We dont have to tell data type]

Global Keyword:
   global x; or global['x']

Echo: will accepct multiple argument, No return Value
Print : Single Argument, Returns 1

Php Data Types:

1.String
2.Integer
3.Boolean
4.Float
5.Array
6.Null
6.Resources
7.Object [ $parent =  new parent();]


Php String Functions:
1.srtlen() [No of characters]
2.str_word_count() [returns no of words]
3.strrev() [Reverse the given stirng]
4.strpos() [Return the position of the stirng] ex strpos("hello world", "world") 6
5.str_replace(find,replace,string)

Define a constant
define(name,value,true/false) [true/false=case sensitive or not default false]

Php Arrays 3 Types
1.Index arrays: [ $arr = array(1,2,3,45,)]
2.Associative arrays: [$arr= array(1=>a,2=>b]
3.Multidimensional arrays: [$arr= array(array(1,2),array(3,4)]

 Php array sort Functions
sort() [acending order]
rsort() [deceinding order]

asort() av [acending value]
ksort() ak [acending key]
arsort() dv [desending value]
krsort() dk [descending key]


Php date and time

date("yyyy/mm/dd h:i:s:a")


Php INCLUDE vs REQUIRE

include:  [warning and continue]
require: [error and stop]

FILE upload:
move_uploaded_file(temppath,targetpath)

COOKIE:
setCookie(name,value,time()+86400*30,"/")

SESSION
session_start()
$_session['name'] = "value"
session_unset()
session_destroy()

php super globlas

$_post
$_get
$_request
$_files
$_session
$_cookie
$_server

ISSSET vs empty

isset [value must be something other than null]
empty[ returns true is it is]


MYSQL CONNECT
mysql_connect(host,username,password)
mysql_select_db(database)


PHP MAGIC METHODS(15 magic methods are ther in php)
1.__construct
2.__destruct
3.__set
4.__get
5.__call
6.callStatic
Programmer no need to call the magic methods that is the reason we call them as magic methods.

__construct , __destruct

__construct:
if php 5 cannot find __construct function then it will search for the method with same name and executes.when object of the class has been created.

__construct called when creation of object. and destruct called when deletion of object
class a
{
   function __construct()
   {
       echo "constructer called"
     }
   function __destructer()
 {
    echo "destrucred called."
   }
}

$aobj = new a(); //constructer is called here.

unset($aobj) // destructer is called


__set //used to set value or property which is not acessible form a class
 __get //used to get value or property which is not acessible from a class
 __call //used to call method which is inacessible or unavalibale
__callStatic //used to call static method which is inaceeble or unavilable


__toString//used to print object values directrly


__isSet //this function is triggerd when isset function is applied on uavalibe property class
__unset //this function is excatly opposite to isset called when unset function to on unavaliable propery in class


__sleep //called when used to seriliaze class object
__wakup //called when used to unserilze class object

__invoke //used to


test dome questions and answers
A thesaurus contains words and synonyms for each word. Below is an example of a data structure that defines a thesaurus:
array("buy" => array("purchase"), "big" => array("great", "large"))
Implement the function getSynonyms, which accepts a word as a string and returns all synonyms for that word in JSON format, as in the example below.
For example, the call $thesaurus->getSynonyms("big") should return:
'{"word":"big","synonyms":["great", "large"]}'
while a call with a word that doesn't have synonyms, like $thesaurus->getSynonyms("agelast") should return:
'{"word":"agelast","synonyms":[]}'
 
solution:
 
<?php
class Thesaurus
{
    private $thesaurus;

    function Thesaurus($thesaurus)
    {
        $this->thesaurus = $thesaurus;
    }

    public function getSynonyms($word)
    {
        $ret=array();
        foreach($this->thesaurus as $key=>$value)
        {
   if($key==$word)
   {
    $myjson = array(
    "word"=>$word,
    "synonyms"=>$value
    );
                $ret = array_merge($ret,$myjson);
   }
            
        }
  if(count($ret)>0)
  {
    return json_encode($ret);
  }
  else
  {
  $myjson = array(
    "word"=>$word,
    "synonyms"=>array(),
    );
   return json_encode($myjson);
  }
    }
}

$thesaurus = new Thesaurus(
    array 
        (
            "buy" => array("purchase"),
            "big" => array("great", "large")
        )); 

//echo $thesaurus->getSynonyms("big");
//echo "\n";
echo $thesaurus->getSynonyms("sadf");
 
 
 









Mysql Over View

DDL: Data defination Language
create  create tabel table_name(column_name data_type(size))
alter   alter table add,modify,drop
delete  delete table table_name
drop    drop table table_name || drop view view_naem
rename  rename table tabele_name to new_table_name
turncte truncate table table_name (removed and saved in hd:: no roll back)

DML: Data Manipulation Language
insert insert into table_name(values...)
update update table set old_value=new_value
delete delete from table_name(can roll back)
merge 

DQL: Data Query Language
select select * from table_name

TCL: Transcation Control Language
rolback
commit

DCL: Data Control Language
grant
revoke

Constrains in Mysql:
1.Primary Key :
column level: [ Create table table_name( column_name datatype(size) primary key )]
table_level(also called as composite key)
                       [Create table table_name(columns_names...,primary key(column_names,..)]
2.Foreign Key
colum_level: [Create table tablename (column_name datatype(size) references table_name(column_name)]

table_level: [Create table table_name(columns..., foreign key(col1,col2) references table_name(column_name)]
table_level:
3.Not null only applyed on colum level
4.Unique: can have null but no duplicates
5.Check

Operators in Msql:

1.Arthemetic Operators : [+, - ,/, *, mod(a,b)]
2.Relational Operators:    [=, >, <, !=]
3.Logical Operators:        [and, or, not]
4.Special Operators:        [in | not in, between | not between, not null | is not null, like | not like]


Functions in Mysql:
 1.Number Functions:    [abs(), mod(m,n), round(column), ceil(column), floor(column)]
2.Character Functions:  [ ]
3.Date Functions

Group Functions in mysql:

1.max()
2.min()
3.avg()
4.sum()
5.count()

Joins:
 1.Inner Join [ Return rows when there is match two tables]
2.Left Join / Left outer Join   [Return all rows from left table]
3.Right Join / Right outer Join [Return all rows from right table]
4.Self Join  [Used to join table it self. Must use alias for at least one table]

Mysql Union
1.union: select without duplicates 
              [Select * from table1
               union
                select * from table2
              ]
2.union all :with duplicates

              [Select * from table1
               union all
                select * from table2
              ]



 Mysql query Examples:

1.select first 3 characters of column (mysql position starts from 1. in oracle and sql it starts form 0
> select substring(columnname,1,5) from emp
2.get position of a character in column
>slect locate('charachter',column name) from emp
3.get lenght of the column character
>SELECT LENGTH(NAME) FROM emp
4.Get First_Name from employee table after replacing 'o' with '$'
 >select REPLACE(FIRST_NAME,'o','$') from employee

5.select name and first name in single column

>SELECT CONCAT(id,NAME) FROM emp

6.Select year month and date from a table

>select year(date), date(date), month(date)

7.select employee whose joing date is 2013

>select * from emp where year(joiningdate)='2013'

8.get joining date and time

>slect * from convert(date_format(joining_date,'yyyy-mm-dd hh:mm:ss:ff' ff= milliseconds 

9.get database date

>slect now()
"Top N Salary" SQL Interview Questions and Answers

10.Select TOP 2 salary from employee table
>select * from employee order by salary desc limit 2
11.Select TOP N salary from employee table
>select * from employee order by salary desc limit N
12.Select 2nd Highest salary from employee table
>select min(SALARY) from (select * from employee order by salary desc limit 2)   
 13.Select Nth Highest salary from employee table
>select min(SALARY) from (select * from employee order by salary desc limit N)


Views:

View is a database object which is used to provide authority level of Security. Generally views doesnot store any data
view are 2 types
1.single view
2.complex view


ex: CREATE VIEW v1 AS SELECT * FROM emp


>how to load data into  table using mysql

load data loacal infile = "c:\\desktop\\file.txt"
into table table_name
fields terminated by ","
lines terminated by "\n"
(field1,field2....)

local is used if we trying to insert from user to remote system


>difference between union and join.
union place the records in one column of two table records one after another
example
table 1:
a
b
c
table 2:
d
e
f
union: 
select colum_name from table_1 
union
select colum_name from table_2
result: will be placed in single column
a
b
c
d
e
f

>types of indexs:
index is one of the essintial feature of the mysql wi
 indexes store data in logcally sorted manner to improve search performance.
 indexes decrease write performance





Some useful Mysql commands


1. Select and insert to antohter table.

INSERT INTO wp_posts_main (
post_author,
post_date,post_date_gmt,
post_content,post_title,
post_excerpt,post_status,
comment_status,ping_status,
post_password,post_name,
to_ping,pinged,post_modified,
post_modified_gmt,post_content_filtered,
post_parent,guid,menu_order,
post_type,post_mime_type,
comment_count     
      )
SELECT
post_author,
post_date,post_date_gmt,
post_content,post_title,
post_excerpt,post_status,
comment_status,ping_status,
post_password,post_name,
to_ping,pinged,post_modified,
post_modified_gmt,post_content_filtered,
post_parent,guid,menu_order,
post_type,post_mime_type,
comment_count
FROM wp_posts

2. finding duplicate content in a table.

SELECT post_title,post_content, COUNT(*) AS COUNT
FROM wp_posts_main
GROUP BY post_content,post_title
HAVING COUNT(*) > 1

3.Update all columns with row id for all rows.


UPDATE wp_posts_final t, (SELECT DISTINCT ID
                        FROM wp_posts_final) t1
   SET t.guid = CONCAT("http://www.1947.com/?p=", t1.ID)
 WHERE t.ID = t1.ID