Sunday, August 30, 2020

Merging two sorted arrays - Big O (n+m) time complexity

 Problem : 

Merge the two sorted arrays.

Edge case : 

Array can empty

Arrays can be in different size



let getMaxLength = (input1,input2) => {
if(input1.length < input2.length) {
return input2.length;
}else {
return input1.length;
}
}
function mergeSortedArrays(input1,input2){
result = [];
let x = 0;
let y = 0;
if(!input1 || input1.length == 0){
return input2;
}
if(!input2 || input2.length == 0){
return input1;
}

let maxLength = getMaxLength(input1,input2);
while(x < input1.length && y < input2.length){
//find first smallest element between two arrays
if(input1[x] < input2[y]){
// x is smaller
result.push(input1[x++]);
}else{
// y is smaller
result.push(input2[y++]);
}
}
// add remaining array elements into result array
while(x < input1.length){
result.push(input1[x++]);
}

while(y < input2.length){
result.push(input2[y++]);
}

return result;
}

function print(result) {
for(index in result){
console.log(result[index]);
}
}
a = [1,5,7];
b = [2,6,31,44];

//print(mergeSortedArrays(a,b));
//print(mergeSortedArrays([],b));
print(mergeSortedArrays(a,[]));
//print(mergeSortedArrays([],[]));




Saturday, August 15, 2020

Basic Python jupyter notebook

 

Variable

a = 10
c = 10.2
b = False
d = 'A'
e = "Apple"

print(a)
print(b)
print(c)
print(d)
print(e)
10
False
10.2
A
Apple

Operator & Precedence

result = 10 + 20
print(result)

result = 1 + 1 * 10 + 30
print(result)

result = 1 + 2 * 10 + 30
print(result)

result = (1 + 1) * (10 + 30)
print(result)
30
41
51
80

Function

def delivery_check(pincode):
    print("delivery to ",pincode)

delivery_check("600100")
delivery to  600100

Main function

def start():
    print("Hello from main function")
    
if __name__ == "__main__":
    start()
Hello from main function

Class, Object and Method

class Order:
    def __init__(self,id,pincode):
        self.id = id
        self.pincode = pincode
    def display(self):
        text = "Order : {id}, to : {pincode}"
        print(text.format(id = self.id,pincode=self.pincode))

order = Order(101,600100)
order.display()
Order : 101, to : 600100

Inheritence

class NonVegOrder(Order):
    def __init__(self,id,pincode):
        super().__init__(id,pincode)
        
order = NonVegOrder(101,600100)
order.display()
Order : 101, to : 600100

String & Array

name = "Test"
char_name = ['p','y','t','h','o','n']
name = ""
new_name = name.join(char_name)
print(new_name)
print(name)
python
Test

List & Loop

char_name = ['p','y','t','h','o','n']
name = ""
for c in char_name:
    name = name + c
    
print(name)    
['p', 'y', 't', 'h', 'o', 'n', '.']

List

names = list(("Ranjith","Raj"))
print("Names length : ",len(names))
names.append('D')
print(names)
Names length :  2
['Ranjith', 'Raj', 'D']

Array

import array as a

digits = a.array("i",[1,2,3])
for d in digits:
    print(d)
1
2
3

if & else

check = False
if check :
    print("Its true")
else:
    print("Its false")
Its false

Dictionary

map = {
    "java": 100,
    "rust" : 200,
    "python": 300
}
print(map["java"])
100

Read input

number = int(input("Enter input"))
if number < 10:
    print("Number less than 10")
else:
    print("Number greater than or equal to 10")
Enter input23
Number greater than or equal to 10

Import

import time


print(time.ctime(time.time()))
    
Sat Aug 15 20:24:50 2020

Threading

import threading

def printme(name):
    print(name)

thread = threading.Thread(printme("first"))
thread.start()
first

Multi threading

import threading
import time


class MyThread(threading.Thread):
    def __init__(self, name,count,sleep_time):
        threading.Thread.__init__(self)
        self.name = name
        self.count = count
        self.sleep_time = sleep_time
        
    def run(self):
        for i in range(0, self.count):
            print(self.name,i)
            time.sleep(self.sleep_time)


thread1 = MyThread("Fast",5,0.5)
thread2 = MyThread("Slow",5,1)
thread1.start()
thread2.start()
print("Main thread done")
Fast 0
Slow 0
Main thread done
Fast 1
Slow 1
Fast 2
Fast 3
Slow 2
Fast 4
Slow 3
Slow 4

Thread join

import threading
import time


class MyThread(threading.Thread):
    def __init__(self, name,count,sleep_time):
        threading.Thread.__init__(self)
        self.name = name
        self.count = count
        self.sleep_time = sleep_time
        
    def run(self):
        for i in range(0, self.count):
            print(self.name,i)
            time.sleep(self.sleep_time)


thread1 = MyThread("Fast",5,0.5)
thread2 = MyThread("Slow",5,1)
thread1.start()
thread2.start()
thread1.join() # Current Main thread joined to thread1 to complete
thread2.join() # Current Main thread joined to thread2 to complete 
print("Main thread done")
FastSlow 0
 0
Fast 1
SlowFast 1
 2
Fast 3
Slow 2
Fast 4
Main thread done
Slow 3
Slow 4

Logging

import logging

logger = logging.getLogger('MyApplication')
logger.info('This is to showcase info level logging in python')
level = "Warning"
logger.info('This is to showcase %s level logging in python',level)
21:08:57: This is to showcase info level logging in python
21:08:57: This is to showcase Warning level logging in python

JSON

import json

order = '{"id" : 10,"user" : "ranjith"}'

order_json = json.loads(order) # Convert string to json
print(order_json['id'])
print(json.dumps(order_json)) # Convert json to string
10
{"id": 10, "user": "ranjith"}

Friday, August 14, 2020

Training session - Python - Class and Object

Order Domain

class Order:
    def __init__(self,count,deliveryAddress,phonenumber,landmark1,buyerName,specialNotes,status):
        self.count = count
        self.deliveryAddress = deliveryAddress
        self.phonenumber = phonenumber
        self.landmark1 = landmark1
        self.buyerName = buyerName
        self.specialNotes = specialNotes
        self.status = status

def processOrder(order):
    if order.count > 15:
        print("Limit exceeded")
    else:
        print(order.count,"Burger","+ Toping")
        print("delivered to ",order.deliveryAddress)
        print("phonenumber:  ",order.phonenumber)

burgerOrder = Order(10121123123123122176,"cdm",230,"mainroad","ran","","ordered")
processOrder(burgerOrder)

Book Domain

class Book:
    def __init__(self,index,page):
        self.index = index
        self.page = page
    def read(self):
        txt = "Index : {index}, Page :  {number:.2f}"
        return txt.format(number = page.get_number(),index = index.get_content())
    
class Page:
    def __init__(self,number):
        self.number = number
    def get_number(self):
        return self.number
        
class Index:
    def __init__(self,content):
        self.content = content
    def get_content(self):
        return self.content
        
index = Index("Holly")
page = Page(10121123123123123123)
book = Book(index,page)
print(book.read())

Thursday, May 28, 2020

Where are innovators?

There was a sizeable crowd gathered in a temple to attend the festival. The wireless mic surprised me during the priest's talk when everyone was praying and chanting. I was deeply looking at the mic (microphone). It stopped working after a certain distance. That priest scolded the service operator and took the wired mic instead. He was covering the total distance with the wired mic while instructing people not to rush.

Later I found a television remote operating with a suitable distance so I tried to focus the IR light towards the roof and it worked. But I never wondered of FM radio, which was in my home even before my birth. I did not pay much attention to that as I took it for granted. The things what surprised me are new, and I have seen the change happening during my time that solved the essential problems of the modern world.

That was the story during the late 90s but now (at the time of writing this blog) I could see 2 out of 10 people (guessing by seeing) having wearable devices, the wireless chargers and many other gadgets are available even in the low-cost market.

Are we respecting these innovators? We know who invented the electric bulb and the computer from our textbooks. But do we recognise the efforts of the inventor of Bluetooth, wireless drone, or at least wireless mouse? These products are all marketed quickly with top competition among companies to gain patents and sue against another company. Entrepreneur shadows are burying the efforts of inventors and innovators. Most people are not free to think. Here, gigantic businesses are exploiting the creators and making profits out of it. The businessman decides the target and deadline for someone’s thinking. Parents should seed innovation thoughts in the kid’s mind from the core, not during the crop. Please refrain from asking children to follow a system. We cared about only the cost of the product, not the value. Following the other person’s success formula is not the right way to groom children.

A foremost step is to identify the problem. Ask yourself; why I want to be like someone, how can I succeed with the man inside me.

A lot of time problems have been given to you and finding the solution is easy as we are taught to bring the solution with the existing pattern. The regular teaching method is educating us to bring the solution, but not helping us to identify our own problem. I see a lot of educated people struggling to handle life after marriage. It’s because no one taught how to handle a new relationship. Perhaps it is not practical to foresee it.

Think and act on one goal at a time produces a significant result. I am not going against parallelism, but too much multitasking kills productivity unless you don’t practice to it.

A mentor shared with me a statement that “if you wish to innovate first, build it for you”.
You could get many pre-defined solutions that suited better for your need, but what’s the enormous deal to cook your own food. Solve your issue by yourself rather than blaming others or expecting a solution from someone else.

I like the trend DIY. I see a few of my sisters decorated their homes with their own products like a pen stand, pillow cover, embroidered towel. We could easily ignore these ideas by saying what is the use of it. But sometimes another side of the same habit saves us. My mom prepares papadam, dehydrated brinjal during summer and that serves us the superb meal even in the rainy season. That the starting point of innovation zone, we enter.

Do something yourself, if you are crazy about innovation.

Rust process to connect ssh via os command

During my rust learning, I wonder to make some application out of my learning. So, thought to make ssh based terminal application so I can use it my daily use.

As I would like to start a small piece of the snippet to make the actual logic to prototype. I began to identify the ssh frameworks that I can utilize in my application.  During that exploration time, I found a shortcut which is easy to achieve at every first level.

The idea is to use the ssh command available in the os. This code is very simple and attracts the rust beginners.

This snippet calling the ssh terminal command and passing the required argument
that is actually my username and server host.
use std::process::Command;

fn main() {
    let username = "<Fillup>";
    let hostname = "<Fillup>";
    let cmd_out = Command::new("ssh")
        .arg(format!("{}@{}",username,hostname))
        .output();

    match cmd_out {
        Ok(o) => {
            let l = format!(
                "{}{}",
                String::from_utf8_lossy(&o.stdout),
                String::from_utf8_lossy(&o.stderr)
            );
            if o.status.success() {
                println!("{}", l);
            }
        }
        Err(e) => {
            println!("{}", e);
        }
    }
}

So the question is still open, did I complete the SSH application?

Now it is in WIP, once completed let you know.

Wednesday, May 27, 2020

Barebone react js Application

Keep these below files in a webserver or create live-server, node express to keep this application running
npm install global live-server
public/index.html
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>my wish list</title>
    </head>
    <body>
        <div id="app"></div>
        <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
        <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
        <script src="/scripts/app.js"></script>
    </body>
</html>
/public/scripts/app.js
let template = React.createElement('h1', null, 'Welcome to react');
appRoot = document.getElementById("app");
ReactDOM.render(template, appRoot);

Monday, May 25, 2020

Make your Mac folder shortcuts into terminal command

Every day all you geeks are typing 'cd' command more than like any another command.
As you want to navigate to move almost nuke and corner of your file system.
But sometimes you often go to a specific folder, maybe that is Downloads or you specific workspace folder.


~ cd ~/Downloads
➜  Downloads
 
As this is very near to home folder and shot, it is easy to navigate but what if you have a project-specific folder that has a 100 character length path. Alias is useful to set shortcut command for your folders.
Edit your shell source file by doing the following command in terminal
 
vi ~/.zshrc

or
 
vi ~/.bash_profile

Update below content into the bottom of your source file,
 
#Alias to my Download folder 
alias downloads='cd ~/Downloads'

Save the profile file by doing vi save (escape + :wq!)
 
➜  downloads

Now type downloads in your terminal hit enter. You are into the Downloads folder.

Troubleshoot:
 Restart the terminal if not working, or check the typo to your profile settings

Below command can be useful to add the current directory to the alias list, as it avoids to open the
bash_profile to update in the vi editor.

 Replace the <name> with the actual value. after the edit, there should not any angle brackets in the terminal command.


➜  echo "alias <name>='cd $PWD'" | cat >> ~/.bash_profile 

Note: As this is appended command, please make sure that you execute it once per alias name.

Merging two sorted arrays - Big O (n+m) time complexity

 Problem :  Merge the two sorted arrays. Edge case :  Array can empty Arrays can be in different size let getMaxLength = ( input1 , input...