Search This Blog

2023/12/06

Javascript Interview Question:Matching Parenthesis


Problem Statement:

Given a string s containing just the characters '(', ')', '{', '}', '['
and ']',determine if the input string is valid.

An input string is valid if:

1) Open brackets must be closed by the same type of brackets.
2) Open brackets must be closed in the correct order.
3) Every close bracket has a corresponding open bracket of the same type.

Example 1:
Input: s = "()"
Output: true
Example 2:

Input: s = "()[]{}"
Output: true
Example 3:

Input: s = "(]"
Output: false

Constraints:
1 <= s.length <= 104
s consists of parentheses only '()[]{}'.


Solution:
var str = "([{{([{([])}])}}]) [({})]";

function wellFormedBrackets(str) {
var circular = 0;
var rectangular = 0;
var curly = 0;

var brackets = {
"[": "]",
"(": ")",
"{": "}",
};

var lastOpening = [];
var lastOpeningChar = "";

for (var char of str) {
if (char == "[" || char == "(" || char == "{") {
lastOpening.push(char);

if (char == "[") {
rectangular++;
}
if (char == "{") {
curly++;
}
if (char == "(") {
circular++;
}
}

if (char == "]" || char == ")" || char == "}") {
lastOpeningChar = lastOpening.pop();
console.log("one:", lastOpeningChar);
console.log("two", char);

if (lastOpeningChar == undefined) {
console.log("No Opening brace");
return false;
} else {
if (brackets[lastOpeningChar] == char) {
if (char == "]") {
rectangular--;
}
if (char == "}") {
curly--;
}
if (char == ")") {
circular--;
}
} else {
console.log("Bracket are not properly nexted");
return false;
}
}
}
}

if (circular + rectangular + curly == 0) {
return true;
} else {
return false;
}
}

var result = wellFormedBrackets(str);
console.log("Result is", result);

2023/10/14

Linux : How to run game in DosBox

 First we need to install DosBox,I am using ubuntu

so i can install using following command

sudo apt install dosbox


After that Download Dos Game


Head over to https://www.myabandonware.com/

Select Platform then in Dos section download game which probably will be zip file.

Now create folder in /home/user as Dosbox and unzip the downloaded file to it

So Your game will be in /home/user/Dosbox

Now lauch DosBox and run follwing command


>mount c: ~/Dosbox

now to change Drive run

>C:

NOW cd into your game folder and find exe and run that

>path/exec.exe

you should able to run the dos game

2023/10/13

Javascript : Create an array with sequential integer values

For creation of an array with sequential integer values lets
consider following code

Code:
const n=10
const arr1 = Array.from(Array(n).keys());
console.log(arr1)

Output:
[
0, 1, 2, 3, 4,
5, 6, 7, 8, 9
]
Explantion:
Lets break down statement
Array.from(Array(n).keys())
into its parts.

1) Array(n): Creates a new array with a length of n. This array initially
contains empty slots (sparse array), meaning it has n slots but no
defined elements.

2) .keys(): Accesses the keys (indices) of the array. This returns an
iterator that generates sequential integer keys starting from 0 up
to n - 1.

3) Array.from(...): Converts the iterator (keys) into an array. The
Array.from method takes an iterable or array-like object and creates a
new array from its elements or values. In this case, it converts the
iterator of keys into an array containing integers from 0 to n - 1.
Code:
const n=10
let arr2 = new Array(n).fill().map((_,index)=> index)
console.log(arr2)

Output:
[
0, 1, 2, 3, 4,
5, 6, 7, 8, 9
]

Explanation:
The code above creates a new array of length n, fills it with undefined
values, and then uses the map method to transform each element to its
index value.
Note:
Instead of statement
let arr2 = new Array(n).fill().map((_,index)=> index)
if we put
let arr2 = new Array(n).map((_,index)=> index)
we get output as [ <10 empty items> ].

Observation:
Consider following code.
Code:
const n=10
let iterator = Array(n).keys()
for(var m of iterator ){
console.log(m)
}
Output:
0
1
2
3
4
5
6
7
8
9
Explanation:
Array(n).keys() method to create an iterator for generating sequential
integer keys from 0 to n - 1, and then iterates through this iterator
using a for...of

2023/10/12

Ruby On Rail:CRUD Operations

 First Create application as follows



rails new apiStack --api --database=postgresql

In controller folder create api folder inside api folder create v1 folder

generate new controller for product

rails g controller api/v1/products index show --no-helper --no-assets --no-template-engine --no-test-framework


generate product model

rails g model product name:string brand:string price:string description:string --no-helper --no-assets --no-template-engine --no-test-framework

in db/seeds.rb add following


Product.create([
{
name:"Quite Comfort 35",
brand:"Bose",
price:"$279.99",
description:"Wireless Bluetooth HeadPhone,Noise Cancelling,with Alexa voice control-black"
}
])

create & run mibgration

rake db:create
rake db:migrate

save seed data

rake db:seed


edit product controller as

class Api::V1::ProductsController < ApplicationController
def index
products = Product.all
render json:products,status:200
end

def create
product = Product.new(
name:params[:name],
brand:params[:brand],
price:params[:price],
description:params[:description])

if product.save
render json:product,status:200
else
render json:{error:"Error creating product"}
end
end

def show
product = Product.find_by(id:params[:id])
if product
render json:product,status:200
else
render json:{error:"Product not found!"}
end
end

def update
product = Product.find_by(id:params[:id])

product.name = params[:name]
product.brand = params[:brand]
product.price = params[:price]
product.description = params[:description]

if product.save
render json:product,status:200
else
render json:{error:"Error Updating product"}
end
end

def destroy
if Product.destroy(params[:id])
render json:{message:"Deleted Product"}
else
render json:{error:"Error Deleting product"}
end
end

def by_brand_name
products = Product.where(brand:params[:name])
if products
render json:products,status:200
else
render json:{error:"Product not found!"}
end
end
end


In config/routes.rb edit as following

Rails.application.routes.draw do
namespace :api do
namespace :v1 do
resources:products,only:[:index,:show,:create,:update,:destroy]
get "products/brand/:name",to:"products#by_brand_name"
end
end
# Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html

# Reveal health status on /up that returns 200 if the app boots with no exceptions, otherwise 500.
# Can be used by load balancers and uptime monitors to verify that the app is live.
get "up" => "rails/health#show", as: :rails_health_check

# Defines the root path route ("/")
# root "posts#index"
end


then run application as


rails s


Test API CAlls as following
a) GET ALL
curl --location 'http://localhost:3001/api/v1/products/'

b) Create Product
curl --location 'http://localhost:3001/api/v1/products' \
--header 'Content-Type: application/json' \
--data ' {
"name": "32 Inch LCD",
"brand": "TOSHIBA",
"price": "$500.00 USD",
"description": "Amazing LCD"
}'

3) Find By Id
curl --location 'http://localhost:3001/api/v1/products/2'

4) Update Product

curl --location --request PUT 'http://localhost:3001/api/v1/products/1' \
--header 'Content-Type: application/json' \
--data '{
"name": "PS4.0",
"brand": "Sony.0",
"price": "$500.00 USD",
"description": "NNextGen Gaming Console"
}'

5) Delete Product
curl --location --request DELETE 'http://localhost:3001/api/v1/products/3'

4) Find By brand
curl --location 'http://localhost:3001/api/v1/products/brand/Bose'


GitHub URL:https://github.com/gitsangramdesai/ror-crud

Gambas:Mysql Connectivity

 Form:




Here I created three text fields TxtFirstName,TxtLastName,TxtEmail & added GridView1 to form

also has three labels LblFirstName,LblLastName,LblEmail

Code :


' Gambas class file

Public $Con As New Connection

Public Procedure Connect()

$Con.Close() ' Close the connection

$Con.Type = "mysql" ' Type of connection

$Con.Host = "localhost" ' Name of the server

$Con.Login = "root" ' User's name for the connection

$Con.Port = "3306" ' Port to use in the connection, usually 3306

$Con.Name = "playground" ' Name of the database we want to use

$Con.Password = "sangram#81" ' User's password

$Con.Open() ' Open the connection

End

Public Sub BtnSave_Click()
Dim $Result As Result
Dim $firstName As String
Dim $lastName As String
Dim $email As String

$firstName = TxtFirstName.Text
$lastName = TxtLastName.Text
$email = TxtEmail.Text

Dim $Query As String

$Query = "INSERT INTO Person(firstName,lastName,email) values('" & $firstName & "','" & $lastName & "','" & $email & "');"

Connect()

$Result = FMain.$Con.Exec($Query)
Message.Info("Record Saved Successfully")

TxtEmail.Clear()
TxtFirstName.Clear()
TxtLastName.Clear()

LoadAll()
Finally ' Always executed, even if a error is raised. Warning: FINALLY must come before CATCH!
FMain.$Con.Close()

Catch ' Executed only if there is an error
Message.Info("Unable to save record")

End



Public Sub LoadAll()

Dim $Result As Result

Dim $Field As ResultField

Dim $rowCount As Integer = 0

Dim $Query As String

$Query = "SELECT * FROM Person;"

Connect()

$Result = FMain.$Con.Exec($Query)

'define layout

'define the gridview layout

GridView1.header = GridView.Horizontal
GridView1.grid = True
GridView1.Rows.count = $Result.Count + 1
GridView1.Columns.count = 4

'column headers
GridView1.Columns[0].text = "Id"
GridView1.Columns[1].text = "First Name"
GridView1.Columns[2].text = "Last Name"
GridView1.Columns[3].text = "Email"

'column width
GridView1.Columns[0].width = 100
GridView1.Columns[1].width = 100
GridView1.Columns[2].width = 100
GridView1.Columns[3].width = 100

For Each $Result
GridView1[$rowCount, 0].Text = $Result!id
GridView1[$rowCount, 1].Text = $Result!firstName
GridView1[$rowCount, 2].Text = $Result!lastName
GridView1[$rowCount, 3].Text = $Result!email

$rowCount = $rowCount + 1
Next

End

Public Sub Form_Open()
LoadAll()
End

My Code is Available at:
https://github.com/gitsangramdesai/gambas-mysql



2023/10/11

Javascript Interview Question:Reverse Order the words in sentence

let str = "Today is Friday";
str = ' ' + str
var length = str.length;
var newStr=''

var last=length
for (let i = length - 1; i >= 0; i--) {
if(str[i]==' '){
newStr = newStr + ' ' + str.substring(i,last).trim()
last = i
}
}

console.log(newStr.trim())

Output:
Friday is Today


2023/10/04

Javascript Interview Question:Pyramid of asterisk (*)

var maxStar = 9

for (let i = 1; i < 10; i++) {
let half = maxStar-i
var totalSpaces = ' '.repeat(half)
process.stdout.write(totalSpaces)
for (let j = 0; j < i; j++) {
process.stdout.write('* ')
}
process.stdout.write('\n')
}

Output:
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *

2023/10/03

MySQL: get size of Database & Table

 Get Size of Database in Mysql


SELECT table_schema "DB Name",
ROUND(SUM(data_length + index_length) / 1024 / 1024, 1) "DB Size in MB"
FROM information_schema.tables
GROUP BY table_schema;


Size of Table in Mysql

SELECT
table_name AS `Table`,
round(((data_length + index_length) / 1024 / 1024), 2) `Size in MB`
FROM information_schema.TABLES
WHERE table_schema = "MatrimonyDb"
AND table_name = "Country";

2023/10/01

Python: read xls

 import xlrd

book = xlrd.open_workbook("location.xls")

sh = book.sheet_by_index(0)

for rx in range(sh.nrows):
for col in range(sh.ncols):
print(sh.cell_value(rx, col) + ' ', end='')
print('\n',end='')

# pip install xlrd

Python:read xlsx

 import pandas as pd

# read by default 1st sheet of an excel file
df = pd.read_excel('name.xlsx')
rows = len(df.index)
cols = len(df.columns)

header = list(df.columns.values)

for head in range(len(header)):
print(header[head] + " ",end=" ")

print()

for row in range(rows):
for col in range(cols):
print(df.iat[row, col] + " ",end="")
print()



# pip install pandas
# pip install openpyxl

Python:read csv file

 import csv

with open('giant.csv', mode ='r') as file:
csvFile = csv.reader(file)
for lines in csvFile:
print(lines)

Python:read ods file

 import pandas as pd


df = pd.read_excel('namelocation.ods', engine='odf')

rows = len(df.index)
cols = len(df.columns)

header = list(df.columns.values)

for head in range(len(header)):
print(header[head] + " ",end=" ")

print()

for row in range(rows):
for col in range(cols):
print(df.iat[row, col] + " ",end="")
print()


# pip install pandas
# pip install odfpy

Python:SQLAlchemy Example

 import sqlalchemy as db

from sqlalchemy.orm import sessionmaker

engine = db.create_engine("mysql+mysqlconnector://root:sangram#81@localhost/typeorm")
conn = engine.connect()
metadata = db.MetaData()

Student = db.Table('Student', metadata,
db.Column('Id', db.Integer(),primary_key=True),
db.Column('Name', db.String(255), nullable=False),
db.Column('Major', db.String(255), default="Math"),
db.Column('Pass', db.Boolean(), default=True)
)

StudentCity = db.Table('StudentCity', metadata,
db.Column('Id', db.Integer(),primary_key=True),
db.Column('City', db.String(255), nullable=False),
db.Column('StudentId',db.ForeignKey("Student.Id"))
)

# metadata.create_all(engine)

# query = db.insert(StudentCity)
# StudentCity_values_list = [
# {'Id':'1', 'City':'Mumbai',"StudentId":1},
# {'Id':'2', 'City':'Delhi',"StudentId":2},
# {'Id':'3', 'City':'Pune',"StudentId":3},
# {'Id':'4', 'City':'Banglore',"StudentId":4},
# ]
# StudentCity_Result = conn.execute(query,StudentCity_values_list)
# conn.commit()

# query = db.insert(Student).values(Id=1, Name='Matthew', Major="English", Pass=True)
# Result = conn.execute(query)

# query = db.insert(Student)
# values_list = [{'Id':'2', 'Name':'Nisha', 'Major':"Science", 'Pass':False},
# {'Id':'3', 'Name':'Natasha', 'Major':"Math", 'Pass':True},
# {'Id':'4', 'Name':'Ben', 'Major':"English", 'Pass':False}]
# Result = conn.execute(query,values_list)
# conn.commit()

# output = conn.execute(db.select(Student))
# rows = output.fetchall()

# output = conn.execute(db.text("SELECT * FROM Student"))
# rows = output.fetchall()



# query = Student.select().where(Student.columns.Major == 'English')
# output = conn.execute(query)
# rows = output.fetchall()


# query = Student.select().where(db.and_(Student.columns.Major == 'English', Student.columns.Pass != True))
# output = conn.execute(query)
# rows = output.fetchall()


# output = conn.execute(db.select(Student.columns.Major.distinct()))
# rows = output.fetchall()


# output = conn.execute(db.select(db.func.sum(Student.columns.Id),Student.columns.Major).group_by(Student.columns.Major))
# rows = output.fetchall()

# rows = output.fetchall()
# headers= output.keys()

# for header in headers:
# print(header + " ",end="")

# print()

# for row in rows:
# for col in row:
# print(str(col) + " ",end="")
# print()

Session = sessionmaker(bind=engine)
session = Session()

inner_join_query = session.query(Student.columns.Name, StudentCity.columns.City,Student.columns.Id).select_from(Student).join(StudentCity, Student.columns.Id == StudentCity.columns.StudentId)

header_ = inner_join_query.statement.columns.keys()

for header in header_:
print(header + " ",end="")

print()


for row in inner_join_query:
for col in row:
print(str(col) + " ",end="")
print()

session.close()



2023/09/28

Node.js:Buffer Interview Questions

 What is a Node.js Buffer?


A Node.js Buffer is a built-in object in Node.js used to
represent binary data directly in memory. It is a raw memory
allocation outside the JavaScript heap that allows Node.js to
handle binary data efficiently, which is crucial for tasks like
working with files, network streams, and other data sources
where binary data is involved.

How can you create a Buffer in Node.js?

You can create a Buffer in Node.js using one of the following methods:

Buffer.from(data): Creates a Buffer from an array, array-like object, or string.
Buffer.alloc(size): Allocates a new, zero-filled Buffer of the specified size.
Buffer.allocUnsafe(size): Allocates a new Buffer of the specified size, but it
may contain uninitialized memory.
Buffer.allocUnsafeSlow(size): Similar to Buffer.allocUnsafe(size), but slower.

How do you read data from a Buffer?

You can read data from a Buffer using methods like readUInt8,
readUInt16LE, readUInt16BE, readUInt32LE, readUInt32BE,
and similar methods for different data types. For example:

const buffer = Buffer.from([0x01, 0x02, 0x03, 0x04]);
const value = buffer.readUInt16LE(0); // Read a 16-bit integer in little-endian format from offset 0

How do you write data to a Buffer?

You can write data to a Buffer using methods like writeUInt8,
writeUInt16LE, writeUInt16BE, writeUInt32LE, writeUInt32BE,
and similar methods for different data types. For example:

const buffer = Buffer.alloc(4);
buffer.writeUInt16LE(0x0102, 0); // Write a 16-bit integer in little-endian format to offset 0


What are the differences between Buffer.from and Buffer.alloc?

Buffer.from creates a new Buffer and initializes it with the provided data (e.g., an array or string).
Buffer.alloc creates a new Buffer and initializes it with zeros.
Buffer.from is used when you want to create a Buffer from existing data,
whereas Buffer.alloc is used when you want to create an empty Buffer with a specific size.

How can you convert a Buffer to a string in Node.js?

Answer: You can convert a Buffer to a string in Node.js using the toString method. For example:

const buffer = Buffer.from('Hello, World!');
const str = buffer.toString('utf8'); // Convert the Buffer to a UTF-8 encoded string


What is the purpose of Buffer.allocUnsafe and Buffer.allocUnsafeSlow?

Answer:

Buffer.allocUnsafe allocates a new Buffer of the specified size but does not initialize its contents.
It is faster than Buffer.alloc because it doesn't fill the buffer with zeros,
but you should be careful when using it as the buffer may contain random data.

Buffer.allocUnsafeSlow is similar to Buffer.allocUnsafe, but it may be slower
and should be used only in cases where Buffer.allocUnsafe is not available.

How can you check the length of a Buffer?

Answer: You can check the length of a Buffer using the length property or the byteLength method:

const buffer = Buffer.from('Hello');
const length1 = buffer.length; // 5
const length2 = buffer.byteLength; // 5

Node.js:Buffers in node.js

 create buffer from string


var buf = Buffer.from('abc');
console.log(buf.toString());


create empty buffer of length 15

var buf = Buffer.alloc(15);
console.log(buf);

return size of buffer

var buf = Buffer.from('abc');
console.log(buf.length);


join three buffer object to one

var buf1 = Buffer.from('a');
var buf2 = Buffer.from('b');
var buf3 = Buffer.from('c');
var arr = [buf1, buf2, buf3];

var buf = Buffer.concat(arr);
console.log(buf.toString());


A Buffer cannot be resized.

Max Buffer size :

var buffer = require('buffer')
console.log(buffer.constants.MAX_LENGTH)

it is less on 32 bit machine & more on 64 bit machines.

Checking wheather object is buffer

var buf1 = Buffer.from('a');
var buf2 = "sa"
console.log(Buffer.isBuffer(buf1));
console.log(Buffer.isBuffer(buf2));


Return the number of bytes in the string "abc":

var len3 = Buffer.byteLength('abc');
console.log(len3);


Check the length of a buffer object:

var buf = Buffer.alloc(15);
var len1 = Buffer.byteLength(buf);
var len2 = buf.length;
console.log(len1);
console.log(len2);


return index from where the searched value is starting. It returns -1 if the value is not present in the buffer.

const buffer = Buffer.from('GeeksforGeeks: A computer science portal');
const output = buffer.indexOf('computer');
console.log(output);

output:
17


const buffer = Buffer.from('geeks community');
const output = buffer.indexOf(101);
const output1 = buffer.indexOf('geeks community');
const output2 = buffer.indexOf('com',7);//start searching at position 7 starting from 0

console.log(output);
console.log(output1);
console.log(output2);

output:
0
1
-1

check if two buffers are equal

var buf1 = Buffer.from('Hi');
var buf2 = Buffer.from('Hi');
console.log(buf1.equals(buf2));

output:
true


subarray:

const buf = Buffer.from('GeeksforGeeks', 'ascii');
console.log("Original buffer is: " + buf);
cropped_buf = buf.subarray(5, 10);
console.log("Cropped buffer is: " + cropped_buf);
cropped_buf[0] = 70; // F
cropped_buf[1] = 79; // O
cropped_buf[2] = 82; // R
console.log("Cropped buffer after modification is: " + cropped_buf);
console.log("Original buffer after modification is: " + buf);

output:

Original buffer is: GeeksforGeeks
Cropped buffer is: forGe
Cropped buffer after modification is: FORGe
Original buffer after modification is: GeeksFORGeeks



another example with negative index

const buf = Buffer.from('GeeksforGeeks', 'ascii');
console.log("Original buffer is: " + buf);

cropped_buf = buf.subarray(-12, -1);
console.log("Cropped buffer is:" + cropped_buf);
cropped_buf = buf.subarray(-10, -5);
console.log("Cropped buffer is: " + cropped_buf);
cropped_buf = buf.subarray();
console.log("Cropped buffer is: " + cropped_buf);


output:
Original buffer is: GeeksforGeeks
Cropped buffer is:eeksforGeek
Cropped buffer is: ksfor
Cropped buffer is: GeeksforGeeks


include or not

const buffer = Buffer.from('Geek One');
console.log(buffer.includes('Geek'));

output:
true

another example
const buffer = Buffer.from('GeeksforGeeks: A computer science portal');
const output = buffer.includes('Geek', 15);
console.log(output);

output:
false


copy method:

let buffer2 = Buffer.from('for');
let buffer1 = Buffer.from('GeeksandGeeks');

buffer2.copy(buffer1, 5,0)
console.log(buffer1.toString());

output:
GeeksforGeeks


compare:
return 0,-1 or 1

const buffer1 = Buffer.from('Geek');
const buffer2 = Buffer.from('Geek');
const op = Buffer.compare(buffer1, buffer2);
console.log(op);

output:
0


sort buffer array:
const buffers = [
Buffer.from('A', 'utf8'),
Buffer.from('C', 'utf8'),
Buffer.from('B', 'utf8')
];

buffers.sort(Buffer.compare);


compare on buffer object

const buffer1 = Buffer.from('GeeksOne');
const buffer2 = Buffer.from('GeekTwo');
let op = buffer1.compare(buffer2, 4);
let op1 = buffer1.compare(buffer2, 0, 7, 5);
console.log(op);
console.log(op1);

output:
-1
1


another example:
const buffer1 = Buffer.from("Geeks");
const buffer2 = Buffer.from("GeeksFor");

let op1 = buffer1.compare(buffer2, 0, 5);
console.log(op1);

output:
0