Search This Blog

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()