Showing posts with label Interview Questions and Answers. Show all posts
Showing posts with label Interview Questions and Answers. Show all posts

Monday 21 June 2021

Kafka Interview Questions and Answers

Kafka Interview Questions and Answers

Question: What is Apache Kafka?
Apache Kafka is a open source framework written in Scala and Java which is used for distributed streaming platform.


Question: What are components of Kafka?
  1. Producer –Producers are responsible for sending the data to Kafka topic.
  2. Consumer –Consumers are subscribers to a topic and also reads and processes from the topic.
  3. Topic –It is name of Group where producer send the messages and consumer receive the messages.
  4. Brokers – We use broker to manage storage of messages in the topic .
  5. ZooKeeper - ZooKeeper is used to coordinate the brokers/cluster topology.



Question: Explain the role of the offset.
There is a sequential ID number given to the messages in the partitions that called offset.
It is used identify each message in the partition uniquely.


Question: What is a Consumer Group?
Kafka consumer group consists of one or more consumers that jointly consume a set of subscribed topics.


Question: What is the role of the ZooKeeper?
Apache Kafka is a distributed system is built to use Zookeeper.
Zookeeper’s main role here is to coordinate the brokers/cluster topology.
It also uses to recover from previously committed offset if any node fails because it works as periodically commit offset.



Question: What is Partition in Kafka?
In every Kafka broker, there are few partitions available, and each partition in Kafka can be either a leader or a replica of a topic. 



Question: What are advantage of kafka?
  1. High-throughput
  2. Low Latency
  3. Fault-Tolerant
  4. Durability
  5. Scalability


Question: What are main APIs of Kafka?

  1. Producer API
  2. Consumer API
  3. Streams API
  4. Connector API


Question: What are consumers?

Kafka Consumer subscribes to a topic, and also reads and processes messages from the topic. 



Question: Explain the concept of Leader and Follower?
There is one server which acts as the Leader, and Other servers plays the role as a Followers. 



Question: What ensures load balancing of the server in Kafka?
Main role of the Leader is to perform the task of all read and write requests for the partition, whereas Followers passively replicate the leader. At the time of Leader failing, one of the Followers takeover the role of the Leader. 



Question: Why are Replications critical in Kafka?
Replications make sure that published messages are not lost and can be consumed in the event of any machine error, program error or frequent software upgrades. 


Question: In the Producer, when does QueueFullException occur?
Kafka Producer attempts to send messages at a pace that the Broker cannot handle at that time QueueFullException typically occurs. 



Question: What is the purpose of retention period in Kafka cluster
Retention period retains all the published records within the Kafka cluster but It doesn’t check whether they have been consumed or not. We can also update the Retention period through configuration. 


Question: What is Maximum size of a message that can be received by the Kafka?
1000000 bytes 


Question: Explain Multi-tenancy?
We can enable the Multi-tenancy is enabled, We can easily deploy Kafka as a multi-tenant solution. However, by configuring which topics can produce or consume data 


Question: What is Streams API?
Streams API permits an application to act as a stream processor, and also consuming an input stream and producing an output stream to output topics. 



  Question: What is Connector API?
Connector API permits to run as well as build the reusable producers or consumers which connect Kafka topics to existing applications. 


Question: What are top companies which uses of Kafka?
Netflix
Mozilla
Oracle
etc


Sunday 28 March 2021

Graphql basic example with code snippet

Graphql basic example with code snippet
Question: What is GraphQL?
GraphQL is a query language for API, and it is server-side runtime for executing queries by using a type system you define in server.


Question: What is GraphQL used for?
Load data from a server to a client (API)


Is GraphQL a REST API?
GraphQL follows the same set of constraints as REST APIs, but it organizes data into a graph. GraphQL can speed up development and automation in comparison to REST API.


Is GraphQL frontend or backend?
Its neither frontend or backend. Its language to exchange the data between client and server.


Does Facebook use GraphQL?
Facebook used GraphQL since 2012.


Who uses GraphQL?
Facebook. Instagram. Shopify. Twitter. StackShare. Stack. The New York Times. Tokopedia. etc


GraphQL Example 1 with Node
var { graphql, buildSchema } = require('graphql');

var schema = buildSchema(`
  type Query {
    name: String,
    age: String,
  }
`);

var root = { name: () => 'My Name is Arun kumar.', age: ()=> '20 Year' };

graphql(schema, '{name}', root).then((response) => {
  console.log(response);
});



GraphQL Example 2 with Node
var { graphql, buildSchema } = require('graphql');

var schema = buildSchema(`
  type Query {
    name: String,
    age: String,
  }
`);

var root = { name: () => 'My Name is Arun kumar.', age: ()=> '20 Year' };

graphql(schema, '{name,age}', root).then((response) => {
  console.log(response);
});



GraphQL Example 3 with Node
var { graphql, buildSchema } = require('graphql');

var schema = buildSchema(`
  type Query {
    name: String,
    age: String,
    address: String,
  }
`);

var root = { name: () => 'My Name is Arun kumar.', age: ()=> '20 Year', address: ()=>'#238, Palm city, Sector 127, kharar'};

graphql(schema, '{name,age,address}', root).then((response) => {
  console.log(response);
});



GraphQL Example 4 with Node
const express = require('express');
const { ApolloServer, gql } = require('apollo-server-express');

const typeDefs = gql`
  type Query {
    hello: String,
    name: String,
    age: String,
    address: String,
    city: String,
  }
`;


const resolvers = {
  Query: {
    hello: () => 'Hello world!',
    name: () => 'My Name is Arun kumar.',
    age: ()=> '20 Year',
    address: ()=>' Sector 127, mohali',
    city:()=> 'kharar'
  },
};

const server = new ApolloServer({ typeDefs, resolvers });

const app = express();
server.applyMiddleware({ app });

app.listen({ port: 4000 }, () =>
  console.log('Now browse to http://localhost:4000' + server.graphqlPath)
);




GraphQL Example 5 with Node
var express = require('express');
var { graphqlHTTP } = require('express-graphql');
var { buildSchema } = require('graphql');

var schema = buildSchema(`
  type Query {
    hello: String,
    name: String,
    age: String,
    address: String,
    city: String,
  }
`);

var root = {
  hello: () => 'Hello world!',
  name: () => 'My Name is Arun kumar.',
  age: ()=> '20 Year',
  address: ()=>' My city, Sector 127',
  city:()=> 'kharar'
};

var app = express();
app.use('/graphql', graphqlHTTP({
  schema: schema,
  rootValue: root,
  graphiql: true,
}));
app.listen(4000, () => console.log('Now browse to localhost:4000/graphql'))





Thursday 23 July 2020

Python Interview Questions and Answers for Freshers

Python Interview Questions and Answers for Freshers

Question: What is current Stable version of Python?

Version: 3.5.1 Dated: 7 December 2015


Question: What is Filename extension of Python?
py, .pyc, .pyd, .pyo, pyw, .pyz


Question: What is offical website of Python?
www.python.org


Question: What is the difference between deep copy and shallow copy?
  1. Shallow copy is used when a new instance type gets created and it keeps the values that are copied.
    Deep copy is used to store the values that are already copied.
  2. Shallow copy is used to copy the reference pointers just like it copies the values.
  3. Shallow copy allows faster execution of the program whereas deep copy makes slow.

Question: How to use ternary operators?
[on_true] if [expression] else [on_false]
x, y = 25, 50
big = x if x < y else y



Question: What are different data-type in Python?
  1. Numbers
  2. Strings
  3. Strings
  4. List
  5. Dictionaries
  6. Sets



Question: What is module in python?
Module is set of related functionalities. Each python program file is a module, which imports other modules to use names they define using object.attribute notation.


Question: What is lambda in python?
lamda is a single expression anonymous function often used as inline function.


Question: How to validate Email Address in python?
re.search(r"[0-9a-zA-Z.]+@[a-zA-Z]+\.(com|co\.in)$","myemail@domain.com")



Question: What is pass in Python?
pass is no-operation Python statement and used to indicate nothing to be done.

Question: What is iterators?
iterators is used iterate over a group of elements, containers, like list


Question: What is slicing in Python?
Slicing is a mechanism to select a range of items from Sequence types like strings, list, tuple, etc.


Question: What is docstring in Python?
Python documentation string is a way of documenting Python modules, functions, classes. PEP 257 standardize the high-level structure of docstrings.


Question: Name few modules that are included in python by default?
  1. datetime
  2. re (regular expressions)
  3. string
  4. itertools
  5. ctypes
  6. email
  7. xml
  8. logging
  9. os
  10. subprocess


Question: What is list comprehension?
Creating a list by doing some operation over data that can be accessed using an iterator.
>>>[ord(i) for i in string.ascii_uppercase]
     [65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90]
 >>>



Question: What is map?
MAP executes the function given as the first argument on all the elements of the iterable given as the second argument.


Question: What is the difference between a tuple and a list?
A tuple is immutable i.e. can not be changed. It can be operated on only.
List is mutable. Changes can be done internally to it.


Question: How to Remove white spaces from string?
filter(lambda x: x != ' ', s)




Question: What are metaclasses in Python?
A metaclass is the class of a class.
A class defines how an instance of the class (i.e. object) behaves while a metaclass defines how a class behaves. A class is an instance of a metaclass.



Question: How do I check whether a file exists without exceptions?
os.path.isfile("/etc/password.txt");//true




Question: How to call an external command?
import subprocess
subprocess.run(["ls", "-l"])

Monday 21 October 2019

Symfony2 Interview Questions and Answers for Beginners

Symfony2 Interview Questions and Answers for Beginners

Question: What is Symfony?
Symfony is a PHP web application framework for MVC applications.


Question: Is Symfony Open Source?
Yes, It is Open Source.


Question: What is current Stable version of Symfony?
Version: 5.0.4, Dated: 31 Jan 2020


Question: What is offical website of Symfony?
symfony.com


Question: What is minimum PHP Version requirement for Symfony?
PHP 7.2.5


Question: What are benefits of Symfony?
  1. Fast development
  2. MVC Pattern
  3. Unlimited flexibility
  4. Expandable
  5. Stable and sustainable
  6. Ease of use.



Question: How to concatenate strings in twig?
{{ 'http://' ~ app.request.host }}



Question: How to get current route in Symfony 2?
$request = $this->container->get('request');
$currentRouteName = $request->get('_route');



Question: How to render a DateTime object in a Twig template?
{{ game.gameDate|date('Y-m-d') }}



Question: How to var_dump variables in twig templates?
{{ dump(user) }}



Question: How to get the request parameters in symfony2?
$name=$request->query->get('name');



Question: How to get list of all installed packages in composer?
composer global show


Saturday 5 October 2019

FuelPHP Interview Questions and Answers for Beginners

FuelPHP Interview Questions and Answers for Beginners

Question: What is FuelPHP?
FuelPHP is PHP Framework written in PHP, based on the HMVC pattern.


Question: Is FuelPHP Open Source?
Yes, It is Open Source.


Question: What is minimum PHP Version required for FulePHP?
PHP 5.4+


Question: Is FulePHP support Multilingual?
Yes, It support Multilingual.


Question: What is offical website of FulePHP?
fuelphp.com


Question: What are Key Features of FuelPHP?
  1. URL routing system
  2. RESTful implementation
  3. HMVC implementation
  4. Form Data validation
  5. ORM (Object Relational Mapper)
  6. Vulnerability protections like XSS, CSRF, SQL Protection and encode output.
  7. Caching System



Question: What is full form of HMVC?
Hierarchical-Model-View-Controller


Question: What is HMVC?
HMVC is an evolution of the MVC pattern.


Question: What are benefits of HMVC?
  1. Modularization
  2. Organization
  3. Reusability
  4. Extendibility



Question: How to get Query in FulePHP?
$userQueryToExecute = Model_Article::query()
        ->select('users')        
        ->where('blocked', '=', 1);

echo $userQueryToExecute->get_query();



Question: How to check that Redis server is running?
try
{
    $redis = \Redis::instance();    
}
catch(\RedisException $e)
{
    //here error will come
}



Question: How to use join with condition?
$queryObj = \Services\Model_Org::query()
->related('org')
->related('profile_image')->related( array(  'comments' => array(   'where' => array(    array('visible' , '=' , '0')   )
  ) ))
->where('rating','!=', 'null')
->order_by('rating','desc')
->get();


Wednesday 25 July 2018

AWS interview questions and answers for 1 year experienced

AWS interview questions and answers for 1 year experienced

Question: What is the difference between Amazon S3 and Amazon EC2 instance?
Amazon S3: It is just storage service where you can upload photo, video, audio, pdf etc any type of files upto 5 terabytes (5Tb).
It store data as a object, you can't install any software like MS office, VLC player, Adobe etc.

You can import/export data from/to S3 and also can access via cloudfront.

EC2 instance: Launching a EC2 instance is similar a create virtual computer (windows, linux) where you can install software unlike S3. You can customize the configuration like volume(storage), RAM, CPU etc.


Question: How to copy files from one bucket to another?
  1. Login to SSH using ip address and ppk file.
  2. Make sure, it have AWS S3 access privilege
  3. Now just execute following command
    aws s3 sync s3://source-bucket s3://destination-bucket --exclude *.tmp
    



Question: Can we change the availability zone of an existing EC2 t1.micro instance?
No, you can not do.
for this, you need to launch new instance from existing instance.



Question: What is Availability Zones?
Amazon EC2 is hosted in world-wide.
These locations are composed of regions and Availability Zones.
Each region has multiple, isolated locations known as Availability Zones.


Question: How to move files directly from one S3 account to another?
Bucket Explorer works on Mac
S3 Browser works on windows.



Question: AWS Difference between a snapshot and AMI?
A snapshot is of an EBS volume where you save at a certain point of time.
An AMI is similar, but its for the EC2 instances themselves. you can create a AMI but can't do snapshot.


Question: What is the maximum length of a filename in S3?
1024 characters.



Question: How to move a domain from Godaddy to AWS Route 53? =>Login on your aws console
=>Click on Route 53
=>Create Hosted Zone
=>Select your new created host title
=>click "Go to Record Sets", take note of the nameservers;

=>Login on your Godaddy account
=>Select your domain
=>Go to Nameservers and click SetNameservers;
=>paste all the four you took from Go to Record Sets;


Question: How to transfer files between from AWS ec2 to S3
aws s3 cp myfolder s3://mybucket/myfolder --recursive



Question: How to transfer files between from S3 to EC2
aws s3 cp s3://mybucket/myfolder myfolder  --recursive



Question: Question: What is private hosted zone?
A private hosted zone is a container that holds information about how you want Amazon Route 53 to respond to DNS queries for a domain



Question: What is the AWS Storage Gateway service?
The AWS Storage Gateway service enables hybrid storage between on-premises environments and the AWS Cloud.


Tuesday 17 July 2018

AWS Tutorial Terminology page 7

AWS Tutorial Terminology page 7

Question: What is Amazon EBS Snapshots?
You can back up the data on your Amazon EBS volumes to Amazon S3 at any point of time knows as snapshots.

Snapshots are incremental backups, which means that only the blocks on the device that have changed after your most recent snapshot are saved.

When you delete a snapshot, only the data unique to that snapshot is removed.
Each snapshot contains all of the information needed to restore your data.



Question: What is enhanced networking on Linux?
Enhanced networking uses single root I/O virtualization (SR-IOV) to provide high-performance networking capabilities on supported instance types. SR-IOV is a method of device virtualization that provides higher I/O performance and lower CPU utilization when compared to traditional virtualized network interfaces.



Question: What is Spot Instances?
A Spot Instance is an unused EC2 instance that is available for less than the On-Demand price.
Because Spot Instances enable you to request unused EC2 instances at steep discounts, you can lower your Amazon EC2 costs significantly.


The hourly price for a Spot Instance is called a Spot price.The Spot price of each instance type in each Availability Zone is set by Amazon EC2, and adjusted gradually based on the long-term supply of and demand for Spot Instances.Your Spot Instance runs whenever capacity is available and the maximum price per hour for your request exceeds the Spot price.



Question: What is Amazon elastic map reduce?
Amazon EMR processes "big data" across a Hadoop cluster of virtual servers on Amazon Elastic Compute Cloud (EC2) and Amazon Simple Storage Service (S3).


Question: What is the AWS Storage Gateway service?
The AWS Storage Gateway service enables hybrid storage between on-premises environments and the AWS Cloud.


Question: Difference between Gateway cached volume and stored volume?
In the cached mode, your primary data is written to S3, while retaining your frequently accessed data locally in a cache for low-latency.
Whereas in the stored mode, your primary data is stored locally and your entire dataset is available for low-latency access while asynchronously backed up to AWS.


Question: What protection was on AWS Storage Gateway?
All data transferred between any type of gateway appliance and AWS storage is encrypted using SSL.
data stored by AWS Storage Gateway in S3 is encrypted server-side with Amazon S3-Managed Encryption Keys (SSE-S3).


Question: What is file gateway?
AWS Storage Gateway service that provides your applications a file interface to seamlessly store files as objects in Amazon S3, and access them, using industry standard file protocols.


Question:What is Amazon kinesis?
Amazon Kinesis is collect and process large streams of data records in real time.
The processed records can be sent to dashboards, used to send alerts and advertising strategies, or send data to a variety of other AWS services.


Question: What are benefits of Amazon Kinesis?
  1. Kinesis Video Streams to capture, process, and store video streams for analytics and machine learning.
  2. Kinesis Data Streams to build custom applications that analyze data streams using popular stream processing frameworks.
  3. Kinesis Data Firehose to load data streams into AWS data stores.
  4. Kinesis Data Analytics to analyze data streams with SQL.



Question: What is IOPS?
IOPS is the standard unit of measurement for I/O (Input/Output) operations per second.


Question: Amazon EBS General Purpose (SSD) volume type?
Elastic Block storage(EBS) General purpose (SSD) is default volume in EC2.
It is suitable for application from small to medium-sized databases, development and test environments, and boot volumes.


Question: What is Aws Data Pipeline?
AWS Data Pipeline is a web service that you can use to automate the movement and transformation of data.
With AWS Data Pipeline, you can define data-driven workflows, so that tasks can be dependent on the successful completion of previous tasks.



Question: What is Amazon Machine Images (AMI)?
An Amazon Machine Image (AMI) provides the information required to launch an instance, which is a virtual server in the cloud.


Monday 12 February 2018

React JS Interview Questions and Answers for beginner

React JS Interview Questions and Answers for beginner

Question: How to use JavaScript expressions in reactJS?
To use the expression in reactjs, you need to wrap the expression with with curly brackets {}.
For Example:
{1+1}
{2*2}
{30/3}
{i == 1 ? 'True!' : 'False'}


Question: How to use JavaScript Expressions in reactJS?

class App extends React.Component {
   render() {
      var myStyle = {
         fontSize: 40,
         color: '#FF0000'
      }
      return (
         <div>
<h1>
Header</h1>
</div>
);
   }
}
export default App;




Question: What is state in ReactJS?
State is the place where the data comes from.
We should try to make our state simple and minimize the number of stateful components.

class App extends React.Component {
   constructor(props) {
      super(props);
  
      this.state = {
         header: "This is Header from State",
         content: "This is Content from State"
      }
   }
   render() {
      return (
         <div>
<h1>
{this.state.header}</h1>
<h2>
{this.state.content}</h2>
</div>
);
   }
}



Question: How to Validating Props?

class App extends React.Component {
   render() {
      return ( 
         <div>
<h1>
 Hello, {this.props.name} </h1>
<h3>
Your Mobile: {this.props.propNumber}</h3>
<h3>
Address: {this.props.propString}</h3>
</div>
);
   }
}
App.propTypes = {
   name: PropTypes.string,
   propNumber: PropTypes.number,
   propString: PropTypes.string,
};
App.defaultProps = {
   name: 'Dear User',   
   propNumber: 9888888888,
   propString: "#8555, Sector 45D, Chandigarh"
}



Question: What is difference between setState and forceUpdate() and findDOMNode() in reactJS?
setState() It is used to update the state of the component.It will only add changes to the original state.
forceUpdate() It is used to forceUpdate the state of the component.It will only update to the original state.
findDOMNode() It is used to forceUpdate the state of the component.It will only update to the original state.


Question: Give working example of forceUpdate() in reactJS?

class App extends React.Component {
   constructor() {
      super();
      this.forceUpdateHandler = this.forceUpdateHandler.bind(this);
   };
   forceUpdateHandler() {
      this.forceUpdate();
   };
   render() {
      return (
         <div>
<button onclick="{this.forceUpdateHandler}">Click to Update</button>
            <br />
<h4>
Random number: {Math.random()}</h4>
</div>
);
   }
}



Question: How to use Loop in ReactJS?

var rows = [];
for (var i = 0; i &lt; numrows; i++) {
    rows.push(<objectrow key="{i}">);
}
return tbody(rows);  </objectrow>



Question: What is meaning of ... in ReactJS?
... is called Spread Attributes.
If you already have props as an object, and you want to pass it in JSX, you can use ... as a "spread" operator to pass the whole props object. For Example:

var parts = ['two', 'three'];
var numbers = ['one', ...parts, 'four', 'five'];



Question: How to set focus in reactJS?
You can use componentDidMount for the same.

class App extends React.Component{
  componentDidMount(){
    this.nameInput.focus();
  }
  render() {
    return(
      <div>
<input defaultvalue="Won't focus" />
        <input ref="{(input)" /> { this.nameInput = input; }} 
          defaultValue="will focus"
        /&gt;
      </div>
);
  }
}




Monday 8 January 2018

Zend Framework 2 Interview questions and answers for beginners

Zend Framework 2 Interview questions and answers for beginners

Question: What is module in ZF2?
Zend Framework2 uses a module system to organised your main application-specific code within each module.
Module is separated code from main which contain its own controllers, models, forms and views, along with configuration.
File Structure of module are as following
     /module
         /Album
             /config
             /src
                 /Album
                     /Controller
                     /Form
                     /Model
             /view
                 /album
                     /album



Question: What is Service manager?
The Service Manager is an implementation of the "Service Locator" design pattern.

Keys used for the service manager should be unique across all modules, you can do
this by prepended by the module name in keys.

Service manager configuration files are merged by the module manager.
The service manager lazily instantiate services when they are needed.



Question: How to invoke a class by service manager?
$serviceManager->setInvokableClass('user_mapper', 'User\Mapper\UserMapper');



Question: How to set the routing in Zend Framework2?
In Zend framwork2, routing is set in configuration file of same module.
File path: module.config.php (Full path: \module\Album\config\module.config.php)

Example of Routing in Zend Framework
'router' => array(
    'routes' => array(
        'album' => array(
            'type' => 'segment',
            'options' => array(
                'route' => '/album[/:action][/:id]',
                'constraints' => array(
                    'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
                    'id' => '[0-9]+',
                ),
                'defaults' => array(
                    'controller' => 'Album\Controller\Album',
                    'action' => 'index',
                ),
            ),
        ),
    ),
)

Following are the example of URL with above routing.
URL 1 : /album/index (Listing)
URL 2 : /album/add (Add Album)
URL 3 : /album/edit/10 (Edit Album )
URL 4 : /album/delete (Delete Album )

If you try to access url /album/hello, it will try to search helloAction in same controller.


Question: How to connect to mysql database in Zend Framework2?
  1. open global.php(/config/autoload/global.php)
  2. Add following before the "return array" String.
        $mysqlDbName='zf2';
        $mysqlDbHost='localhost';
        $mysqlDbUsername='root';
        $mysqlDbPassword='';
    
  3. replace the db array with following
         'db' => array(
             'driver'         => 'Pdo',
             'dsn'            => "mysql:dbname={$mysqlDbName};host={$mysqlDbHost}",
             'username' => $mysqlDbUsername,
             'password' => $mysqlDbPassword,         
             'driver_options' => array(
                 PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
             ),
         ),
        




Question: How to protect from Cross Site Scripting (XSS) vulnerabilities?
You need to use a in-built function whenever you print any data to browser.
    $htmlData='Hello World! How are you?';
    echo $this->escapeHtml($htmlData);



Question: How to direct from controller in Zend Framework2?
you can use redirect method for same.
    $this->redirect()->toUrl('/album/edit/1');



Question: How to permanent Redirect in Zend Framework2?
you can use redirect method for same.
    $this->redirect()->toUrl('/album/')->setStatusCode(301);



Question: How to temporary redirect in Zend Framework2?
you can use redirect method for same.
    $this->redirect()->toUrl('/album/')->setStatusCode(302);



Question: How to Change layout from controller in Zend Framework 2.0?
Add Following code in controller.
$this->layout('layout/custom'); //custom.phtml      
File path is : module\{module}\view\layout\custom.phtml Question: How to Change layout for module level in Zend Framework 2?
  1. Open the module.config.php of the module. (path: module\{module}\config\module.config.php)
  2. Add/Update Following code in view_manager array.
            'template_map' => array(
                'layout/layout'           => __DIR__ . '/../view/layout/layout.phtml', //Setup the layout            
                'error/404'               => __DIR__ . '/../view/error/404.phtml',    //Setup the error        
            ),
    




Thursday 7 September 2017

Shell Scripting Interview Questions and Answer

Shell Scripting Interview Questions and Answer

Question: How to Check if a directory exist?
DIRECTORY='directoryname'
if [ -d "$DIRECTORY" ]; then
  echo "Directory is found"
else
  echo "Directory is Not found"
fi



Question: How to concatenate two string variable?
str1='Web'
str2='Technology'
fullStr="$str1 $str2";
echo $fullStr; #Web Technology 



Question: What do you mean by echo file1.txt > file2.txt?
> is used to redirect output.
echo file1.txt > file2.txt

It just redirect the output to file2.txt


Question: What do you means by 2>&1?
0 is stdin
1 is stdout
2 is stderr
>& is the syntax to redirect a stream to another file descriptor

So, Its saying display the error on stdout


Following two do same thing.
echo test 1>&2
OR
echo test >&2




Question: What is scp and why use? Give example?
SCP is used to copy the file/dir from one server to another server.
Example:
scp -r user@your.server.example.com:/path/to/source /home/user/destination/




Question: What is command to copy a file?
cp file1.txt \another\folder\file1.txt



Question: What is command to move a file?
mv file1.txt \another\folder\file1.txt



Question: How to count number of words in file?
 wc -w file.txt



Question: How to append in file from source file?
 cat sourcefile.txt >> destinationfile.txt
It will add the content in destinationfile.txt from sourcefile.txt



Question: How to search a string and then delete that line?
 sed '/removeTxt/d' ./file
It will remove the line having content removeTxt and print the output to console.



Question: How to set a variable to the output from a command?
 OUTPUT="$(ls -1)"
echo "${OUTPUT}"



Question: How to convert a string in lowercase?
a="Hello World!" 
echo "$a" | tr '[:upper:]' '[:lower:]' #hello world!



Question: What is use of export command?
export command is used to make the available of variable in child process.
Example 
export name=test

Now name variable will be accessible in child process.



Question: How to print date in yyyy-mm-dd format?
YYYY-MM-DD format
echo `date +%Y-%m-%d`
YYYY-MM-DD HH:MM:SS format
echo `date '+%Y-%m-%d %H:%M:%S'`



Question: How to reverse the lines?
tac file1.txt
It will revere the lines and display in console output.


Question: How to redirect output to file?
 ls -l 2>&1 | tee -a errorfile.txt

It will store error and output(both) in error_file.txt


Question: How to determine whether a Linux is 32 bit or 64 bit?
uname -m

Output
x86_64 ==> 64-bit kernel
i686   ==> 32-bit kernel



Question: How to compare two directories?
diff --brief -r dir1/ dir2/
diff -qr -r dir1/ dir2/



Question: When do we need curly braces around shell variables?
When you want to expand the variable (like foo) in the string.
For Example you want to make $foobar.
echo "${foo}bar"




Friday 29 July 2016

Laravel Interview Questions and Answers

Laravel Interview Questions and Answers

Question: What is Laravel?
Laravel is a open-source PHP framework developed by Taylor Otwell used for Developing the websites.
Laravel helps you create applications using simple, expressive syntax.


Question: What are Advantages of Laravel?
  1. Easy and consistent syntax
  2. Set-up process is easy
  3. customization process is easy
  4. code is always regimented with Laravel



Question: Explain about Laravel Project?
Laravel is one of the most popular PHP frameworks used for Web Development.
This framework is with expressive, elegant syntax.
It is based on model–view–controller (MVC) architectural pattern.


Question: What are the feature of Laravel5.0?
  1. Method injection
  2. Contracts
  3. Route caching
  4. Events object
  5. Multiple file system
  6. Authentication Scaffolding
  7. dotenv – Environmental Detection
  8. Laravel Scheduler



Question: Compare Laravel with Codeigniter?
Laravel Codeigniter
Laravel is a framework with expressive, elegant syntax CodeIgniter is a powerful PHP framework
Development is enjoyable, creative experience Simple and elegant toolkit to create full-featured web applications.
Laravel is built for latest version of PHP Codeigniter is an older more mature framework
It is more object oriented compared to CodeIgniter. It is less object oriented compared to Laravel.
Laravel community is still small, but it is growing very fast. Codeigniter community is large.



Question: What are Bundles,Reverse Routing and The IoC container ?
Bundles: These are small functionality which you may download to add to your web application.
Reverse Routing: This allows you to change your routes and application will update all of the relevant links as per this link.
IoC container: It gives you Control gives you a method for generating new objects and optionally instantiating and referencing singletons.



Question: How to set Database connection in Laravel?
Database configuration file path is : config/database.php
Following are sample of database file
 
'mysql' => [
    'read' => [
        'host' => 'localhost',
    ],
    'write' => [
        'host' => 'localhost'
    ],
    'driver'    => 'mysql',
    'database'  => 'database',
    'username'  => 'root',
    'password'  => '',
    'charset'   => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix'    => '',
],
 



Question: How to enable the Query Logging?
DB::connection()->enableQueryLog();



Question: How to use select query in Laravel?
$users = DB::select('select * from users where city_id = ?', 10);
if(!empty($users)){
    foreach($users as $user){

    }
} 



Question: How to use Insert Statement in Laravel?
DB::insert('insert into users (id, name, city_id) values (?, ?)', [1, 'Web technology',10]);



Question: How to use Update Statement in Laravel?
DB::update('update users set city_id = 10 where id = ?', [1015]);



Question: How to use Update Statement in Laravel?
DB::update('update users set city_id = 10 where id = ?', [1015]);



Question: How to use delete Statement in Laravel?
DB::delete('delete from  users where id = ?', [1015]);



Question: Does Laravel support caching?
Yes, Its provides.


Monday 11 April 2016

YII interview questions and answers for fresher

yii interview questions and answers for fresher

Question: What is Yii?
Yii is a PHP framework which is based on MVC (Model View Controller).


Question: Is it opensource?
Yes, It is opensource. Download and use as per your project requirement. Question: What is full form of Yii
Yes it is.


Question: In which language, It is written?
PHP.


Question: What is current stable version of Yii?
Version: 2.0.7 dated February 14, 2016.


Question: What is offical website of Yii Framework?
http://www.yiiframework.com


Question: From where i an download Yii Framework?
http://www.yiiframework.com/download


Question: How to start Yii?
http://www.yiiframework.com/tour


Question: What are main feature of Yii framework?
  1. MVC design pattern
  2. Web Service available for Apps like android
  3. Internationalization and localization translation for multilingual.
  4. Caching for speed up the application
  5. Error handling and logging for tracking
  6. cross-site scripting (XSS), cross-site request forgery (CSRF) protection
  7. PHPUnit and Selenium for testing.
  8. Automatic code generation help us to fast development.



Question: How to set default controller on Yii?
array(
    'name'=>'Yii Framework',
    'defaultController'=>'site',
);



Question: How to get current controller id?
echo Yii::app()->controller->id;



Question: How to get current action id?
echo Yii::app()->action->id;



Question: What is the first function that gets loaded from a controller? ?
index



Question: How can we use ajax in Yii?
use ajax helper


Question: What are two type of models in YII
  1. Form models
  2. active records


Question: What are active records model?
Active Record is a design pattern used to abstract database access in an object-oriented way.
active records model is based on this design pattern.


Question: How to define a form model?
class MyLoginForm extends CFormModel
{
    public $username;
    public $password;
    public $rememberMe=false;
}



Question: How to set validation in Form Model?
class MyLoginForm extends CFormModel
{
    public $username;
    public $password;
    public $rememberMe=false; 
    private $_identity;
 
    public function rules()
    {
        return array(
            array('username, password', 'required'),
            array('rememberMe', 'boolean'),
            array('password', 'authenticate'),
        );
    }
 
    public function authenticate($attribute,$params)
    {
        $this->_identity=new UserIdentity($this->username,$this->password);
        if(!$this->_identity->authenticate())
            $this->addError('password','username or password Incorrect .');
    }
}



Question: What are the core application components available on Yii?
  1. db- database connection.
  2. assetManager - manage the publishing of private asset files
  3. authManager - manage role-based access control
  4. cache- manage caching functionality
  5. clientScript- manage javascript and CSS
  6. coreMessages- provides translated core messages
  7. errorHandler- manage errors handling.
  8. themeManager- Manage themes
  9. urlManager- URL parsing and creation functionality
  10. statePersister- mechanism for persisting global state
  11. session- Session management
  12. securityManager- Security Managment



Thursday 7 January 2016

OOP Interview Questions and Answers

OOP Interview Questions and Answers


What is Object Oriented Programming?
Object-oriented programming (OOP) is a programming language model organized around objects rather than actions;
Objects are instances of classes, are used to interact with one another.

Following are few examples of object-oriented programming languages
PHP, C++, Objective-C, Smalltalk, C#, Perl, Python, Ruby.

The goals of object-oriented programming are:
  1. Increased understanding.
  2. Ease of maintenance.
  3. Ease of evolution.


What is data modeling?
In class, we create multiple get/set function to get and set the data through the protected functions known as Data Modeling.
class dataModel {    
    public function __set( $key, $value ) {
        $this->$key = $value;
    } 
}
Following are the benefits of Data Modeling
  1. It is very fast.
  2. Smart way to  manipulation on data
  3. No extra layer of logic 
  4. Really flexible to be modeled per need 
  5. Setters can explicitly define what data can be loaded into the object


What is difference between class and interface?
1) Interfaces do not contain business logic
2)You must extend interface to use.
3) You can't create object of interface.



How Session - cookie works in PHP?
When a website open in new client machine(Browser), new sessionId is created and stored in php server and in client machine (In cookie).
All data is store in PHP Server and cookie only have sessionId. When client send sessionId with request to the server, then server fetch the data corresponsing to that sessionId and retun to the browser.



What are some of the big changes PHP has gone through in the past few years?
5.1 added PDO
5.3 - added namespace support



What is Polymorphism?
It is simply "One thing, can use in different forms"
For example, One car (class) can extend two classes (hond & Alta)



How to load classes in PHP.
We can load a class with the use of "autoload" class.
If we want to change from default function autoload to testautload function.
we can do this with "spl_autoload_register"
spl_autoload_register('kumar');



How to call parent constructor?
parent::__construct()



Are Parent constructors called implicitly when create an object of class?
No, Parent constructors are not called implicitly It must call this explicitly. But If Child constructors is missing then parent constructor called implicitly.



What happen, If constructor is defined as private OR protected.
If constructor declared as private, PHP through the following fatal error when create object. Fatal error: Call to private BaseClass::__construct() from invalid context in. If constructor declared as private, PHP through the following fatal error when create object. Fatal error: Call to protected BaseClass::__construct() from invalid context in



What happen, If New-Style constructor & old-style constructor are defined. Which one will be called.
New-Style constructor will called. But if New-Style constructor is missing, old style constructor will called.


What are different visibility of method/property?
There are 3 types of visibility of method & property and are following
Public: Can be accessed from same class method, child class and from outside of class.
Protected : Can be accessed from same class method, child class.
Private: Can be accessed from same class method only.
class TestClass
{
    public $public = 'Public';
    protected $protected = 'Protected';
    private $private = 'Private';

    function printValue()
    {
        echo $this->public;
        echo $this->protected;
        echo $this->private;
    }
}

$obj = new TestClass();
echo $obj->public; // Works
echo $obj->protected; // Fatal error: Cannot access protected property TestClass::$protected in
echo $obj->private; // Fatal error: Cannot access private property TestClass::$private in C:\wamp\www\arun\class\class.php on line 20
$obj->printValue(); // Shows Public, Protected and Private 


What is Scope Resolution Operator?
The Scope Resolution Operator (also called Paamayim Nekudotayim) is double colon that allows access to static, constant, and overridden properties or methods of a class. Following are different uses Access to static
Acess the constant
Access the overridden properties of parent class
Access the overridden methods of a parent class



What is Static Keyword in PHP?
  • If we declare a Method or Class Property as static, then we can access that without use of instantiation of the class.
  • Static Method are faster than Normal method.
  • $this is not available within Static Method.
  • Static properties cannot be accessed through the object(i.e arrow operator)
  • Calling non-static methods with Scope Resolution operator, generates an E_STRICT level warning.
  • Static properties may only be initialized using a literal or constant value.
  • Static properties/Normal properties Can't be initialized using expressions value.

class StaticClass
{
    public static $staticValue = 'foo';

    public function staticValue() {
        return self::$my_static;
    }
}
echo StaticClass::$staticValue;




What is Abstraction in PHP?
  • Abstraction are defined using the keyword abstract .
  • PHP 5 introduces abstract classes and methods. Classes defined as abstract may not be instantiated (create object).
  • To extend the Abstract class, extends operator is used.
  • You can inherit only one abstract class at one time extending.
  • Any class that contains one abstract method must also be declare as abstract. Methods defined as abstract simply declare the method's signature, they can't define the implementation.
  • All methods marked as abstract in the parent's class, declaration must be defined by the child.
  • additionally, these methods must be defined with the same (or a less restricted) visibility (Public,Protected & private).
  • Type hint & number of parameter must be match between parent & child class.



What is Interface in PHP?
  • Interfaces are defined using the interface keyword.
  • All methods declared in an interface must be public. Classes defined as Interface may not be instantiated(create object).
  • To extend the interface class, implements operator is used.
  • You can inherit number of interface class at the time of extending and number of abstract class separated by comma.
  • All methods in the interface must be implemented within a child class; failure to do so will result in a fatal error.
  • Interfaces can be extended like classes using the extends operator.
  • The class implementing the interface must use the exact same method signatures as are defined in the interface. Not doing so will result in a fatal error.
  • Type hint & number of parameter must be match.



What is Traits in PHP?
  1. Traits are a mechanism for code reuse in single inheritance.
  2. A Trait is similar to a class, but only intended to group functionality in a fine-grained and consistent way. 
  3. It is not possible to instantiate a Trait but addition to traditional inheritance. It is intended to reduce some limitations of single inheritance to reuse sets of methods freely in several independent classes living in different class hierarchies.
  4. Multiple Traits can be inserted into a class by listing them in the use statement, separated by commas(,).
  5. If two Traits insert a method with the same name, a fatal error is produced.

    Example of Traits
class BaseClass{
    function getReturnType() {
        return 'BaseClass';
    }
}
trait traitSample {
    function getReturnType() {
        echo "TraitSample:";
        parent::getReturnType();
    }    
}

class Class1 extends BaseClass {
    use traitSample;   
}

$obj1 = new Class1();
$obj1->getReturnType();//TraitSample:BaseClass



What is Overloading?
It is dynamically create method / properties and performed by magic methods. Overloading method / properties are invoked when interacting with properties or methods that have not been declared or are not visible in the current scope, Means we you are calling a function which is not exist. None of the arguments of these magic methods can be passed by reference.
In PHP, Overloading is possible http://200-530.blogspot.in/2013/04/oop-magic-methods.html



What is Object Iteration?
PHP provides a way for objects to be iterate through a list of items, for this we can use foreach. Only visible properties will be listed.
class TestClass{
    public $public='PublicVal';
    protected $protected='ProtectedVal';
    private $private='PrivateVal';
    
    function myfunc() {
        return 'func';
    }
    
    function iterateVisible(){
        foreach($this as $key => $value) {
           print "$key => $value\n";
       }
    }
}

$obj=new TestClass();
$obj->iterateVisible(); 



What is Final Keyword in PHP?
PHP introduces the final keyword, which prevents child classes from overriding a method by prefixing the definition with final.
If the class itself is being defined final then it cannot be extended. If the function itself is being defined final then it cannot be extended.



What is Serialize function in php?
It return string containing a byte-stream representation of any value that can be stored in PHP.



Comparing Objects?
When using the comparison operator (==), object variables are compared in a simple manner, namely: Two object instances are equal if they have the same attributes and values, and are instances of the same class.
When using the identity operator (===), object variables are identical if and only if they refer to the same instance of the same class



What is UML?
UML stands for Unified Modeling Language.
You can do following things with UML
  • Manage project complexity.
  • create database schema.
  • Produce reports.


What are Properties of Object Oriented Systems?
  • Inheritance
  • Encapsulation of data
  • Extensibility of existing data types and classes
  • Support for complex data types
  • Aggregation
  • Association 


Question: What is serialization?
serialization: returns a string containing a byte-stream representation of any value that can be stored in PHP.
Before starting your serialization process, PHP will execute the __sleep function automatically.

What can you Serialize?
  1. Variables
  2. Arrays
  3. Objects


For example
   
$str_array = array( "I", "Love", "PHP" );
$serialized_str = serialize($str_array);
echo $serialized_str;
Output
a:3:{i:0;s:1:"I";i:1;s:4:"Love";i:2;s:3:"PHP";}




Question: What is un-serialization?
unserialize: can use this string to recreate the original variable values.
Before starting your unserialization process, PHP will execute the __wakeup function automatically.

What can you  un-Serialize?
Resource-type

   
$unserialized = unserialize('a:3:{i:0;s:1:"I";i:1;s:4:"Love";i:2;s:3:"PHP";}');
print_r($unserialized);

Output
Array ( [0] => I [1] => Love [2] => PHP )