Tuesday 10 September 2019

PowerShell script to connect to connect to remote

We need to install the Posh-SSH module

Here is the script written using Posh-SSH module

param(
    $Computername = "xxxxx",
    $Username = "xxxx",
    $Password = "xxx",
    $Port = 22,
    $KeyfilePath = ""
    # $AutoUpdateFingerprint = $False
)
# function This-FingerPrintUpdate(){
#     Write-Output "calling fingerprint fun.."
#     if($AutoUpdateFingerprint)
#     { Remove-SSHTrustedHost $Computername }
# }
function This-GetSSHCommandOutput(){
# Create new session and execute the command given
$SecPasswd   = ConvertTo-SecureString $Password -AsPlainText -Force
$Credentials = New-Object System.Management.Automation.PSCredential ($Username, $SecPasswd)
    $Session = New-SSHSession -Computername $Computername -Credential $Credentials -Port $Port -Acceptkey
    $Output = (Invoke-SSHCommand -Command 'export PATH=/home/xxx/.rbenv/shims:/home/agwebadmin/.rbenv/bin:/home/xxx/bin:/home/agwebadmin/.local/bin:/home/xxx/.rbenv/shims:/home/xx/.rbenv/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin; export RAILS_ENV=production; ruby -v; cd current/hotDesks; rake sunspot:solr:reindex' -SSHSession $Session).Output
    # Remove the session after we're done
    Remove-SSHSession -Name $Session | Out-Null
    # return the actual output
    Write-Output $Output
}
# This-FingerPrintUpdate
This-GetSSHCommandOutput

Referrences:

https://www.powershellmagazine.com/2014/07/03/posh-ssh-open-source-ssh-powershell-module/




Python Script To Connect to remote server and run rails tasks

We need to import paramiko python2 package and it's dependent packages like bcrypt and PyNaCI

Here is the python2 script to connect ssh

import paramiko
ssh_client=paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect(hostname='xxxx',username='xxxx',password='xxxx'', allow_agent=False,look_for_keys=False)
ssh_client.invoke_shell()
stdin,stdout,stderr=ssh_client.exec_command("export PATH=/home/xxx/.rbenv/shims:/home/xxx/.rbenv/bin:/home/agwebadmin/bin:/home/xxx/.local/bin:/home/xxx/.rbenv/shims:/home/xxx/.rbenv/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin; export RAILS_ENV=production; ruby -v; cd current/HotDesk; rake sunspot:solr:reindex")
print stdout.read()
print stderr.read()
ssh_client.close()

To get ruby path we need to run command $which ruby

Monday 30 October 2017

git branching and merging

git branching and merging


# My repository currently pointing to master branch

$git branch
* master
gatekeeper
development

# Create a new branch from master to work with the task.

$git checkout -b bug-111

It will creates a new branch and switched to bug-111

Work on the issue/task

Now commit your changes

$git commit -m "Bug-111 changes " file1 file2...

Now switch to any branch for which you want merge your code

$git checkout gatekeeper

# Now my repository points to gatekeeper branch
# Inorder to avoid conflicts, I will update the references and I will pull the code from remote git repository .

$git fetch
# this command update all the referrences

$git pull origin gatekeeper
# To get latest  changes and avoiding conflicts.

$git merge bug-111

# After merge if you get any conflicts, rectify those conflicts and commit the changes by using below command

$git commit -im "bug-111 conflicts resolved" file1 file2

$git push origin gatekeeper

# To merge our changes to remote repository.















Thursday 18 May 2017

Difference between collect, select, map and each in ruby

To iterate over an array we generally use collect, select, map and each.

All four methods have a similar signature and take a block parameter. The map and collect methods both return an array of values returned by the block. The select method will return the actual values being iterated over if the block evaluates to true

1) Map

Map takes the enumerable object and a block like this [1,2,3].map { |n| n*2 } and evaluates the block for each element and then return a new array with the calculated values.

so the outcome of  [1,2,3].map { |n| n*2 } will be [2,4,6]

If you are try to use map to select any specific values like where n >2 then it will evaluate each element and will output only the result which will be either true or false

so the outcome of  [1,2,3].map { |n| n>2 } will be [false, false, true]

2) Collect

Collect is similar to Map which takes the enumerable object and a block like this [1,2,3].collect { |n| n*2 } and evaluates the block for each element and then return a new array with the calculated values.

so the outcome [1,2,3].collect{ |n| n*2 } of will be [2,4,6]

If you are try to use collect to select any specific values like where n >2 then it will evaluate each element and will output only the result which will be either true or false

so the outcome of  [1,2,3].collect { |n| n>2 } will be [false, false, true]

3) Select

Select evaluates the block with each element for which the block returns true.

so the outcome of  [1,2,3].select { |n| n*2 } will be [1,2,3]

If you are try to use select to get any specific values like where n >2 then it will evaluate each element but returns the original array

so the outcome of  [1,2,3].select{ |n| n>2 } will be [3]

4) Each

Each will evaluate the block with each array and will return the original array not the calculated one.
so the outcome of  [1,2,3].each{ |n| n*2 } will be [1,2,3]

If you are try to use each to select any specific values like where n >2 then it will evaluate each element but returns the original array

so the outcome of  [1,2,3].each { |n| n>2 } will be [1,2,3]

Wednesday 17 May 2017

Singleton Design pattern in rails

Singleton is a design pattern that restricts instantiation of a class to only one instance that is globally available. It is useful when you need that instance to be accessible in different parts of the application, usually for logging functionality, communication with external systems, database access, etc.

Single Instance of a class

class Logger
  def initialize
    @log = File.open("log.txt", "a")
  end

  @@instance = Logger.new

  def self.instance
    return @@instance
  end

  def log(msg)
    @log.puts(msg)
  end

  private_class_method :new
end

Logger.instance.log('message 1')


In this code example, inside class Logger we create instance of the very same class Logger and we can access that instance with class method Logger.instance whenever we need to write something to the log file using the instance method log. In the initialize method we just opened a log file for appending, and at the end of Logger class, we made method new private so that we cannot create new instances of class Logger. That is Singleton Pattern: only one instance, globally available.

Ruby Singleton module

Ruby Standard Library has a Singleton module which implements the Singleton pattern. Previous example when using the Singleton module would translate to:

require 'singleton'

class Logger
  include Singleton

  def initialize
    @log = File.open("log.txt", "a")
  end

  def log(msg)
    @log.puts(msg)
  end
end

Logger.instance.log('message 2')
Here we require and include Singleton module inside Logger class, define initialize method which opens the log file for appending and instance method log for writing to that log file. Ruby Singleton module does lazy instantiation (creates instance from Logger class at the moment when we call Logger.instance method) and not during load time (like in the previous example). Also, Ruby Singleton module makes new method private, so we don't have to call private\_class\_method.


Tuesday 24 May 2016

the calling order in angular js

Here's the calling order:
  1. app.config()
  2. app.run()
  3. directive's compile functions (if they are found in the dom)
  4. app.controller()
  5. directive's link functions (again, if found)
Here's a simple demo where you can watch each one executing (and experiment if you'd like).
Example:
index.html
<div ng-app="myApp" ng-controller="myCtrl">
    <div test1 test2> </div>
</div>
index.js
var myApp = angular.module('myApp', []);
myApp.factory('aProvider', function() {
   console.log("factory");
});
myApp.directive("test1", function() {
    console.log("directive setup");
    return {
        compile: function() {console.log("directive compile");}
    }
});
myApp.directive("test2", function() {
    return {
        link: function() {console.log("directive link");}
    }
});
myApp.run(function() {
    console.log("app run");
});
myApp.config( function() {
    console.log("app config");
});
myApp.controller('myCtrl', function($scope) {
    console.log("app controller");
});

Order Of execution:
app config
VM61:64 app run
VM61:51 directive setup
VM61:53 directive compile
VM61:72 app controller
VM61:59 directive link

Difference between constant and value

A constant can be injected anywhere.
A constant can not be intercepted by a decorator, that means that the value of a constant should never be changed.
var app = angular.module('app', []);

app.constant('PI'3.14159265359);

app.controller('appCtrl'function(PI) {
    var radius = 4;
    // calculate area of the circle
    var area = PI * radius * radius;
});
Value differs from constant in that value can not be injected into configurationsbut it can be intercepted by decorators.
var app = angular.module('app', []);

app.value('greeting''Hello');

app.config(function ($provide) {
    $provide.decorator('greeting'function ($delegate) {
        return $delegate + ' World!';
    });
});