VIM: Binding a shortcut

 All this time, I do not know how to create my own VIM Bindings. And yes, trying yourself is the only way you learn anything.

I want to explain what I have learnt on creating a vim shortcut, so you might get a good headstart.

The command I am going to explain is as below


map <C-b> :w\|!ruby spec/example_spec.rb <cr>

so

  • map: is like you are mapping <custome_key> <series of actions>
  • <C-b>: this stands for CTRL+b 

If you want to use Shift, Alt, Cmd(Mac), yes VIM have options for all of that.

```

S-...>		shift-key			*shift* *<S-*

<C-...>		control-key			*control* *ctrl* *<C-*

<M-...>		alt-key or meta-key		*meta* *alt* *<M-*

<A-...>		same as <M-...>			*<A-*

<D-...>		command-key (Macintosh only)	*<D-*
```
Vim documentation: intro (sourceforge.net)
  • Then :w\|!ruby spec/example_spec.rb<cr>
    • :w is save
    • \|: is like you are joining this command with with another action.
    • !ruby spec/example_spec.rb
      • ! is for invoking shell commands, for example give :!uptime, you will see what I am saying.
      • ruby spec/example_spec.rb, you know its ruby command executing the file.
      • <cr>: This carriage return equal to <Enter> key, with out this, your command will be loaded but to execute you have to press enter again. so adding <cr> at the end, will help executing your command.

Based on above understanding, lets say you have a python file like service.py, you want to execute it with a VIM binding, you can use below command
map <C-r> :w\|!python service.py <cr>
so on CTRL+r, I will be running my python program.

Hope it helps.
Thanks
Raja

Javascript: call vs bind vs apply

 Hello Everyone, 

I came across a snippet where code have .call() method.

Thought its been a while since I went through their understanding, via this article I am explaining with examples what call, bind and apply does in javascript.

Please read comments for understanding.

Hope it helps.

var obj = {
name: "Raja",
sayHello: function(args) {
console.log(`Hello ${this.name}, How are you doing `);
},
};

// call : Changing the context::this scope to the argument we are passing.
// normal

obj.sayHello() // Hello Raja, How are you doing ?
obj.sayHello.call({name : "Rajasekhar"}); // Hello Rajasekhar, How are you doing ?

var obj = {
name: "Raja",
sayHello: function(args) {
console.log(`Hello ${this.name}, How are you doing ? ${args}`);
},
};
// apply: same as call, we can also pass arguments as 2nd argument
obj.sayHello.apply({ name: "Rajasekhar" }, ["Testing"]); // Hello Rajasekhar, How are you doing ? Testing


// bind: Change function definition to a different context
// you can change the definition once

var obj = {
name: "Raja",
sayHello: function(args) {
console.log(`Hello ${this.name}, How are you doing ? ${args}`);
},
};

var contxt = {"name" : "ApplyContext:)"};
var newHello = obj.sayHello.bind(contxt);
newHello("Good Day!!!"); // Hello ApplyContext:), How are you doing ? Good Day!!!

GoLang: Quick gist on Difference between Marshal, Unmarshal, Encoder and Decoder

Summary: Marshal, Unmarshal and Encode, Decode

Summary: Marshal, Unmarshal and Encode, Decode

  • Marshal: Convert struct/map interface data into JSON.
  • Unmarshal: Convert JSON data into struct/map

If reading from a file involved, then you read it in []byte format. To read from a file

  • using os.Open open the file.

  • then read all the data using io.ReadAll method.

  • Encoder and Decoder kind of do reading/writing internally. More like a simplified version of Marshal and Unmarshal.

  • Encoder converts the struct/map into JSON and automatically writes into io.Writer

  • Decoder reads from io.Writer and convert the JSON data into struct/map interface.

If there is a byte slice to work with, use Marshal and Unmarshal. If there is an io.Writer or an io.Reader, use Encode and Decode.

Ref: https://blog.devgenius.io/to-unmarshal-or-to-decode-json-processing-in-go-explained-e92fab5b648f

GoLang: How to render a web template using Gin framework and render data from map ?

 I have struggled lot of time, to break this into working modal. So below code, is working example where you can have your data in a slice of URLs and render that data using Go Templates. 

I am giving a skeleton HTML template, not adding any thing extra. 

I believe the code itself is self explanatory, if any questions, please dont hesitate to ask.


main.go

package main

import (
"log"
"net/http"

"github.com/gin-gonic/gin"
)

type URL struct {
Name string
Url string
}

var URLs = []URL{
{Name: "google", Url: "google.com"},
{Name: "yahoo", Url: "yahoo.com"},
{Name: "gmail", Url: "gmail.com"},
}

func main() {

router := gin.Default()
router.LoadHTMLGlob("templates/*")
router.GET("/", bookmarks)
router.GET("/hello", func(c *gin.Context) {
c.HTML(http.StatusOK, "index.tmpl", gin.H{
"title": "Main website",
"Items": URLs,
})
})

log.Fatal(router.Run(":8000"))
}

func bookmarks(c *gin.Context) {
c.HTML(http.StatusOK, "index.tmpl", gin.H{
"title": "Bookmarks",
"URLs": URLs,
})
}

Go Templates will be stored inside templates directory, so create a templates directory where you have your main.go file and have that file as below 

index.tmpl


<html>
<h1>
{{ .title }}
</h1>
<body>
{{ range .URLs}}
{{.Name}}
{{.Url}}
{{end}}
</body>
</html>

Hope it helps.

Thank you.

Linux: How to scan remote host for open ports ?

Linux : How to find a remote port is opened or not ?

Helllo Team,

If you are trying to findout whether a remote server port is opened or closed, then there are so many ways. Here In this article I am posting on same using telnet and nc commands.

Using telnet

Telnet usually holds prompt, so to avoid that, we are using echo in front of the command.

> $ echo | telnet xxxxxx 22
Trying xxxxxx...
Connected to xxxxx.
Escape character is '^]'.
Connection closed by foreign host.

Using nc

with nc command, its direct.

> $ nc -z -v -u xxxxx 22
Connection to xxxx port 22 [udp/ssh] succeeded!

# -z: Just perform scans without sending any data to the respective service running on the given port.
# -v : Verbose
# -u: UDP packets, without this it will be default tcp.

Hope it helps. Thanks

ServiceNow: How to read the content of a text file from an incident record attachment

How to read the content of a text file from an incident record attachment:

 GlideSysAttachment API is used to handle attachments.

With this API,

  • we can copy attachment from one record to another
  • read the content of a attached file as text, base64 or content stream
  • write the content
  • read all attachments of a record and also we can delete any of the attachment of a record

var attachment = new GlideSysAttachment();
var incidentSysID = '136e85931bc8fc1037fc4263cc4bcb46';
var agr = attachment.getAttachments('incident', incidentSysID);
gs.info(agr.getRowCount());
while (agr.next()) {
var attachmentContent = attachment.getContent(agr);
gs.info('Attachment content: ' + attachmentContent);



Output:
x_67546_crusher: Attachment content: Vamshi Vemula 
Staff software Engineer

 

OS Internals: Interprocess Communication ( IPC)

ipc

Interprocess Communication ( IPC )

  • Interprocess communication allows a process to communicate with another process.

  • Communications can be one of two types

    • Between related process ( parent and child )
    • Between unrelated processes ( one or more different processes)
  • IPC can use

    • Pipes
    • First In First Out ( FIFO) - Queue
    • Message Queues
    • Shared Memory
    • Semaphores
    • Signals

Pipes

  • Pipes are half-duplex, they can only read or write a process but only in one direction,

  •  

First In, First Out (Named Pipes)

  • FIFO are also called as named pipes, and are half duplex as pipes.

  • when you create a pipe, to identify it, execute ls -l command to the pipe, you can see if its a pipe or not

In the above output prw-r--r-- - p denotes that its a pipe.

Shared Memory

  • shared memory is full duplex, either process can read and/or write.
  • most efficient type of IPC, it does not require any kernel intervention once the shared memory has been allocated/deallocated.
  • Required a program
  • Any number of processes can read and write to the same shared memory segment.
  • You can query shared memory with the ipcs command
  • Processes must manage shared memory
  • Process must protect shared memory being wirtten or race conditions will occur( if two process are trying to access same data at same time)

Message Queues

  • created by syscall
  • managed by kernel
  • kernel will delete the message from queue once it is read
  • each read and write creates a syscall to the kernel
  • the message queue helps eliminate the occurrences of race conditions but comes at the expense of performance due to the syscall interrupt(trap)
  • data will remain in the queue until it is read and once read its gone.

 

Semaphores

  • Semaphores are used to protect critical/common regions of memory shared between multiple processes.

  • So other process cant use this shared memory till the process that owned the memory releases it.

  • Semaphores are the atomic structures of operating systems

  • Two Types of semaphores:

    • Binary: Only two states 0 and 1, locked/unlocked, or available, unavailable etc
    • Counting Semaphores : Allow arbitrary resource counters
  • When a process 'allocates' a semaphore, it blocks the other processes from access until the first process issues a 'release' indicating it has completed its operation.

  • The kernel then makes the semaphore available again for allocation.

Signals

  • A signal is a notification of an event occurrence.

  • A signal is also know as a trap, or software interrupt.

  • if you perform 'kill -l' you can see list of killl siganls implemented in your kernel

    • for example in a linux machine

     

    • And in Mac,
  • Signals can be generated by a user, process or kernel
  • if its a process, it is supposed to be written to handle them
  • Certain signals numeric 9-15 cannot be handled by the process they will immediately cause termination of the process and cannot be blocked, these are called 'process crash-outs' ExL CTRL+C, which cant be blocked by the process and terminates the process.

 

POSIX standards now govern the use and definition of IPC constructs and added support to modern features like threads etc.