Sunday, May 19, 2019

Mysql viva Questions and Answers


Clone Tables:

SHOW CREATE TABLE tutorials_tbl 
 
--Get the complete structure about the table.
-- Rename this table and create another table.
-- If you want to copy data from old table then you can do it by using INSERT INTO... SELECT statement.
REF: https://www.tutorialspoint.com/mysql/mysql-clone-tables.htm



SELECT VERSION( ) - Server version string
SELECT DATABASE( ) - Current database name (empty if none)
SELECT USER( ) - Current user name
SHOW STATUS - Server status indicators
SHOW VARIABLES - Server configuration variables


Database Export/Import

-- Exporting Data with the SELECT ... INTO OUTFILE Statement
-- LOAD DATA LOCAL INFILE 'dump.txt' INTO TABLE mytbl; (INFILE)

 

What is the difference between Primary Key and Unique Key?

Both Primary and Unique Key is implemented for Uniqueness of the column. Primary Key creates a clustered index of column where as an Unique creates unclustered index of column. Moreover, Primary Key doesn’t allow NULL value, however Unique Key does allows one NULL value.


How to store picture file in the database. What Object type is used?

Storing Pictures in a database is a bad idea. To store picture in a database Object Type ‘Blob’ is recommended.

What is Data Mining?

 Data Mining is a subcategory of Computer Science which aims at extraction of information from set of data and transform it into Human Readable structure, to be used later.

What is an ERD?

ERD stands for Entity Relationship Diagram. Entity Relationship Diagram is the graphical representation of tables, with the relationship between them. 

What are indexes in a Database. What are the types of indexes?

Clustered Index
  1. Only one per table.
  2. Faster to read than non clustered as data is physically stored in index order.
Non­clustered Index
  1. Can be used many times per table.
  2. Quicker for insert and update operations than a clustered index.

Clustered Index
A clustered index determine the physical order of DATA in a table.For this reason a table have only 1 clustered index.
like "dictionary" No need of any other Index, its already Index according to words
Nonclustered Index
A non clustered index is analogous to an index in a Book.The data is store in one place. the index is store in another place and the index have pointers to the storage location of the data.For this reason a table have more than 1 Nonclustered index.
like "Chemistry book" at staring there is a separate index to point Chapter location and At the "END" there is another Index pointing the common WORDS location

What is the difference between Primary Key and Unique Key

Both Primary and Unique Key is implemented for Uniqueness of the column. Primary Key creates a clustered index of column where as an Unique creates unclustered index of column. Moreover, Primary Key doesn’t allow NULL value, however Unique Key does allows one NULL value.

 

What are Heap tables?

HEAP tables are present in memory and they are used for high speed storage on temporary basis.
• BLOB or TEXT fields are not allowed
• Only comparison operators can be used =, <,>, = >,=<
• AUTO_INCREMENT is not supported by HEAP tables
• Indexes should be NOT NULL

How do you control the max size of a HEAP table?
Maximum size of Heal table can be controlled by MySQL config variable called max_heap_table_size


 What is the default port for MySQL Server?
The default port for MySQL server is 3306.

How do you login to MySql using Unix shell?
We can login through this command:
# [mysql dir]/bin/mysql -h hostname -u <UserName> -p <password>

 What happens when the column is set to AUTO INCREMENT and if you reach maximum value in the table?
It stops incrementing. Any further inserts are going to produce an error, since the key has been used already.

 How can we find out which auto increment was assigned on Last insert?
LAST_INSERT_ID will return the last value assigned by Auto_increment and it is not required to specify the table name

How can you see all indexes defined for a table?
SHOW INDEX FROM <tablename>;

What do you mean by % and _ in the LIKE statement?
% corresponds to 0 or more characters, _ is exactly one character in the LIKE statement.

Is Mysql query is case sensitive?
No.

What are the different tables present in MySQL?
Total 5 types of tables are present:
  • MyISAM - Each MyISAM table is stored on disk, MyISAM is the default storage engine as of MySQL
  • Heap
  • Merge
  • INNO DB - lnnoDB is a transaction safe storage engine developed by Innobase Oy which is a Oracle Corporation now.
  • ISAM
MySQL Database Engines: MySQL is a SQL database processing layer on top of a storage engine. The default engine is MyISAM which is very fast but does not support higher level functionality such as foreign keys or transactions. One must use the InnoDB database storage engine to support foreign keys and transactions.


 What is the difference between CHAR and VARCHAR?

When the table is created, CHAR is used to define the fixed length of the table and columns. The length value could be in the range of 1-255. VARCHAR command is given to adjust the column and table length as required

 What are the limits for using columns to create the Index?

The maximum limits of indexed columns that could be created for any table is 16.

What is the use of ENUM in MySQL?

Use of ENUM will limit the values that can go into a table. For instance; the user can create a table giving specific month values and other month values would not enter into the table.
 -- enum includes varibales that variable can be insert.

What is meant by transaction and ACID properties?

Transaction is logical unit of work where either all or none of the steps should be performed. ACID is the abbreviation for Atomicity, Consistency, Isolation, and Durability that are properties of any transaction.

What are the standard SQL commands every SQL developer should know?

The basic SQL commands can be organized into the following categories:
  • Data Manipulation Language (DML)
    • INSERT: Creates records. The “Create” in CRUD.
    • SELECT: Retrieves records. The “Read” in CRUD.
    • UPDATE: Modifies records. The “Update” in CRUD.
    • DELETE: Deletes records. The “Delete” in CRUD.
  • Data Definition Language (DDL)
    • CREATE: Creates a new object.
    • ALTER: Alters an existing object.
    • DROP: Deletes an existing object.
  • Data Control Language: (DCL)
    • GRANT: Grants privileges to users.
    • REVOKE: Revokes privileges previously granted to a user.

Name four ways to maintain data integrity within a RDBMS.
AWhen it comes to storing data accurately, consistently, and reliably within a RDBMS, there are four general types of data integrity that you can implement:
  • Entity (Row) Integrity: Avoids duplicate rows in tables.
  • Domain (Column) Integrity: Restricts the type, format, or range of values to enforce valid entries.
  • Referential Integrity: Ensures rows used by other records cannot be deleted.
  • User-Defined Integrity: Enforces rules set by the user that do not fall into the other categorie

What is the purpose of database normalization and how does it work?

AThe primary purpose of normalization is to make databases more efficient by eliminating redundant data and ensuring data dependencies are coherent. Storing data logically and efficiently reduces the amount of space the database takes up and improves performance. The set of guidelines used to achieve normalization are called normal forms, numbered from 1NF to 5NF. A form can be thought of as a best-practice format for laying out data within a database.

 Use following command for taking backup of your MySQL database using mysqldump utility.
mysqldump –u[user name] –p[password] [database name] > [dump file]

mysql -u username -p database_name < file.sql (IMport)




Reference: 
  1. https://www.tutorialspoint.com/mysql/mysql-administration.htm
  2. https://www.tecmint.com/10-mysql-database-interview-questions-for-beginners-and-intermediates/
  3.  https://career.guru99.com/top-50-mysql-interview-questions-answers/
  4. https://www.guru99.com/wildcards.html (_, % in LIKE in sQL)
  5. https://www.upwork.com/i/interview-questions/sql/ (important)
  6. http://upworktestru.com/mysql-test-upwork-answers-questions/ (important for upwork test)
  7.  https://blogs.oracle.com/mysql/how-to:-storing-and-retrieving-spatial-data-on-mysql-server-with-connectornet
  8.  http://www.mysqltutorial.org/select-random-records-database-table.aspx (rand()) (VVI)

*Names of databases, tables and columns can be up to 64 characters in length 
 

create table foo (id int auto_increment, name int);

The id column cannot be auto incremented because it has not been defined as a primary key

 

 Use the SQL_NO_CACHE option in the query.

upwork test:

Tuesday, May 14, 2019

Nodejs viva question and answer


https://www.youtube.com/watch?v=OHYjxMoG5XU (very very inportnat)

difference between async.series and async.parallel

async.series invokes your functions serially (waiting for each preceding one to finish before starting next). async.parallel will launch them all simultaneously (or whatever passes for simultaneous in one-thread land, anyway).



--------------------------------------------
https://www.designcise.com/web/tutorial/whats-the-difference-between-promise-all-and-promise-allsettled-in-javascript

Promise.all():

Promise.all() resolves only when all given promises resolve, and will reject immediately if any of the promises reject (or non-promises throw an error). It is useful in cases when you have interdependent tasks, where it makes sense to reject immediately upon any of them rejecting.

Promise.allSettled():

Promise.allSettled() resolves when all of the given promises have either fulfilled or rejected. Unlike Promise.all(), it does not immediately reject upon any of the promises rejecting, instead it waits for all promises to complete, even if some of them fail. Therefore, it is useful in cases when you have multiple asynchronous tasks that are not interdependent, where you may want to know the result of each promise.

----------------------------------

nodejs debuging

-- use console.log ,      --instapact, vs code provide builting debuging 

---------

Event module 

https://www.tutorialspoint.com/nodejs/nodejs_event_emitter.htm

----------------------------
Error handling
https://www.toptal.com/nodejs/node-js-error-handling

Up to this point, we mostly discussed dealing with operational errors. How about programmer errors? The best way to deal with these errors is to crash immediately and restart gracefully with an automatic restarter like PM2—the reason being that programmer errors are unexpected, as they are actual bugs that might cause the application to end up in a wrong state and behave in an unexpected way.





What is Node.js? Where can you use it?  
Node.js is a JavaScript runtime platform built on Chrome's V8 JavaScript engine.
-- video streaming sites
-- real time application (chatting)
-- General-purpose applications and Distributed systems.
Features of Node.js
Asynchronous and Event DrivenAll APIs of Node.js library are asynchronous, that is, non-blocking. It essentially means a Node.js based server never waits for an API to return data. The server moves to the next API after calling it and a notification mechanism of Events of Node.js helps the server to get a response from the previous API call.
  • It is generally fast
  • It almost never blocks
  • It offers a unified programming language and data type
  • Everything is asynchronous


Where to Use Node.js?

Following are the areas where Node.js is proving itself as a perfect technology partner.
  • I/O bound/intensive Applications (An application that reads and/or writes a large amount of data)
  • Data Streaming Applications ()
  • Data Intensive Real-time Applications (DIRT)
  • JSON APIs based Applications
  • Single Page Applications

Where Not to Use Node.js?

It is not advisable to use Node.js for CPU Bound/intensive applications.

Is Node.js a framework?

No, it's an environment, and back-end frameworks run within it. Popular ones include Express.js (or simply Express) for HTTP servers and Socket.IO for WebSocket servers.

Is Node.js a programming language?

No, the ".js" means that the programming language you use with Node.js is JavaScript (or anything that can transpile to it, like TypeScript, Haxe, or CoffeeScript.)

What is the difference between Node.js and Angular/AngularJS?

Node.js executes JavaScript code in its environment on the server, whereas Angular is a JavaScript framework that gets executed on the client (i.e. within a web browser.)

Why is Node.js Single-threaded?

Node.js is single-threaded for async processing.
-- For single thread, more performance and scalability

By doing async processing on a single-thread under typical web loads, more performance and scalability can be achieved as opposed to the typical thread-based implementation.


Explain callback in Node.js.

A callback function is called at the completion of a given task. This allows other code to be run in the meantime and prevents any blocking.  Being an asynchronous platform, Node.js heavily relies on callback. All APIs of Node are written to support callbacks.

-- library or functions are asynchoronus so, sometime we need to do some task after getting response. that we send callback function with custom code to execute.

What are the functionalities of NPM in Node.js?

NPM (Node package Manager) provides two functionalities:
  • Online repository for Node.js packages
  • Command line utility for installing packages, version management and dependency management of Node.js packages

What are Globals in Node.js?

Three keywords in Node.js constitute as Globals. These are:
  • Global – it represents the Global namespace object and acts as a container for all other <global> objects.
  • Process – It is one of the global objects but can turn a synchronous function into an async callback. It can be accessed from anywhere in the code and it primarily gives back information about the application or the environment. 
  • Buffer – it is a class in Node.js to handle binary data. 
  • console - console.log, console.info. console.info
  • settimeout
  • settimeinterval
  • __filename
  • __dirname

     


 What are “streams” in Node.js

Streams are objects that let you read data from a source or write data to a destination in continuous fashion. In Node.js, there are four types of streams −
  • Readable − Stream which is used for read operation.
  • Writable − Stream which is used for write operation.
  • Duplex − Stream which can be used for both read and write operation.
  • Transform − A type of duplex stream where the output is computed based on input.
Each type of Stream is an EventEmitter instance and throws several events at different instance of times. For example, some of the commonly used events are −
  • data − This event is fired when there is data is available to read.
  • end − This event is fired when there is no more data to read.
  • error − This event is fired when there is any error receiving or writing data.
  • finish − This event is fired when all the data has been flushed to underlying system.


Node.js - Utility Modules

 There are several utility modules available in Node.js module library. These modules are very common and are frequently used while developing any Node based application.

OS Module
Provides basic operating-system related utility functions.
Path Module
Provides utilities for handling and transforming file paths.
Net Module
Provides both servers and clients as streams. Acts as a network wrapper.
DNS Module
Provides functions to do actual DNS lookup as well as to use underlying operating system name resolution functionalities.
Domain Module
Provides ways to handle multiple different I/O operations as a single group.


Can you access DOM in node?
No, you cannot access DOM in node.

What is the command that is used in node.js to import external libraries?
Command “require” is used for importing external libraries, for example, “var http=require (“http”)”.  This will load the http library and the single exported object through the http variable.

What is global installation of dependencies?

Globally installed packages/dependencies are stored in <user-directory>/npm directory. Such dependencies can be used in CLI (Command Line Interface) function of any node.js but can not be imported using require() in Node application directly. To install a Node project globally use -g flag.
C:\Nodejs_WorkSpace>npm install express -g











Use the following command −
C:\Nodejs_WorkSpace>npm ls -g
 
 

What is Package.json?

package.json is present in the root directory of any Node application/module and is used to define the properties of a package.
 
 

What is Event Emmitter?

EventEmitter class lies in events module. It is accessibly via following syntax −
//import events module
var events = require('events');

//create an eventEmitter object
var eventEmitter = new events.EventEmitter();
When an EventEmitter instance faces any error, it emits an 'error' event. When new listener is added, 'newListener' event is fired and when a listener is removed, 'removeListener' event is fired.
EventEmitter provides multiple properties like on and emit. on property is used to bind a function with the event and emit is used to fire an event.
 
 Which module is used for file based operations? 
fs module is used for file based operations.
var fs = require("fs")
 
buffer module is used for buffer based operations.
var buffer = require("buffer")
http module is used for web based operations.
var http = require("http")
 
 
What is Piping in Node? 

Piping is a mechanism to connect output of one stream to another stream. 
 
 
 









Streams are objects that let you read data from a source or write data to a destination in continuous fashion.

 
 
 
 

What is Chaining in Node?

Chanining is a mechanism to connect output of one stream to another stream and create a chain of multiple stream operations. It is normally used with piping operations.
 
 

 It shows the latest version of the package that is available.

 npm view <package-name> version
 
 

Interview Questions

Interview questions for Node.js engineers fall into three categories:

  1. General questions: Here, the interviewer should verify common tech knowledge for senior engineers.
  2. JavaScript questions: Node.js is a JavaScript runtime environment, so developers should have a deep understanding of the JavaScript programming language itself. We maintain a community-driven list of interview questions that can be used here.
  3. Node.js questions: Subjects related to the platform itself.

We’ll focus here on platform-related questions for senior developers that can help determine whether a candidate is a great Node.js engineer.

Q: What are three ways to handle asynchronous operations in Node.js? Describe their pros and cons.

There are three primary, built-in approaches for handling async operations: callbacks, promises, and async/await.

Callbacks are the oldest method. It’s best to avoid them, as they have a couple of anti-patterns, like callback hell (also known as the “Pyramid of Doom”). However, they are quite widely used in old projects and libraries.

Promises are a native feature of ECMAScript 6 (ES6, sometimes called ES2015)—supported fully since Node.js 6.17, and partially as far back as Node.js 0.12. They have additional methods that make them more powerful and flexible than callbacks.

Async/await is the newest native approach to deal with asynchronous operations. It’s the best one from a code structure perspective but doesn’t have such a wide range of built-in features as promises do.

Developers should definitely understand and use promises and async/await. It’s even better if they’re experienced with other tools for handling async operations, like bluebird and observables; if they’re being hired for an existing project that uses these extensively, this may be more of a requirement than a nice-to-have.

Red flag: The developer still defaults to callbacks and doesn’t know (or care) about promises and async/await.

Q: How should Node.js developers handle errors in asynchronous functions?

As a follow-up to the answers of the previous question, each approach to asynchronous code has its own way of handling errors.

To handle errors using callbacks, there is the quite well-known error-first convention:

fetchUsers(url, (err, data) => {

  if (err) {

    // handle error 

  } else {

    // operate upon data

  }

});

The idea is that an error is always passed as the first argument of a callback function so it can be handled in a consistent way.

In contrast, promises have a special catch handler to process errors:

fetchUsers(url)

  .then(data => {

    // operate upon data

  })

  .catch(err => {

    // handle error 

  });

To handle errors when using async/await, developers can use a simple try-catch block:

async main() {

  try {

    const data = await fetchUsers(url);

    // operate upon data

  } catch (err) {

    // handle error 

  }

}

Node.js developer candidates should be able to describe the examples above.

Red flags: The developer has little or no experience with handling errors from callbacks, promises, and async/await. (That said, since callbacks aren’t recommended anyway, knowledge of callback error handling would be less important for a greenfield project.)

Q: What are some Node.js frameworks for building web applications? Describe their pros and cons.

Frameworks are almost always a necessity with Node.js. It is quite unlikely for engineers to use pure Node.js built-ins to build web servers, as there are widespread and robust solutions for that, and it simply doesn’t make sense to reinvent the wheel.

Express.js is one of the most popular Node.js frameworks for web applications. Its long-term support is quite good, and it has a lot of commonly needed routing and middleware features, extending Node.js functionality to make it more flexible and powerful.

Nest.js is essentially an upgrade to Express.js that uses TypeScript, a modern language that’s a strict syntactical superset of JavaScript. It provides developers with the ability to write better, more structured, and less error-prone code.

Hapi.jsKoa.jsMeteor, and Sails.js are other web application frameworks for Node.js a candidate might mention.

In the table below, some pros and cons of each of them are listed.

FrameworkAdvantagesDisadvantages
Express.js
  • Simple, flexible, scalable
  • Wide functionality
  • Easy to learn
  • Easy to customize
  • Used by a broad audience
  • Well-documented
  • Performant
  • Does not use TypeScript
  • Difficult to maintain
Nest.js
  • Uses TypeScript
  • Built on top of Express.js
  • Has a well-structured architecture, similar to the Angular framework
  • Used by a broad audience
  • Has built-in modules for popular technologies like GraphQL, microservices, and WebSockets
  • Relatively new, so some functionality from Express.js is not in place
Hapi.js
  • Plugin system, allowing for easier maintenance
  • Profound control of request handling
  • Does not use TypeScript
  • Small audience
  • Performance is lacking
Koa.js
  • Good user experience
  • Lightweight
  • Clean and readable async code
  • Does not use TypeScript
  • Small audience
  • No built-in middleware

Red flag: A Node.js developer with weak or absent knowledge of web application frameworks. A definite exception here would be if they have strong knowledge in one particular framework—particularly Express.js, since it’s practically a de-facto standard and even the foundation of some of the other frameworks.

Q: What are the two main ways to scale an application? Is there anything specifically to Node.js in how you would approach them?

This question helps determine whether a developer has experience with building large applications. Node.js apps can be scaled horizontally and vertically.

Horizontal: Node.js can be cloned and distributed across multiple servers, or across CPU nodes within one server. There are solutions in a place like PM2 that help to distribute load across nodes within a server, or AWS Load Balancer to help with multi-server scaling.

Vertical: This means CPU and memory can be increased on the same node/server—nothing Node.js-specific.

Red flag: The developer doesn’t have knowledge of, or experience in, scaling.

Q: How do developers test a Node.js application?

There are three main types of testing: unit, integration, and end-to-end.

  • Unit testing means testing individual units/components of an application. It’s the lowest level of testing, the purpose of which is to verify if small pieces of code work properly in isolation.
  • Integration testing is the next level of testing, which intends to make sure that separate modules work together accurately.
  • End-to-end testing is the highest level of the testing hierarchy, which verifies that both client and server work properly together.

Quite often, developers need to use stubs and spies to mock third-party modules or API calls. They are crucial during testing as they prevent accessing real data, and simplify testing itself.

There are different packages for Node.js that help with testing, including Mocha, Chai, and Jest. Developers should be familiar with at least one—preferably with the one (hopefully) already in use, in the case of an existing project.

At the very least, a candidate should understand the difference between testing types.

Red flag: The developer has no experience with unit, integration, or end-to-end testing.

Q: How can Node.js developers make sure that project dependencies are secure?

A Node.js app may become insecure because of the npm packages in use. There are a few rules developers should follow to keep an application safe:

  1. Check packages themselves. It’s worth validating the package’s author, its GitHub stars, opened/closed issues comparison, weekly downloads, number of releases, etc.
  2. Use the npm audit command. It allows getting a list of packages’ known vulnerabilities. Running npm audit fix would automatically install compatible updates to vulnerable dependencies. It also executes by default during npm install.
  3. Use npm outdated to verify if any installed packages are obsolete.

Dedicated Node.js developers will take care of vulnerabilities by staying on top of such issues continuously as part of the development process.

Red flag: The developer blanketly ignores or doesn’t care about vulnerability warning messages.

Q: What are global objects in Node.js? Describe them.

Node.js has two types of global objects: global and pseudo-global.

Global objects are those which are available in the global scope. There are also built-in objects that are accessible in the global scope as well—those that are part of the JavaScript language itself.

The most-used global objects are:

  1. console, a Node.js module used to print to stdout and stderr
  2. global, a global namespace object. In browsers, the top-level scope is the global scope, but Node.js is different. A method/variable should be put in the global object to be accessible in every module.
  3. process, a Node.js module allowing interaction with Node.js’ running process
  4. Built-in functions, like setTimeout()setImmediate(), and setInterval()

By contrast, pseudo-global objects exist in the module scope. Pseudo-globals include:

  1. __dirname, the directory name of the current module
  2. __filename, the file name of the current module
  3. moduleexports, and module.exports, which are part of Node.js module system
  4. require(), a built-in function which allows the import of other modules

Red flag: The developer has no experience with, or does not understand the differences between, types of globals.

How to Hire Node.js Developers Most Effectively

The process of hiring a great Node.js developer is more than just interviewing with platform-related questions. It implies validating both technical and soft skills.

Out of all of the important topics that the soft skills review covers, a fundamental first step before searching is asking oneself, “Why am I looking for a skilled Node.js developer in the first place?” Be it igniting the existing development team with extra developer power, or mentoring peers and leading a technical transformation and excellence process, or kick-starting an MVP—answering this question greatly helps to define the values, traits, and experience of the ideal candidate.

Notwithstanding the goals of the soft skills review, the technical part comes into play at all times. Node.js development is an expertise that has some standard sets of tooling, patterns, and integral parts that are used over and over. The more experience a Node.js developer has using them for solving various problems and combining them in different ways, the more valuable such a developer becomes for development teams.

There’s definite value in the simple process of going through the fundamental topics of modern Node.js development flow, such as databases, third-party tools, DevOps, and the Node.js platform itself. Hearing answers to some pivotal development-, JavaScript-, and Node.js-specific questions can shed light on whether the developer is indeed as experienced and skilled as will be required for the goals that will be put before them.

 
 
 
 
Reference:
  1. https://www.journaldev.com/7462/node-js-architecture-single-threaded-event-loop (good for understanding nodje architechture)
  2. https://www.simplilearn.com/node-js-interview-questions-and-answers-article
  3.  https://career.guru99.com/top-25-interview-questions-on-node-js/
  4. https://www.tutorialspoint.com/nodejs/nodejs_interview_questions.htm (VVI for viva questin preperation)
  5. https://www.tutorialspoint.com/nodejs/nodejs_mock_test.htm?min=1&max=25 (important) 
  6.  http://upwork-test.pe.hu/node-js
  7. http://bodesktestanswers2013.blogspot.com/2016/06/upwork-nodejs-test-2016.html 
  8. https://codeburst.io/all-about-core-nodejs-part-1-b9f4b0a83278(Please read the doc for buffer : You want to change from one string encoding to another.)


/************************************************************

https://medium.com/@madasamy/15-javascript-concepts-that-every-nodejs-programmer-must-to-know-6894f5157cb7

(To understand apply/call/bind in javascript)

/*****************************************



Autoboxing and Unboxing

  Autoboxing  is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper cl...