Javascript Interview Questions(Part-4)

JavaScript Coding interview questions with solutions:-

Question1:-

You would like to set a password for a bank account. However, there are three restrictions on the format of the password:

it has to contain only alphanumerical characters (az, AZ, 09);
there should be an even number of letters;
there should be an odd number of digits.
You are given a string S consisting of N characters. String S can be divided into words by splitting it at, and removing, the spaces. The goal is to choose the longest word that is a valid password. You can assume that if there are K spaces in string S then there are exactly K + 1 words.

For example, given "test 5 a0A pass007 ?xy1", there are five words and three of them are valid passwords: "5", "a0A" and "pass007". Thus the longest password is "pass007" and its length is 7. Note that neither "test" nor "?xy1" is a valid password, because "?" is not an alphanumerical character and "test" contains an even number of digits (zero).

Write a function:

int solution(char *S);
that, given a non-empty string S consisting of N characters, returns the length of the longest word from the string that is a valid password. If there is no such word, your function should return 1.

For example, given S = "test 5 a0A pass007 ?xy1", your function should return 7, as explained above.

Assume that:

N is an integer within the range [1..200];
string S consists only of printable ASCII characters and spaces.
In your solution, focus on correctness. The performance of your solution will not be the focus of the assessment.


Solution1:-

function solution(S) {
// write your code in JavaScript (Node.js 6.4.0)
var pwds = S.split(" ");
var pwdLen = -1;
pwds.forEach(function(pwd){
if(pwd.match(/^[a-zA-Z0-9]*$/)){
if(pwd.length%2!=1)
return;
var chrCnt = pwd.match(/[a-zA-Z]/g || []).length;
if(chrCnt%2!=0)
return;
if (pwd.length > pwdLen)
pwdLen = pwd.length;
}
});
return pwdLen;
}

Question2:-
Given four integers, display the maximum time possible in 24 hour format HH:MM. For example, if you are give A = 1, B = 9, C = 9, D = 2 then output should be 19:29. Max time can be 23:59 and min time can be 00:00.

If it is not possible to construct 24 hour time then return error. For example, given A = 1, B = 9, C = 7, D = 9 an error should be returned since minimum time represented by these integers is 17:99 which is “NOT POSSIBLE”?

Solution2:-

function solution(A, B, C, D) {
var arr = [];
var digit = [];
var timeString = "";
//create array from given numbers
arr.push(A);
arr.push(B);
arr.push(C);
arr.push(D);
digit[0] = findMax(arr,2);
digit[1] = digit[0]==2?findMax(arr,3):findMax(arr,9);
digit[2] = findMax(arr,5);
digit[3] = findMax(arr, 9);
//final number
if(digit[0] ==-1 ||digit[1] ==-1||digit[2] ==-1||digit[3] ==-1){
return "NOT POSSIBLE";
}
timeString = digit[0]+""+digit[1]+":"+digit[2]+""+digit[3];

return timeString;

}
//finding the less than equal number and return it
function findMax(arr, find){
if(arr.length!=4)
{
return -1;
}
var numToFind = -1;
var indexToRemove = -1;
//iterate arrary
for(var i = 0; i < arr.length;i++){
if(arr[i] <= find)
{
if(arr[i]> numToFind)
{
numToFind = arr[i];
indexToRemove =i;
}
}
}
if (indexToRemove == -1)
return -1;
arr[indexToRemove] = -1;
return numToFind;
}

Question3:-Given DOM tree I need to find the maximum depth of the nested ul/ol tags.
Example:-

<ul>
<li>Item:
<ol>
<li>Point:
<div>
<ul>
<li>elem1</li>
</ul>
</div>
</li>
</ol>
</li>
<li>elem2</li>
</ul>
<ul>
<li>simple list1</li>
</ul>
<ul>
</ul>
The depth would be 3

Solution3:-

function solution() {

var len, max_depth=0;
$('li:not(:has(ol)):not(:has(ul))').each(function(){
len = $(this).parents('ul,ol').length;
if(len > max_depth)
max_depth =len;
});
//console.log(max_depth);
return max_depth;
}

More Interview Questions

Vue.js npm run dev error with vue-cli

Problem:- On running the npm run dev, command after installing vue-cli, following error is thrown?
Starting dev server…
events.js:160
      throw er; // Unhandled ‘error’ event
      ^

Error: listen EADDRINUSE :::8080
    at Object.exports._errnoException (util.js:1026:11)
    at exports._exceptionWithHostPort (util.js:1049:20)
    at Server._listen2 (net.js:1262:14)
    at listen (net.js:1298:10)
    at Server.listen (net.js:1376:9)….

Solution:-
From above error we can get an hint “listen EADDRINUSE :::8080”,
issue is our port 8080 is already used, thus vue server is NOT getting started.

Easy solution, just change the port in /config/index.js file

  dev: {
    env: require(‘./dev.env’),
    port: 8082,
    autoOpenBrowser: true, 

Re-run the app again and it’ll launch without any error on new port

vue.js launching page

Keep learning and Keep sharing.

Install oracle free edition with IDE on Linux machine?

Problem:- How to install the latest free edition of oracle database with IDE?
Solution:-
A) First we’ll install oracle database and then install the sql developer ide.

Steps:-
Follow the below steps to install the 11g database(latest when this post was written)
Download the latest oracle version for ubuntu

  1. Unzip using the command:
    unzip oracle-xe-11.2.0-1.0.x86_64.rpm.zip 
  2. Install required packages using the command:
    sudo apt-get install alien libaio1 unixodbc
  3. Convert RPM package format to DEB package format (that is used by Ubuntu) using the command:
    sudo alien --scripts -d oracle-xe-11.2.0-1.0.x86_64.rpm
  4. Create the required chkconfig script using the command::
    sudo pico /sbin/chkconfig

    The pico text editor is started and the commands are shown at the bottom of the screen. Now copy and paste the following into the file and save:


    #!/bin/bash
    # Oracle 11gR2 XE installer chkconfig hack for Ubuntu
    file=/etc/init.d/oracle-xe
    if [[ ! `tail -n1 $file | grep INIT` ]]; then
    echo >> $file
    echo '### BEGIN INIT INFO' >> $file
    echo '# Provides: OracleXE' >> $file
    echo '# Required-Start: $remote_fs $syslog' >> $file
    echo '# Required-Stop: $remote_fs $syslog' >> $file
    echo '# Default-Start: 2 3 4 5' >> $file
    echo '# Default-Stop: 0 1 6' >> $file
    echo '# Short-Description: Oracle 11g Express Edition' >> $file
    echo '### END INIT INFO' >> $file
    fi
    update-rc.d oracle-xe defaults 80 01
  5. Change the permission of the chkconfig file using the command:
    sudo chmod 755 /sbin/chkconfig  
  6. Set kernel parameters. Oracle 11gR2 XE requires additional kernel parameters which you need to set using the command:
    sudo pico /etc/sysctl.d/60-oracle.conf

    Copy the following into the file and save:

    # Oracle 11g XE kernel parameters  
    fs.file-max=6815744
    net.ipv4.ip_local_port_range=9000 65000
    kernel.sem=250 32000 100 128
    kernel.shmmax=536870912

    Verify the change using the command:

    sudo cat /etc/sysctl.d/60-oracle.conf 

    You should see what you entered earlier. Now load the kernel parameters:

    sudo service procps start

    Verify the new parameters are loaded using:

    sudo sysctl -q fs.file-max

    You should see the file-max value that you entered earlier.

  7. Set up /dev/shm mount point for Oracle. Create the following file using the command:
    sudo pico /etc/rc2.d/S01shm_load

    Copy the following into the file and save.

    #!/bin/sh
    case "$1" in
    start) mkdir /var/lock/subsys 2>/dev/null
    touch /var/lock/subsys/listener
    rm /dev/shm 2>/dev/null
    mkdir /dev/shm 2>/dev/null
    mount -t tmpfs shmfs -o size=2048m /dev/shm ;;
    *) echo error
    exit 1 ;;
    esac

    Change the permissions of the file using the command:

    sudo chmod 755 /etc/rc2.d/S01shm_load
  8. [This step was not included in the screencast, but you should do it.] Execute the following commands:
    sudo ln -s /usr/bin/awk /bin/awk 
    sudo mkdir /var/lock/subsys
    sudo touch /var/lock/subsys/listener
  9. REBOOT your Ubuntu VM.
  10. Install the oracle DBMS using the command:
    sudo dpkg --install oracle-xe_11.2.0-2_amd64.deb
  11. Configure Oracle using the command:
    sudo /etc/init.d/oracle-xe configure 

    Enter the following information:

    • A valid HTTP port for the Oracle Application Express (the default is 8080)
    • A valid port for the Oracle database listener (the default is 1521)
    • A password for the SYS and SYSTEM administrative user accounts
    • Confirm password for SYS and SYSTEM administrative user accounts
    • Whether you want the database to start automatically when the computer starts (next reboot).
  12. Setup environment variables by editting your .bashrc file:
    pico ~/.bashrc

    Add the following lines to the end of the file:

    export ORACLE_HOME=/u01/app/oracle/product/11.2.0/xe
    export ORACLE_SID=XE
    export NLS_LANG=`$ORACLE_HOME/bin/nls_lang.sh`
    export ORACLE_BASE=/u01/app/oracle
    export LD_LIBRARY_PATH=$ORACLE_HOME/lib:$LD_LIBRARY_PATH
    export PATH=$ORACLE_HOME/bin:$PATH

    Load the changes by executing your profile:

    . ~/.profile
  13. Start the Oracle 11gR2 XE:
    sudo service oracle-xe start
  14. Add user YOURUSERNAME to group dba using the command
    sudo usermod -a -G dba YOURUSERNAME
  15. Start the Oracle XE 11gR2 server using the command:
    sudo service oracle-xe start

    This step is most likely not necessary, but I am documenting the command here anyway.

  16. Start command line shell as the system admin using the command:
    sqlplus sys as sysdba

    Enter the password that you gave while configuring Oracle earlier. You will now be placed in a SQL environment that only understands SQL commands.

  17. Create a regular user account in Oracle using the SQL command:
    create user USERNAME identified by PASSWORD;

    Replace USERNAME and PASSWORD with the username and password of your choice. Please remember this username and password.


  18. Grant privileges to the user account using the SQL command:
    grant connect, resource to USERNAME;

    Replace USERNAME and PASSWORD with the username and password of your choice. Please remember this username and password.

  19. Exit the sys admin shell using the SQL command:
    exit;
  20. Start the commandline shell as a regular user using the command:
    sqlplus

    You will be prompted for a username and password. Once authenticated, you will be able to type in the standard SQL commands learned in class.

B) After our successfull installation of oracle, we are going to configure sql developer IDE.

Download the latest sql developer edition
1.sudo alien –scripts -d sqldeveloper-version.noarch.rpm
A file named sqldeveloper_version_all.deb will be generated. To run this file, execute the following statement:

2.sudo dpkg –install sqldeveloper_version_all.deb
Create a .sqldeveloper directory in your home folder:

3.sudo mkdir /home/.sqldeveloper/
Run SQL Developer from the terminal.

4.sudo /opt/sqldeveloper/sqldeveloper.sh
5.Enter the path for java installed on your system
How to find path by using the command whereis jvm
generally its installed inside /usr/lib/jvm/java-version

$ sudo alien --scripts -d sqldeveloper-4.2.0.17.089.1709-1.noarch.rpm
[sudo] password for user:
sqldeveloper_4.2.0.17.089.1709-2_all.deb generated
user@test:~/Documents/Northstar/oracle$ sudo dpkg --install sqldeveloper_4.2.0.17.089.1709-2_all.deb
Selecting previously unselected package sqldeveloper.
(Reading database ... 277479 files and directories currently installed.)
Preparing to unpack sqldeveloper_4.2.0.17.089.1709-2_all.deb ...
Unpacking sqldeveloper (4.2.0.17.089.1709-2) ...
Setting up sqldeveloper (4.2.0.17.089.1709-2) ...
Processing triggers for libc-bin (2.23-0ubuntu7) ...
user@test:~/Documents/test/oracle$ sudo mkdir /home/.sqldeveloper/ms@test:~/Documents/test/oracle$ sudo /opt/sqldeveloper/sqldeveloper.sh

Oracle SQL Developer
Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.

Type the full pathname of a JDK installation (or Ctrl-C to quit), the path will be stored in /home/mandeep/.sqldeveloper/4.2.0/product.conf
/usr/lib/jvm/java-1.8.0-openjdk-amd64

6.Accept the default settings for any window pop ups

sql developer pop window during installation

7. All done, check the first look of SQL developer to work with oracle.

Oracle sql developer ide
Note:-
Login as sys user using terminal:-
 sqlplus / as sysdba , enter username and password > execute the queries

Reference documents:-
http://www2.hawaii.edu/~lipyeow/ics321/2014fall/installoracle11g.html

Practical issues and solutions for working with JMeter – Part3

Scenario1:-
How i can extract jmeter response into a variable?
Solution:-
We can achieve it in different ways, we used Json Path PostProcessor
in our example, 
Lets say our response json is in the given format:-

{
"sensorId": "123456bc-25e8-48e1-8abe-b24efe461501",
"sensorName": "waterTemp",
"serialNumber": "4345633352864906",
"status": "ENABLED"
}

Now to extract sensorId based on the “sensorNumber” we can extract it in following manner. 

extract data from json response


Scenario2:-
How we can add response values from jmeter to external file ?
Solution:-
We can achieve it in different ways, we used Bean Sampler
in our example, 
Lets say we want to save the above SENSOR_ID value into external file,

sensorid= vars.get("SENSOR_ID");
//Adding logs to jmeter
log.info("sensor id is"+sensorid);
// Pass true incase to append file
fileName = new FileOutputStream("/home/path/performance/Tests/result.csv", true);
p = new PrintStream(fileName);
this.interpreter.setOut(p);
print(topic);
fileName.close()

Write jmeter results to csv file
Learn More?

Change layout of default signup form of MailChimp?

Problem:- Mailchimp is good for creating signup forms, but but..how i can change the layout of signup forms and make them look fancy?

The greatest mistake you can make in life is to be continually fearing you will make one.”Elbert Hubbard

Pr-requisites:-
1.Create account with mailchimp(as of now its free for 2000 subscribers)
2.Login with new account, create a list and create a signup form(we selected the default general form)

creating list in mailchimp
 create signup form in mailchimp
Our starting default form will look something like :-
Default form in mailchimp

But we want it to be like as below:-

designing fancy form using mailchimp

Solution:-
Step1:- Copy all the default code generated by mailchimp under “Embedded forms”
Embedded forms in mailchimp
Step2:-Replace the “form” tag code of your local fancy form with mailchimp form code
 signup code from mailchimp

Step3:- Copy the id attribute of input tags of mailchimp and add that to your fancy form, repeat the above steps for all the fields say firstname,lastname and email.

So easy isn’t it? thus we retained our fancy form but with the functionality of mailchimp.

Keep learning and Keep Sharing 

Learn more 
How to install wordpress using Bitnami

Installing wordpress on Linux using Bitnami

We already installed the individual LAMP(apache server, mysql server, php) stack for working with wordpress on linux(ubuntu) environment.

You don’t have to see the whole staircase. Just take the first step 



In case we want to make our life bit easier, we can install the above LAMP stack with one push button using Bitnami.

How to install?

1. Open the bitnami.com > applications > wordpress > local install > download the package(which is by default selected as linux, based on the OS configuration of your PC)

local install bitnami linux


2.Change the permission on downloaded .run file as below
chmod a+x ./filename.run 
launch the run file as ./filename.run
 giving permission on .run file in linux
3.Select the default options through the installer package

installation of bitnami for linux
Note:- Do remember the username and password that are used in the setup.(It’ll be used for wp-admin login to wordpress)

admin acccount for wordpress in bitnami
4.After installation is complete >finish and  browser will launch the bitnami page on default port 127.0.0.1:8080

5.Click on the link to access wordpress or open the URL :- 127.0.0.1:8080/wordpress/
 access wordpress on bitnami
6.You can configure the default port, check the phpmyadmin from the manager window.
manager for bitnami on linux

Do more configurations:-
1.Open the location where bitnami is installed, wp-bitnami/apps/wordpress/htdocs/
This is the place where all the wordpress files are present, edit this to create new themes, plugins, change configurations.

For Example1, 
a)open the htdocs folder in code editor lets say sublime
b)wp-content/ — create a new folder say child and with file style.css
c)write the below comments into style.css file
/*
Theme Name: Child of Twenty Seventeen
Template: twentyseventeen
*/ 

working with htdocs file in wordpress

d)Check that corresponding theme is shown in appearances/themes from URL of the wordpress

child theme in wordpress created using style.css

Example2:-Place new theme/plugins downloaded from internet, 
htdocs/wp-content/plugins/ —place it here


Keep Learning and keep exploring :)

Enable auto save feature in Sublime editor

Problem:- How to add auto-save functionality in Sublime-Text?

Solution:-

Using auto-save package.

How to install this?
1)Open package Control in sublime (Ctrl+Shift+p)

open install package control sublime
2)Search and select install option 

3)Search auto-save and select it 

4)Enable auto-save

Press Command + Shift + P again and search for AutoSave. Here, there are 3 options:(select the one that you want to enable)

  • Toggle AutoSave: all files
  • Toggle AutoSave: current file only
  • Toggle AutoSave Backup: current file only
    enable auto save in sublime editor

Install and Configure MySql on Linux?

Frank Herbert
Installation for mysql is similar to installing apache server and php on Ubuntu. 
Step1:- Open terminal window and type the below command(install mysql-server)

sudo apt-get install mysql-server


Note:-

Adding root password in installing mysql
  • Add root password in the dialog box after installation. 
  • Incase any pop up comes during installation just accept the default and continue the installation process.

Step2:- Install workbench(IDE) to work with MySql
sudo apt-get install mysql-workbench

Step3:- Start mysql workbench
a)Type the below command in terminal
mysql-workbench 
b)Open the default localhost instance and add “root” password.

Launch localhost in mysql


Note:- You can add workbench to launcher and open it from terminal as well from launcher.

Step4:- Create schema(database) in workbench.
a)Databases > New
b)Add schema name, select collation value say “utf8” > Apply > Close

Add new schema in workbench

c)Now we can create our tables inside the database.

So now we have Apache, MySQL, and PHP running on Linux, the complete LAMP stack. 

 

Install and configure PHP on ubuntu?

“Without new experiences, something inside of us sleeps. The sleeper must awaken.” Frank HerbertFrank Herbert t

Step1:- Open terminal window and type the below command(install php)

sudo apt-get install php libapache2-mod-php php-mcrypt php-mysql


We have used extra parameters for configuring php to use apache server that we already installed and also to connect with mysql. So we dont do any configurations manually 

Step2:- Verify the installation of PHP
We need to create sample php script inside the root of apache server and open it in the apache server
a) cd to apache root path, cd /var/www/html/
b) Create test.php file, sudo nano test.php
c)Add the basic phpinfo function call into file, save and exit (ctrl+x > y > enter) the nano editor
create php script inside apache root folder

d) Start apache server (sudo apachectl start) and check the test.php file(open localhost/test.php) 

launch php file in server

Step3:- Configure php settings 
a)Lets say we want to enable php logs, we need to open php.ini file 
sudo nano /etc/php/7.0/php.ini
b)Search display_errors in php.ini file and turn it to on
ctrl+w(for searching in nano)

change php.ini file
c)Restart the apache server
sudo apachectl restart
d)Check that settings are changed by checking the browser

php.ini file configured in server