NPM Cheat Sheet

To check for outdated and update

npm outdated
npm update
npm install

To Update all packages

npm install -g npm-check-updates
and then
ncu -u

List globally installed packages.

npm list -g –depth=0

Check packages not used

npm install -g depcheck
depcheck

npm uninstall

Javascript Object to Array and visa versa

const obj = {"1":"5","2":7,"3":9,"4":155,"6":"189","7":587,"8":"455","9":"89","10":"80","12":"887.6","13":89,"14":9}
const objToArr = Object.keys(obj).map(function(key) {
  return [key, Number(obj[key]) ];
});
console.log(objToArr)
/*
[ [ '1', 5 ],
  [ '2', 7 ],
  [ '3', 9 ],
  [ '4', 155 ],
  [ '6', 189 ],
  [ '7', 587 ],
  [ '8', 455 ],
  [ '9', 89 ],
  [ '10', 80 ],
  [ '12', 887.6 ],
  [ '13', 89 ],
  [ '14', 9 ] ]
*/


let resultObj = objToArr.reduce(function(result, item, index, array) {
   Object.assign(result, { [ item [ 0 ] ]:item[1]} )
  return result;
}, {}) //watch out the empty {}, which is passed as "result"
console.log(resultObj)
/*
{ '1': 5,
  '2': 7,
  '3': 9,
  '4': 155,
  '6': 189,
  '7': 587,
  '8': 455,
  '9': 89,
  '10': 80,
  '12': 887.6,
  '13': 89,
  '14': 9 }
*/

resultObj2 = {...objToArr};
console.log(resultObj2)
/*
{ '0': [ '1', 5 ],
  '1': [ '2', 7 ],
  '2': [ '3', 9 ],
  '3': [ '4', 155 ],
  '4': [ '6', 189 ],
  '5': [ '7', 587 ],
  '6': [ '8', 455 ],
  '7': [ '9', 89 ],
  '8': [ '10', 80 ],
  '9': [ '12', 887.6 ],
  '10': [ '13', 89 ],
  '11': [ '14', 9 ] }
*/





ES6 Arrow functions and correct using of bind(this)

function Desciples(firstname, attributes) {
  this.firstname = firstname;
  this.attributes = attributes;
  this.listAttributes = function() {
    return this.attributes.map(function (attrib)  {
      console.log(this.firstname + " did " + attrib);
    });
  };
}

let desciple1 = new Desciples("John", [
  "Author of Gospel of John ",
  "Author of Reveleations",
  "Desicple that Jesus loved"
]);

desciple1.listAttributes();

retuns

"undefined did Author of Gospel of John "
"undefined did Author of Reveleations"
"undefined did Desicple that Jesus loved"

But if we change it to

this.listAttributes = function() {
    return this.attributes.map(attrib => {
      console.log(this.firstname + " did " + attrib);
    });


"John did Author of Gospel of John "
"John did Author of Reveleations"
"John did Desicple that Jesus loved"

We can also create local variable to the function and assign this to it

 this.listAttributes = function() {
    self = this;
    return this.attributes.map(function (attrib)  {
      console.log(self.firstname + " did " + attrib);
    });
  };

We can also use the BIND on the function like:

  this.listAttributes = function() {
    return this.attributes.map(function (attrib)  {
      console.log(this.firstname + " did " + attrib);
    }.bind(this));
  };

Or the MAP has a second paramenter and we can pass this there that will also work

  this.listAttributes = function() {
    return this.attributes.map(function (attrib)  {
      console.log(this.firstname + " did " + attrib);
    },this);
  };

Python update to fix Kodi on linux (Ubuntu and mint)

I had issues with my Kodi 17.6 on linux. I have noticed errors involving cryptography and ffi. Here is the procedure that I followed to fix it.
Open a Terminal and do the following:

 sudo apt-get install build-essential libssl-dev libffi-dev python-dev python-pip

After its done then install cryptography for python

pip install cryptography

It will prompt to install update pip BUT DONT DO THAT IT WILL BREAK THINGS.

Javascript Essentials ES6

Object to String Array of the object keys

 const strArrKeys = Object.keys(jsObjectVariable); 

Object to Array with Key Value pairs

let theobj = { key1: "value1", key2: "value2" }
Object.entries(theobj).forEach(eachKeyVal =>
   { console.log("Key is " + eachKeyVal[0] + " and value is " + eachKeyVal[1]) }); 

Array from object values

 jsObjectVariable = { one : 1, two: 2, three: { temp1: "t1", temp2: "t2" } } const strArr = Object.keys(jsObjectVariable) // Returns ARRAY of the keys .map(k => jsObjectVariable[k] ); // Retruns an Array of values console.log(strArr); const strArr2 = Object.keys(jsObjectVariable) // Returns ARRAY of the keys .map(k => { return jsObjectVariable[k] } ); // Retruns an Array of values console.log(strArr2); jsARRVariable = [(one => 1),(two => 2)]; const strArr3 = jsARRVariable.map((k,v) => {return v;} ); // Returns array of values console.log(strArr3); 

Make a copy of the object.

cont newObject = {...oldObject};

Make a copy of the array.

cont newArray = [...oldArray];

Add values to an Array immutably.
Dont use push use concat, it will make a copy of the array.
Add an integer called counter to an array called results:

cont newObject = {
    ...oldObject,
    results: oldObject.results.concat(oldObject.counter)
};

Delete values from an Array immutably.

const idToDelete = 4;
const newArray = [...oldArray];
newArray.splice(idToDelete,1);

OR

newArray = oldArray.filter((result,index) => index !== idToDelete);

You can also create dynamic object keys (Object Names based on variables) and use them

var example = {one : 'something', two: 'somethingElse'};
var test = {
    [example.one]: true,
    [example.two]: function () { console.log('This is SomethingElse function Result');},
};

console.log(test.something);
test.somethingElse();

IN ES5 we used to:

var key = 'dynamicKey';
var o = {};
o[key] = 'value';

But in ES6, when creating an object literal, you can do this:

Continue reading “Javascript Essentials ES6”

Java easily convert from char or string to ENUM

One of my popular ways to make my code more readable is to make use of an ENUM.

If you have some “if” or “switch” statement:

             char myChar = 'D';
             if (myChar=='H') {
              //SOME CODE
              } else if (myChar=='V') {
                //SOME OTHER CODE
                 }

it does not say much about the functionality thats why I use enums

public enum myType {
        HORIZONTAL("H"),
        VERTICAL("V");
        private char directionToken;
        
        public static myType fromChar(char searchchar) {
            for (myType st : myType.values()) {
                if (st.directionToken == searchchar) {
                    return st;
                }
            }
            return null;
        }
        
        private myType(String transToken) {
            this.directionToken = transToken.charAt(0);
        }

        public char directionToken() {
            return directionToken;
        }
    }    

.....

             myType currRecordType = myType.fromChar(linechar[43]);
             switch (currRecordType) {
                 case HORIZONTAL:{
                     ...
                     break;
                     }
                     
                 case  VERTICAL:{
                     ...
                     break;
                 }
             }

Python Dictionaries and Panda

Here are some quick references to Python Dictionaries and Panda include

#Dictionaries
#Create
cities_in_europe = {'spain':'madrid', 'france':'paris', 'germany':'berlin', 'norway':'oslo' }

#Read value back
cities_in_europe['france']

#Add to Dictionaries
cities_in_europe['italy'] = 'venice'

#Change a value
cities_in_europe['italy'] = 'rome'

#"key" in dicarr
'italy' in delcities_in_europe #-> returns true

#delete a key
del(cities_in_europe['italy'])

print(cities_in_europe)

#N Dimention Dictionaries
europe = { 'spain': { 'capital':'madrid', 'population':42.33 },
'france': { 'capital':'paris', 'population':63.02 },
'germany': { 'capital':'berlin', 'population':78.62 },
'norway': { 'capital':'oslo', 'population':8.078 } }

#Get Single value
europe['france']['capital']
europe['france']['population']

# Print out the capital of France
print(europe['france']['capital'])

# Add One more Element
data = {'capital':'rome','population':59.83}

# Add data to europe under key 'italy'

europe['italy'] = data

#Add in one line
europe['england'] = {'capital':'london','population':78.88}

# Print europe

print(europe)

Pre Defined Lists

# Pre-defined lists
names = ['United States', 'Australia', 'Japan', 'India', 'Russia', 'Morocco', 'Egypt']
dr = [True, False, False, False, True, True, True]
cpc = [809, 731, 588, 18, 200, 70, 45]

import pandas as pd

my_dict = {'country':names ,
'drives_right':dr ,
'cars_per_cap':cpc }

# Build a DataFrame cars from my_dict: cars

cars = pd.DataFrame(my_dict)
print(cars)

row_labels = ['US', 'AUS', 'JAP', 'IN', 'RU', 'MOR', 'EG']

# Specify row labels of cars

cars.index = row_labels

print(cars)

Panda from CSV File

———- CVS FILE ————–
,country,capital,area,population
BR,Brazil,Brasilia,8.516,200.4
RU,Russia,Moscow,17.10,143.5
IN,India,New Delhi,3.286,1252
CH,China,Beijing,9.597,1357
SA,South Africa,Pretoria,1.221,52.98


import pandas as pd

brics = pd.read_csv("path/to/brics.csv", index_col = 0)
print(brics)

Column and Row Access
print(brics['country'])
print(type(brics['country']))
#Gives you <class 'pandas.core.series.Series'>

print(brics[['country']])
print(type(brics[['country']]))
#Gives you <class 'pandas.core.frame.DataFrame'>

#Two Columns
print(brics[['country','capital']])

#Row Access
brics[0:3] # Rows 0,1,2
brics[3:6] # Rows 3,4,5

#loc and iloc
brics.loc['RU'] #Selects row for RU
brics.iloc[1]
brics.loc[['BR','SA']] #Selects ROW BR and SA
brics.iloc[[0,4]]

#Select Area for SA
brics.loc['SA','area'])

# Capital and area for SA and RU
brics.loc[['SA','RU'],['capital','area']])
brics.loc[['RU','MOR'],['country','area']]
#Combine loc and iloc using ix
brics.ix[[4,5],['country','capital']]
brics.ix[4:6,['country','capital']]

#Slice-ing loc
brics.loc[:,'area']) #As Series
brics.loc[:,['area']]) #As DataFrame
brics.loc[:,['area','capital']]) #As DataFrame Area , Capital

Pivot Tables in PostgreSQL

To use the pivot table function you need the tablefunc extention for postgres.

CREATE extension tablefunc;

I liked this post : vertabelo post it helped me but I want to add to that one, so please read it first. Then come back.
So consider this SQL

select IDENTIFIER, CATAGORIES, SUM(value) as VALUES 
from TABLE 
group by IDENTIFIER, CATAGORIES

So lets consider our categories being 3 letter Months ie (Jan, Feb,….) and we want to show payments for each month.

select SOME_PRIMARY_KEY, 
       to_char (DATE_PAYMENT_MADE,  ''Mon'')  as MONTH_CODES,
       SUM(PAYMENTS) as TOT_PAID 
from TABLE 
group by SOME_PRIMARY_KEY, to_char (DATE_PAYMENT_MADE,  ''Mon'')

Now to run this have each month as a column we would

 SELECT *   FROM crosstab( '
     select SOME_PRIMARY_KEY, 
            to_char (DATE_PAYMENT_MADE,  ''Mon'')  as MONTH_CODES,
            SUM(PAYMENTS) as TOT_PAID 
      from TABLE 
group by SOME_PRIMARY_KEY, to_char (DATE_PAYMENT_MADE,  ''Mon'')
') 
AS final_result(MyPK character varying(20) , Jan numeric,Feb numeric,Mar numeric,Apr numeric,May numeric,Jun numeric,Jul numeric,Aug numeric,Sep numeric, Oct numeric, Nov numeric,Dec numeric) 
)

This does not give us the desired result since it will fill up from the fist column the values and not assign it to the correct column. To get the desired result we will have to add a second parameter to crosstab

 SELECT *   FROM crosstab( '
     select SOME_PRIMARY_KEY, 
            to_char (DATE_PAYMENT_MADE,  ''Mon'')  as MONTH_CODES,
            SUM(PAYMENTS) as TOT_PAID 
      from TABLE 
group by SOME_PRIMARY_KEY, to_char (DATE_PAYMENT_MADE,  ''Mon'')
',
  $$VALUES ('Jan'::text),('Feb'),('Mar'),('Apr'),('May'),('Jun'),('Jul'),('Aug'),('Sep'),('Oct'),('Nov''),('Dec')$$
) 
AS final_result(MyPK character varying(20) , Jan numeric,Feb numeric,Mar numeric,Apr numeric,May numeric,Jun numeric,Jul numeric,Aug numeric,Sep numeric, Oct numeric, Nov numeric,Dec numeric) 
)

Java 8 Lambda – Simple explanation of the Consumer Interface

I have not found a simple explanation of how the consumer interface works and how to use it in a lambda expression. Hopefully I will help you guys to see how easy it is to use and you will also simplify your code.
The legacy way to create a List and loop through it :

public class ConventionalForLoop {
    
    public static void main(String[] args) {
        List<Integer> il = new ArrayList<>();
        il.add(10); il.add(15); il.add(20); il.add(25);

        for (Iterator<Integer> i = il.iterator(); i.hasNext();) {
            Integer item = i.next();
            System.out.println("For Loop Value :" + item);
        }
    }
}


Now with Java 8 we can use a Consumer Interface and for explanation I have declared it.

public class ShowConsumer {
    public static void main(String[] args) {
        class ConsumeInt implements Consumer<Integer>
            {
                @Override
                public void accept(Integer i) {
                    System.out.println("Value From Consumer :" + i.toString());
                }
            }
        List<Integer> arrl = Arrays.asList(10,15,20,25);
        ConsumeInt ci = new ConsumeInt();
        arrl.forEach(ci);
    }


With the lambda expression it is very simple :

public class ShowConsumer {
    public static void main(String[] args) {
        List<Integer> arrl = Arrays.asList(10,15,20,25);
        arrl.forEach(i -> System.out.println("Value From Consumer :" + i.toString()));
    }
}

Java 8 Lambda Expressions quick explanation

To get started with Lambda expressions in Java 8 I have found that there was no simple explanation, so here is it its basic form for everyone to understand.
First of all look at this implementation of the Animal Interface. you will notice there are lots of unnecessary boilerplate code.
They are all Highlighted in the code:

  
package showlambda;

interface Animal {
    void eat();
}

class Dog implements Animal {
    @Override
    public void eat() {
        System.out.println("Feed me Anything");
    }
}

class Cat implements Animal {
    @Override
    public void eat() {
        System.out.println("Feed Me Meat");
    }
}

public class ShowLambda {
    public static void main(String[] args) {
        Cat c = new Cat();
        c.eat();
        Dog d = new Dog();
        d.eat();
    }
    
}


We dont have to declare the classes we can create one Anonymously like so:

package showlambda;

interface Animal {
    void eat();
}

public class ShowLambda {
    public static void main(String[] args) {
        Animal anonymousdog;
        Animal anonymouscat;
        anonymousdog = new Animal() {
            @Override
            public void eat() {
                System.out.println("Feed me Anything anonymously :-)") ;
            }
            
        };
        anonymouscat = new Animal() {
            @Override
            public void eat() {
                System.out.println("Feed me Meat anonymously :-)") ;
            }
        };
        anonymousdog.eat();
        anonymouscat.eat();
    }
}

But we are still stuck with all the boilerplate code.
The only thing that we really require is the implementation code and this is where the lambda comes in,
Now we don’t have to mention the eat method since there is only one:

package showlambda;

@FunctionalInterface
interface Animal {
    void eat();
}

public class ShowLambda {
    public static void main(String[] args) {
        Animal anonymousdog;
        Animal anonymouscat;
        anonymousdog = () -> 
            {
                System.out.println("Feed me Anything Yeah Lambda :-)") ;
            };
        anonymouscat = () -> 
            {
                System.out.println("Feed me Meat Yeah Lambda :-)") ;
            };
        anonymousdog.eat();
        anonymouscat.eat();
        
    }
}

Since there is just one line of code to implement eat we can even simplify it more:

package showlambda;

@FunctionalInterface
interface Animal {
    void eat();
}

public class ShowLambda {
    public static void main(String[] args) {
        Animal anonymousdog;
        Animal anonymouscat;
        anonymousdog = () -> System.out.println("Feed me Anything Yeah Lambda :-)") ;
        anonymouscat = () -> System.out.println("Feed me Meat Yeah Lambda :-)");
        anonymousdog.eat();
        anonymouscat.eat();
        
    }
}


Now to show how to implement a parameter:

package showlambda;

interface Animal{
    void eat(String food);
}

public class ShowLambda {
    public static void main(String[] args) {
        Animal anonymousdog;
        Animal anonymouscat;
        anonymousdog = (food) -> System.out.println("Feed me Anything Yeah Lambda :-) Parameter :" + food) ;
        anonymouscat = (f) -> System.out.println("Feed me Meat Yeah Lambda :-) Parameter :" + f);
        anonymousdog.eat("Dog Food");
        anonymouscat.eat("Cat Food");
        
    }
}