Interview Questions

Scripting

Angualr JS - AJAX Sample

<html>
   <head>
      <title>Angular JS Test</title>
     
      <style>
         table, th , td {
            border: 1px solid grey;
            border-collapse: collapse;
            padding: 5px;
         }
         
         table tr:nth-child(odd) {
            background-color: #f2f2f2;
         }
         
         table tr:nth-child(even) {
            background-color: #ffffff;
         }
      </style>
     
   </head>
   <body>
      <h2>AngularJS Sample Application</h2>
      <div ng-app = "" ng-controller = "currencyController">

DirtyDB -CRUD operations (coffeescript)

The following code performs basic CRUD operations in dirtyDB using coffeescript.

db.coffee

@db = require('dirty')('/tmp/test.dirty')

@db.on 'load', =>
   @entries = {}
   value = {eyes: 'blue'}
   @db.set "karthick",value
   @db.set "raju",value  
   #@entries[key]=value
   @db.forEach (key,value)  =>  
      console.log 'Found key: %s, val: %j', key, value
      @entries[key]=value
   key = "karthick"  
       
   console.log 'record get->',@db.get(key)  
   
   console.log 'remove record->',@db.rm(key)        
   

Google Go - Square Root

package main

import (
    "fmt"
)

func Sqrt(x float64) float64 {
   
    prev := 0.0
    i:=0.0
    for (i<10.0){
     
        if (x==(i*i)){
           return i  
        } else if((i*i) > x ){
           
            return prev;
        }    
        prev = i
        i++
    }
    return i
}

func main() {
    fmt.Println(Sqrt(25))
}

Underscore - Object Array to Map

Use the following code to convert an object array to Map using Underscore.js

var obj_map = _.object(_.map(objArray, function(item) {
                 return [item.id, item]
        }));

How to login in to linux without password using keys from windows?

Follow the steps below to login in to a linux machine from windows without a password
using public/privae keys.

1.) Download putty-gen.exe ( a tool which generates pubic/private key pairs).
2.) Generate a private/public key pair using putty-gen.
3.) Store the private/public keys in a separate files in a secure location .
4.) Login to the remote linux machine, create a file "authorized_keys" in ".ssh" directory.
5.) Copy the public key generated in step 2 in to the file authorize_keys.
6.) chmod 600 authorized_keys
7.) Logout from the remote machine.

BackboneJS - set http headers

Use the following code to set http headers with backbone's save, fetch and destroy methods.

model.save({ }, {beforeSend: sendHeader,
                                        success : function(data) {
                                             alert("success"); 
                                        },
                                        error : function(m, xhr, o) {
                                             alert("error");  
                                        }
                                });



sendHeader : function(xhr) {
                        xhr.setRequestHeader("name", "tdd");
                }

Python - TastyPie Create a Model Resource

The following is a sample code to create a ModelResource in TastyPie.

import copy
from tastypie.resources import ModelResource
from tastypie.authentication import Authentication
from tastypie.authorization import Authorization
from django.db import models

class DeviceResource(ModelResource):    
   
    class Meta:        
        queryset = Device.objects.all()      
        resource_name = 'device'
        excludes = ['pk']
        include_resource_uri = False
        always_return_data = True
        authentication = Authentication()

Python - Read Json Data from File

The following code is used to read json data from a file.

import json
with open('template.json', 'r') as json_file:
            jdata = json.dumps(json_file)
            print (jdata)

Python -Django Signal handlers

Use the following code to handle any events/signals in Django.

from django.db.models.signals import post_save
from django.dispatch import receiver
from myapp.models import Device

@receiver(post_save, sender=Device)
def my_handler(sender, **kwargs):
        print "myhandler"
        # your code for processing

In the above code , my_handler method handles post_save event/signal , which will be called whenever a save event is triggered in the Device model. Similarly other signals can be imported and specified in the @receiver annotation.

Python - Mysql DB connectivity Example

Use the following code to connect and fetch records to MysqlDB from Python

'''
Created on Aug 5, 2013

@author: Administrator
'''
from MySQLdb import *

class DAO(object):
    '''
    classdocs
    '''


    def __init__(self):
        print "hi"
       
    def dbAccess(self):
         db = connect("localhost", "root", "mysql", "techDB")
         cursor = db.cursor()
         cursor.execute("SELECT * from Student")
         row = cursor.fetchone()
         while row is not None:
              print(row)