my net house

WAHEGURU….!

Courses to complete this Quarter

Understand Stack and Heap from the Ideology of C and C/C++

Writing Flow:
1. Introduction to working of Stack and Heap inside Memory .

2. How Stack Works.

3. How Heap Works.

4. Conclusion based on performance and Ease of use. ::

There are various parts which are responsible to make one complete set of memory which is responsible for Execution and life cycle of application  or process. We can also say that this process is unified either you are using ThreadPool or Process Pool. Whole memory is divided into major three parts, Stack, Heap, Code(Text), Global variables and Constant’s Section, As from the name of last two it can be concluded easily that these parts are responsible for storage of Global Variable and keeping the source code, Other two important parts left are Stack and Heap. Let’s talk about Stack in next Section.

 

Stack is container of one and many functions with the static memory allocated to it, All the memory to stack is allocated before the compile time and it remains same throughout the whole life cycle of application, if there comes more requirement of memory than the allocated one it becomes famous “Stack-over-flow. Main() function call sits on the bottom of the stack. It gets executed at the end of the Stack, All the other Function based on calls sit on each other  in the stack. All the local Variables are also stored in the Stack as well.

 

Heap is something different in terms of ideology from the stack, Where stack is all about occurring of function call  in the series with fixed memory size but in the case of Heap it is all Dynamic. When we need requirement of memory in the runtime without not fixed size heap is there for us. There are multiple ways we can use memory allocations in heap in C and C++. Some known methods are Malloc(), Calloc(), realloc() and free(). C++ is superset of C so all the mentioned functions can also be used in C++ as well, with each call of these functions we get Pointer to Memory block, with that Block one can store data. Make sure one this that in C and C++ memory allocation is not Dynamic so one has to Allocate and De-Allocate memory manually.

Apart from C and C++ there are many other languages those make substantial use of Stacks and Heaps, For example in Python most of the stuff is Stored on heap so  you can allocated data to it even on run time but when you use Generators() or Lazy-Iterators() those are framed on stack and with each continuous  call each functions free the space in the Stack, In the case of Go-lang  something very weird happens, Quoting from StackOverFlow-

It’s worth noting that the words “stack” and “heap” do not appear anywhere in the language spec. Your question is worded with “…is declared on the stack,” and “…declared on the heap,” but note that Go declaration syntax says nothing about stack or heap.

That technically makes the answer to all of your questions implementation dependent. In actuality of course, there is a stack (per goroutine!) and a heap and some things go on the stack and some on the heap. In some cases the compiler follows rigid rules (like “new always allocates on the heap”) and in others the compiler does “escape analysis” to decide if an object can live on the stack or if it must be allocated on the heap.

Source: https://stackoverflow.com/questions/10866195/stack-vs-heap-allocation-of-structs-in-go-and-how-they-relate-to-garbage-collec

 

Source for Stack and Heap of C/C++: https://www.youtube.com/watch?v=_8-ht2AKyH4

 

Note:* Overall  Performance and Consistency of the Application is based on smart use of both Stack and Heap. 

 

 

Dive into Closures in Go Programming.

First thing you will find out when you think About Closures, Either in Python or in Golang,
Point is Why would someone will ever use
the Closures insted of Regular Function and What impact will it to on my Code and Running o code,
Well Tat would be a Difiult Question to answer, One thing always matter is your taste of writing code and
how well you want to understand your logic and How well you can UNderstand the Flow-Control of your code
Why you should use Closure Functions?

When the inner function has to remember the state of the Outer functino then uou can use Closure functions, As many times
You will make Sure how good your inner functin is and how much you want to make access of your outer function only then you can
find out how much it is useful to make sure that all the functinos that your are using or gonig to be reuse can be closures as well.

package main

import (
“fmt”
)

func NormalFunc() { // this function has no Return Type and takes no input, It will just print String(“Hello world”)

fmt.Println(“Hello World!!!”)

}

func main() {

NormalFunc()

func(msg string) { // This function has also no Retrn type but will take string as input.
fmt.Println(msg)
}(“hello World”)
}


Now let’s Dive More into Closures!!

package main

import (
“fmt”
)

func NormalFunc() { // this function has no Return Type and takes no input, It will just print String(“Hello world”)

fmt.Println(“Hello World!!!”)

}

func NotNormalFunc() func(string) {
//msg := “Hello World”
return func(msg string) {
fmt.Println(msg)
}
}

func int_count() func() int {
i := 0
return func() int {
i++
//fmt.Println(i)
return i
}
}
func main() {

NormalFunc()
func(msg string) { // This function has also no Retrn type but will take string as input.
fmt.Println(msg)
}(“hello World”)
fmt.Println(“here we are Calling NOt-Normal Function”)
not_normal := NotNormalFunc()
not_normal(“hello-world”) // This part is so Sexy!!!
fmt.Println(“Now we are calling thing which is More Close to Closure.”)
output := int_count()
fmt.Println(output()) // Notice this Function call very Carefully!!
fmt.Println(output())
output2 := int_count()
fmt.Println(output2()) // Notice this Function call very Carefully!!
fmt.Println(output2())

}

Dive into Interfaces in Golang.

How to Think about interfaces in Golang.

1. Yo need to package multiple Functions into one Interface. That’s we also call Polymorphism as well.
2. Then the data on which you need to Apply those Operations Should be a Struct{}
3. Bingo! Now you know what are the interfaces.

Note* : Make sure the Funcitons You will be creating in the interaces shold be having Function Declaration like this:

func (u user) notify() {
fmt.Printf(“Sending User Email To %s\n”,
u.name,
u.email)
}

Where “user” is struct.

A dead Simple Explanation is as Follows:

package main

import "fmt"

// notifier is an interface that defines notification
// type behavior.
type notifier interface {
notify()
}

// user defines a user in the program.
type user struct {
name string
email string
}

// notify implements the notifier interface with a pointer receiver.
func (u user) notify() {
fmt.Printf("Sending User Email To %s\n",
u.name,
u.email)
}

func main() {

// Create a value of type User and send a notification.
u := user{"Bill", "bill@email.com"}
m := user{"Arshpreet", "arsh840@gmail.com"}
// Values of type user do not implement the interface because pointer
// receivers don't belong to the method set of a value.

u.notify()
m.notify()
}

Using Type Assertion For Interface. Why to use Type Assertion;

https://stackoverflow.com/questions/38816843/explain-type-assertions-in-go

package main

import "fmt"
import "math"

func main() {
shapes := []Shape{
Circle{1.0},
Square{1.772453},
Rectangle{5, 10},
Triangle{10, 4, 7},
}
for _, v := range shapes {
fmt.Println(v, "\tArea:", v.Area())
if t, ok := v.(Triangle); ok {
fmt.Println("Angles:", t.Angles())
}
}
}

type Shape interface {
Area() float64
}
type Circle struct {
Radius float64
}
type Triangle struct {
A, B, C float64 // lengths of the sides of a triangle.
}
type Rectangle struct {
A, B float64
}
type Square struct {
A float64
}

func (t Circle) Area() float64 {
return math.Pi * t.Radius * t.Radius
}

// Heron's Formula for the area of a triangle
func (t Triangle) Area() float64 {
p := (t.A + t.B + t.C) / 2.0 // perimeter half
return math.Sqrt(p * (p - t.A) * (p - t.B) * (p - t.C))
}
func (t Rectangle) Area() float64 {
return t.A * t.B
}

func (t Square) Area() float64 {
return t.A * t.A
}

func (t Circle) String() string {
return fmt.Sprint("Circle (Radius: ", t.Radius, ")")
}
func (t Triangle) String() string {
return fmt.Sprint("Triangle (Sides: ", t.A, ", ", t.B, ", ", t.C, ")")
}
func (t Rectangle) String() string {
return fmt.Sprint("Rectangle (Sides: ", t.A, ", ", t.B, ")")
}
func (t Square) String() string {
return fmt.Sprint("Square (Sides: ", t.A, ")")
}

func (t Triangle) Angles() []float64 {
return []float64{angle(t.B, t.C, t.A), angle(t.A, t.C, t.B), angle(t.A, t.B, t.C)}
}
func angle(a, b, c float64) float64 {
return math.Acos((a*a+b*b-c*c)/(2*a*b)) * 180.0 / math.Pi
}

Emty interaces are the Most Amazing thing you will Love about Golang, If you Come from Python Background.

package main

import "fmt"

func main() {

// fmt.Println can be called with values of any type.
fmt.Println("Hello, world")
fmt.Println(12345)
fmt.Println(3.14159)
fmt.Println(true)
var a interface{}
a = "hello"
fmt.Println("this is a", a)
a = 23453535
fmt.Println("this is a", a)
a = []int{2, 3, 5, 7, 11, 13}
fmt.Println("this is a", a)

}

Sample program to show the syntax and mechanics of type switches and the empty interface.

package main

import "fmt"

func main() {

// fmt.Println can be called with values of any type.
fmt.Println("Hello, world")
fmt.Println(12345)
fmt.Println(3.14159)
fmt.Println(true)

// How can we do the same?
myPrintln("Hello, world")
myPrintln(12345)
myPrintln(3.14159)
myPrintln(true)

}

func myPrintln(a interface{}) {
switch v := a.(type) {
case string:
fmt.Printf("Is string : type(%T) : value(%s)\n", v, v)
case int:
fmt.Printf("Is int : type(%T) : value(%d)\n", v, v)
case float64:
fmt.Printf("Is float64 : type(%T) : value(%f)\n", v, v)
default:
fmt.Printf("Is unknown : type(%T) : value(%v)\n", v, v)
}
}

Read Image RGB values using Golang

Using Go-Routine to call image reading multiple times.

package main

import (
“fmt”
“image”
“log”
“os”

// Package image/jpeg is not used explicitly in the code below,
// but is imported for its initialization side-effect, which allows
// image.Decode to understand JPEG formatted images. Uncomment these
// two lines to also understand GIF and PNG images:
// _ “image/gif”
// _ “image/png”
_ “image/jpeg”
)

func image_reader(c chan int) {

reader, err := os.Open(“interceptor.jpg”)
if err != nil {
log.Fatal(err)
}
defer reader.Close()

// reader := base64.NewDecoder(base64.StdEncoding, strings.NewReader(data))
m, _, err := image.Decode(reader)
if err != nil {
log.Fatal(err)
}
bounds := m.Bounds()

var histogram [16][4]int
for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
for x := bounds.Min.X; x >12][0]++
histogram[g>>12][1]++
histogram[b>>12][2]++
histogram[a>>12][3]++
}
}

// Print the results.
fmt.Printf(“%-14s %6s %6s %6s %6s\n”, “bin”, “red”, “green”, “blue”, “alpha”)
for i, x := range histogram {
c <- i
fmt.Printf("0x%04x-0x%04x: %6d %6d %6d %6d\n", i<<12, (i+1)<<12-1, x[0], x[1], x[2], x[3])
}

}

func main() {
c := make(chan int)
go image_reader(c)
x := <-c // receive from c
fmt.Println(x)
fmt.Println("all done from here as well")
}

 

Art of Concurrency in Golang…..Part2…(Some Pure Basics of Go-Routines, to Blow your mind.)

Some Pure Basics of Go-Routines, to Blow your mind like Dope.
When you can run Multiple Anonymous G-Routines. Each Go-Routine Will
Exist after Wait.done() Till the n wg.wait() for the main Thread Will hold the Program
After all Go-Routines will be Done Completly.
But for any call of Anonymous Function() Calling your Go-Rotine’s Calling will never be Synchronous!

// Sample program to show how to create goroutines and
// how the scheduler behaves.
package main

import (
“fmt”
“runtime”
“sync”
)

func init() {

// Allocate one logical processor for the scheduler to use.
runtime.GOMAXPROCS(1)
}

func main() {

// wg is used to manage concurrency.
var wg sync.WaitGroup
wg.Add(2)

fmt.Println(“Start Goroutines”)

// Create a goroutine from the lowercase function.
go func() {
lowercase()
wg.Done()
}()

// Create a goroutine from the uppercase function.
go func() {
uppercase()
wg.Done()
}()

// Wait for the goroutines to finish.
fmt.Println(“Waiting To Finish”)
wg.Wait()

fmt.Println(“\nTerminating Program”)
}

// lowercase displays the set of lowercase letters three times.
func lowercase() {

// Display the alphabet three times
for count := 0; count < 3; count++ {
for r := ‘a’; r <= ‘z’; r++ {
fmt.Printf(“%c “, r)
}
}
}

// uppercasea displays the set of uppercase letters three times.
func uppercase() {

// Display the alphabet three times
for count := 0; count < 3; count++ {
for r := ‘A’; r <= ‘Z’; r++ {
fmt.Println(“–“)
fmt.Printf(“%c “, r)
}
}
}

Art of Concurrency in Golang Part-1

There are multiple Ways to talk about Concurrency in Golang but I would only Go with Channels, Why?

Because it is Ridiculously Simple and Efficient Solution. To Do more and More Concurrency in GoLang you need two Channels, One would be Sender and other would be Receiver. To Achieve Concurrency all of yo need to do following tings as well:

  1. Create a Function that takes at least Channel as Argument.
  2. Do all the required Processes/Calculations and Send that Value to Channel-Argument.
    That’s IT!  Now run that Function as Go-Routine, Run as Mnay as Go-Rountines you want, Put inside For Loop if you are looking for Parallel-Execution of tings!!

Following Example is Ridiculously Simple we are calling sun() Multiple times and using only one Channel to Receive values from Go-Routines. ad when you get those results you can use any kind operations on those Channels as well.

package main

import “fmt”

func sum(a []int, c chan int) {
sum := 0
for _, v := range a {
sum += v
}
c <- sum // send sum to c
}

func main() {
a := []int{7, 2, 8, -9, 4, 0}

c := make(chan int)
go sum(a[:len(a)/2], c)
go sum(a[len(a)/2:], c)
x, y := <-c, <-c // receive from c

fmt.Println(x, y, x+y)
}

Note* : – There is no Return Statement in the above Function. 🙂 😉

Let's take to next approach now, What we will see now with Next implementation of Golang thing:

package main

import (
"fmt"
"sort"
)

func sum(a []int, c chan int) {
sum := 0
for _, v := range a {
sum += v
}
c <- sum // send sum to c
}

func largest(a []int, c chan int) {
sort.Ints(a)
fmt.Println(a[len(a)-1])
c <- a[len(a)-1]
}

func main() {
a := []int{7, 2, 8, -9, 4, 0}

c := make(chan int)
go sum(a[:len(a)/2], c)
go sum(a[len(a)/2:], c)
go largest(a, c)
x, y, z := <-c, <-c, <-c // receive from c
fmt.Println(x, y, x+y)
fmt.Println("this is largest number", z)

}

Buffered Channels: 

When you want to limit the Receiving Value of Channels. You can Create Bufered Channels.

package main

import "fmt"

func main() {
    c := make(chan int, 2)
    c <- 1
    c <- 2
    fmt.Println(<-c)
    fmt.Println(<-c)
}

When you have Spin one Function/GO-Routine Multiple times by taking care of the Things like Dead-Lock and Getting the Results in the Synchronous Form you can go with kind of Following code.

Note* We are able to give capacity to Channel and sing that Capacity Go Routine can be Run Multiple Times to make sure that all the Channels are Running as per the Requirements.

Use Of “range{}” is important for the Channel.  

package main

import (
“fmt”
)

func fibonacci(n int, c chan int) {
x, y := 0, 1
for i := 0; i < n; i++ {
c <- x
x, y = y, x+y
}
close(c)
}

func main() {
c := make(chan int, 1)
fmt.Println("this is channel", c)
fmt.Println("this is Capacitty of channel", cap(c))
go fibonacci(cap(c), c)
for i := range c {
fmt.Println(i)
}
}

 

Create a Ridiculously Simple FileServer in Golang

Having light weight tool like Goalng in your ToolChain which is As easy as to Adapt like Python and Powerful than C or C++ you get to play with every aspect of  computer-Science.

You just need two Files, one is server.go and other would be client.go

In the server.go we will open connection on particular port to accept the connections, Most of the capabilities are inside the “net” package provided by Golang.
All you need to know that how to open connection and how to Create buffer size and how to write that buffer into the connection, All you need to look for few docs
for net package and you are great to go with one of your first FileServer of Golang.


package main

import (
“fmt”
“io”
“net”
“os”
“strconv”
)

//Define the size of how big the chunks of data will be send each time
const BUFFERSIZE = 1024

func main() {
//Create a TCP listener on localhost with porth 27001
server, err := net.Listen(“tcp”, “localhost:27001”)
if err != nil {
fmt.Println(“Error listetning: “, err)
os.Exit(1)
}
defer server.Close()
fmt.Println(“Server started! Waiting for connections…”)
//Spawn a new goroutine whenever a client connects
//for {
connection, err := server.Accept()
if err != nil {
fmt.Println(“Error: “, err)
os.Exit(1)
}
fmt.Println(“Client Connected”)
//go sendFileToClient(connection)
//sendFileToClient(connection)

defer connection.Close()
//Open the file that needs to be send to the client
file, err := os.Open(“dummyfile.dat”)
if err != nil {
fmt.Println(err)
return
}
defer file.Close()
//Get the filename and filesize
fileInfo, err := file.Stat()
if err != nil {
fmt.Println(err)
return
}
fileSize := fillString(strconv.FormatInt(fileInfo.Size(), 10), 10)
fileName := fillString(fileInfo.Name(), 64)
//Send the file header first so the client knows the filename and how long it has to read the incomming file
fmt.Println(“Sending filename and filesize!”)
//Write first 10 bytes to client telling them the filesize
connection.Write([]byte(fileSize))
//Write 64 bytes to client containing the filename
connection.Write([]byte(fileName))
//Initialize a buffer for reading parts of the file in
sendBuffer := make([]byte, BUFFERSIZE)
//Start sending the file to the client
fmt.Println(“Start sending file!”)
for {
_, err = file.Read(sendBuffer)
if err == io.EOF {
//End of file reached, break out of for loop
break
}
connection.Write(sendBuffer)
}
fmt.Println(“File has been sent, closing connection!”)
//}
}

//This function is to ‘fill’
func fillString(retunString string, toLength int) string {
for {
lengtString := len(retunString)
if lengtString < toLength {
retunString = retunString + ":"
continue
}
break
}
return retunString
}

Note:
Fill String Method: Fill String Method has good amount of significance, Each time When Server and Client code will be able to communicate
with each other one need to look for “Exact amount of file Size and FileName should be received to client, Only then we can do good amount of Sync between both the Ends”

Now let’s have closer look with Golang client to find out how to receive file from server, Which is quite simple, Now we have Buffered file size and that we will red from
connection, We have file name in Byte string as well, which we will also read from server and create the file of same name,,once reading is finished we will just save thatByte string into the file and good to go with all the things.

package main

import (
“fmt”
“io”
“net”
“os”
“strconv”
“strings”
)

//Define that the binairy data of the file will be sent 1024 bytes at a time
const BUFFERSIZE = 1024

func main() {
connection, err := net.Dial(“tcp”, “localhost:27001”)
if err != nil {
panic(err)
}
defer connection.Close()
fmt.Println(“Connected to server, start receiving the file name and file size”)
//Create buffer to read in the name and size of the file
bufferFileName := make([]byte, 64)
bufferFileSize := make([]byte, 10)

//Get the filesize
connection.Read(bufferFileSize)
//Strip the ‘:’ from the received size, convert it to a int64
fileSize, _ := strconv.ParseInt(strings.Trim(string(bufferFileSize), “:”), 10, 64) // Look carefully for 10 and 64 here. We have max of 10 bytes of fileSize and then we will convert string to int64

//Get the filename
connection.Read(bufferFileName)
//Strip the ‘:’ once again but from the received file name now
fileName := strings.Trim(string(bufferFileName), “:”)

newFile, err := os.Create(fileName)
if err != nil {
panic(err)
}
defer newFile.Close()
//Create a variable to store in the total amount of data that we received already
var receivedBytes int64

//Start writing in the file
for {
if (fileSize – receivedBytes) < BUFFERSIZE {
io.CopyN(newFile, connection, (fileSize – receivedBytes))
//Empty the remaining bytes that we don't need from the network buffer
connection.Read(make([]byte, (receivedBytes+BUFFERSIZE)-fileSize))
//We are done writing the file, break out of the loop
break
}
io.CopyN(newFile, connection, BUFFERSIZE)
//Increment the counter
receivedBytes += BUFFERSIZE
}
fmt.Println("Received file completely!")
}

 

Now in the above server.go you need to make Client requests Asynchronous, So let's make Go-Routine.

package main

import (
"fmt"
"io"
"net"
"os"
"strconv"
)

//Define the size of how big the chunks of data will be send each time
const BUFFERSIZE = 1024

func main() {
//Create a TCP listener on localhost with porth 27001
server, err := net.Listen("tcp", "localhost:27001")
if err != nil {
fmt.Println("Error listetning: ", err)
os.Exit(1)
}
defer server.Close()
fmt.Println("Server started! Waiting for connections…")
//Spawn a new goroutine whenever a client connects
for {
connection, err := server.Accept()
if err != nil {
fmt.Println("Error: ", err)
os.Exit(1)
}
fmt.Println("Client connected")
go sendFileToClient(connection)
}

}

//This function is to 'fill'
func fillString(retunString string, toLength int) string {
for {
lengtString := len(retunString)
if lengtString < toLength {
retunString = retunString + ":"
continue
}
break
}
return retunString
}

func sendFileToClient(connection net.Conn) {
fmt.Println("A client has connected!")
defer connection.Close()
//Open the file that needs to be send to the client
file, err := os.Open("dummyfile.dat")
if err != nil {
fmt.Println(err)
return
}
defer file.Close()
//Get the filename and filesize
fileInfo, err := file.Stat()
if err != nil {
fmt.Println(err)
return
}
//fileSize := strconv.FormatInt(fileInfo.Size(), 10)
fileSize := fillString(strconv.FormatInt(fileInfo.Size(), 10), 10)
//fileName := fileInfo.Name()
fileName := fillString(fileInfo.Name(), 64)
//Write first 10 bytes to client telling them the filesize
connection.Write([]byte(fileSize))
//Write 64 bytes to client containing the filename
connection.Write([]byte(fileName))
//Initialize a buffer for reading parts of the file in
sendBuffer := make([]byte, BUFFERSIZE)
//Start sending the file to the client
fmt.Println("Start sending file!")
for {
_, err = file.Read(sendBuffer)
if err == io.EOF {
//End of file reached, break out of for loop
break
}
connection.Write(sendBuffer)
}
fmt.Println("File has been sent, closing connection!")
return
}
 

Look for the function sendFileToClient() where we have went through Separate Process to write filesize, Filename and filebuffer to connection. One more thing to look carefully for the following code:


for {
connection, err := server.Accept()
if err != nil {
fmt.Println("Error: ", err)
os.Exit(1)
}
fmt.Println("Client connected")
go sendFileToClient(connection)
}

This is infinite “for loop” so for any client request and each time Go routine will be fired up. That’s it! Stay Tuned for more Fun!! and More Go!!

Raise yourself and you!

Most of time it is so important one Need to go deep inside ourselves and look for the things which is also called  Self Discovery, Meditation and Spiritual experience. Few people also reference it as Spiritual-Science and Meta-Physics.

I might not be big fan of things Which really don’t comes with certain kind of Equation, That is dominant Engineering Student’s mind which is super Curious and Contradicting.

Few days Ago I was reading/watching lot of stuff about Alpha-Male, Personality Traits, EQ vs IQ, Consciousness and much more, On the way I read/listen following books:

1. INTJ: Understanding your Personality Type
2. Spark: The revolutionary New Science of Exercise
3. No More Mr. Nice guy
4. How to Think Like Leonardo Da VInci
5. INFJ 101
6. The way to Superior Man

Almost all above books falls in the category of Self-Development, You all might like such kind of books or path to self-Development.

There is a very good website called: https://www.16personalities.com/. One can find out inner traits of his her personality in this website and open up new ways to live up life in General. stay tuned for more consciousness related posts as well.

Python and Pomodoro

Hacking things are not just attitude but now it seems like way of life. Interesting things are happening all over the  world and one can’t just sit around and look into stuff on the INTERNET. There are many ways one can hack into his/her brain and get most out of it. I just want to get bit more productive so I would be able to get more time out of the work and concentrate more on traveling as well. You can also follow the method being used in the image below:

But such methods are still under heavy development. All you must need to do or change is body activity and Pomodoro is always helpful for me to d that.

To do small Pomodoro Activity you can use following of My script/package to make new changes at your workplace.

 

%d bloggers like this: