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:

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

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");
        
    }
}

Few lines of code to show all the basics of python datetime handling

Here is a few lines of code to show :
Line 3. How to Create a datetime object on a certain time
Line 4. How to subtract or add time to another time and how to compare datetime objects
Line 5. How to convert datetime to string
Line 6. How to get the current time

import datetime

lasttime = datetime.datetime(1900,1,1,0,0,0)

while True :
    if lasttime  < datetime.datetime.now() - datetime.timedelta(seconds=30) :
        print("30 Secornds has passed Date Now is :" + datetime.datetime.now().strftime("%A %d %B %Y %I:%M:%S%p") )
        lasttime = datetime.datetime.now()

Delete files that are older than 10 (or x) days

Here is a simple python script to delete files from the current directory that are older than 10 days,
you probably need to customize it a little to specify the files to delete.


#!/usr/bin/python

# run by crontab
# removes any files in current folder older than days_old days

import os, sys, time

def get_file_directory(file):
    return os.path.dirname(os.path.abspath(file))
    
now = time.time()
days_old = 1 #change this to how many days old files to delete
cutoff = now - (days_old * 86400)
files = os.listdir(get_file_directory(__file__))
file_path = get_file_directory(__file__)
for xfile in files:
        print("Check :" + xfile)
        if xfile.startswith('0000'):    #My Files stated with 0000 you can add other criteria here maybe xfile.endswith('.OLD')
            fullFile = os.path.join(str(file_path), xfile)
            #print("Path : " + fullFile)  Remove the comment to list all the files to be deleted
            if os.path.isfile(fullFile):
                t = os.stat(fullFile)
                c = t.st_ctime
                # delete file if older than [days_old] days
                if c < cutoff:
                    print("Will Remove " +fullFile + "to go ahead and remove the files please remove the # in the next line") #for now we will just print it
                    #os.remove(fullFile)  #comment this line to delete the files
            

Thanks to https://stackoverflow.com/users/1465704/xman-classical for the outline