Dataset in React

When life gives you lemons, you make lemonade. And when it doesn’t, hack your way around it. Such was the case with a piece of React code where the previous programmer passed some data-* attributes as props, then onto the JSX markup and later extract them from event.target in the event handlers (or also from the event.currentTarget or from native event). Now, React isn’t ready enough for this (as of January, 2017). The dataset property which are generally accessible via the HTMLElement.dataset property aren’t handled the DOM way.

While playing around wrappers, I had to find a workaround to pass the data-* props. I wrote a little hack to extract the data-* attributes using regex and some spread syntax to pass the dataset to both the outer wrapper, and the inner component.

Example:

render() {
  // Extract the keys present in the `props`
  // Filter the keys which have `data-` as prefix
  // and insert them into `dataset` object
  const dataset = {};
  const { state, props } = this;
  Object.keys(props).filter (value => {
    if (/data-\S+/gi.test(value)) {
       dataset[value] = props[value];
    }
  });
  return (
    <Wrapper {...dataset} onChange={this.handleChange} >
      <Component {...dataset} name="component-type-1">
      </Component>
    </Wrapper>
  )
}

The advantage – you can access the dataset in your handleChange method from the event.currentTarget and event.target. Visit this MDN link to know more about dataset.

Redux forms: Scroll to form field containing error message

  • Redux forms v6.2+ provide you with an onSubmitFail callback when a validation fails in your form.
  • Add refs to all Field elements with name
  • Note: Without refs, this will not work at all.
  • Import the following function as a utility and bind it in your constructor.
  • Whenever there is an error, this scroll the page to the 1st element in the page containing errors.

 


import ReactDOM from 'react-dom';
/**
 * Handles the errors received and determines the first element
 * containing the error as the 'key' element, so that,
 * it's positions can be determined
 * Scrolls the page that element to bring into visibility
 * And focuses on the element
 * Requires developers to use 'ref' attribute with 'name' in form fields
 * @param  {[object]} errors
 * @return {[undefined]}
 */

export function handleSubmitFail(errors) {
    if (!this.refs) {
        return;
    }
    const refsKeys = Object.keys(this.refs);
    const keys = Object.keys(errors);
    let key = null;
    let matchfound = false;

    refsKeys.filter(item => {
        if (keys.indexOf(item) > -1 && !matchfound) {
            key = item;
            matchfound = true;
            return false;
        } else { // eslint-disable-line no-else-return
            return true;
        }
    });

    this.targetNode = this.refs[key];

    if (this.targetNode) {
        const node = ReactDOM.findDOMNode(this.targetNode);
        const parentNode = ReactDOM.findDOMNode(this);
        const xy = node.getBoundingClientRect();
        this.x = xy.right + window.scrollX;
        this.y = xy.top + window.scrollY - 60;
        parentNode && parentNode.scrollTo && parentNode.scrollTo(this.x, this.y) || 
        (parentNode && parentNode.scrollTop && (parentNode.scrollTop = this.y) ) || 
        window && window.scrollTo(this.x, this.y); // eslint-disable-line no-unused-expressions
    }
}

 

When I’m on Modafinil vs when I’m not on Modafinil

When I’m on Modafinil

  • I should prepare the strategy for creating great designs
  • I should organize mood boards, and should focus on creating themes and UI kits rather than jumping into design
  • I should investigate why t-engine is faster than vanilla nginx
  • I should find out if anyone else logged into my digital ocean VPS as the root user or not
  • I must find out the optimal way to isolate webpack from node to reduce the compile time
  • I must learn Kannada
  • I’ve heard people who learnt multiple languages had greater IQ
  • P V Narasimha Rao must have been great. He sent Vajpayee as a delegate to represent India once. That’s damn awesome.
  • There should be IQ level indicator in Facebook. You should ignore (or prevented from) engaging in comment-wars with people of lower IQs. I must create a chrome plugin that determines someone’s IQ and warns.

When I’m not on Modafinil

  • I should rather be at home. I focus better at home
  • The chirpy team next to me is very noisy & seems jobless. I can’t work in an environment like this.
  • I need coffee.
  • Enough for the day. Too noisy here. I should rather go home and sleep to get rid of the noise in my head.
  • It’s Wednesday. Because the noise levels are at peak.
  • I don’t know how to file IT returns yet. How’ll I manage a family?
  • The problem with open floor office designs is – you’ve no privacy. Joel Spolsky was right. Nobody wants to work in facebook because of their acre wide open floor office.
  • I need espresso. Double black eye.
  • Why people are so optimistic about their political leader and too cynical about who question the authority in this nation?
  • I’ve no cash. How’ll I manage a family?
480px-unofficial_javascript_logo_2-svg

Make a Custom Array without distorting the Original

  function MyArray () {
    var _arr = [].slice.call(arguments, 0);
    for( var i=0; i<_arr.length; i++ ) {
      this[i] = _arr[i];
    }
    var THIS = this;
    var max = arguments.length;
    Object.defineProperty(THIS, 'length', {
      enumerable: false,
      get: function() { 
        var keys = Object.keys(this);
        for(var i=0; i< keys.length; i++) {
            keys[i] = parseInt(keys[i], 10);
            if( !isNaN (keys)[i] ){
              if (keys[i] > max) {
              max = keys[i]
            }
          }
        }

        for( var i=0; i<max; i++ ) {
          if( !this[i] ) {
            this[i] = void 0;
          }
        }
        return max;
      },
      set: function(){
        max = arguments[0];
      }
    });


    this.splice = [].splice.bind(this);
    this.push   = [].push.bind(this);
    this.add    = [].push.bind(this);
    this.splice = [].slice.bind(this);
    this.pop    = [].pop.bind(this);

    this.addAll = function() {
      var arr = arguments[0];
      for (var i=0, j = this.length; i<arr.length; i++, j++) {
        this[j] = arr[i];
      }
    };
    return this;
  };


  MyArray.prototype = new Array;
  MyArray.prototype.constructor = MyArray;



  var collection = new MyArray(1, 2, 3, 4);


  console.log(collection);
  //true
  console.log(collection instanceof Array);
  //true
  console.log(collection instanceof MyArray);
  // true

  console.log("collection", collection);
  //[1,2,3,4];
  console.log("collection.length", collection.length);
  //4

  console.log("-------------------------1");


  collection.add("hello");
  console.log("pushed hello");
  //5
  console.log("collection.length", collection.length);
  //5
  console.log("collection[4]", collection[4]);
  //"hello"
  

  console.log("-------------------------2");


  collection.push("world");
  console.log("pushed world");
  console.log("collection.length", collection.length);
  //6
  console.log("collection[5]", collection[5]);
  //world
  console.log("collection", collection);
  //world



  console.log("-------------------------3");


  collection.addAll(["java", "script"]);
  console.log("pushed [java, script]");
  console.log("collection.length", collection.length);
  //8
  console.log("collection", collection);
  //[1,2,3,4,"hello", "world", "java", "script"]


  console.log("-------------------------4");



  collection[8] = "last";
  console.log("assigned collection[8] = 'last'  ");
  //9
  console.log("collection.length", collection.length);
  //9


  console.log("-------------------------5");



  console.log("collection.pop()", collection.pop());
  //"last"
  console.log("collection.length", collection.length);
  //8
  console.log("collection", collection);
  // [1,2,3,4,"hello", "world", "java", "script"]


  console.log("-------------------------6");
  console.log("Array.prototype.addAll", Array.prototype.addAll);
  //undefined


11264881_800444453357506_8919000067016279292_n

(WIP)Articles: Colonialism and Homophobia

Terms:

POC – People of color, everybody except caucasians

LGBT in the Modern Day

Popular Articles

The Guardian – Africa: homophobia is a legacy of colonialism

  • Most Africans don’t recognize homophobia as a colonial legacy
  • Before colonialism, many traditional cultures were tolerant of different sexualities and gender relations.
  • E.g. In the Ganda or Baganda Tribe, (Uganda’s largest ethnic group) women from the royal clan are addressed with male titles and may or may not be required to perform duties expected of women.

Slate: How American Evangelicals Infected Uganda

Role of Christianity

  • Tribal Chiefs and Village Courts of law were traditionally the hallmark of conflict resolution.
  • But those were traded for a European Penal Code system post colonialism, which included the criminalization of homosexuality.
  • Sodomy laws would not have impacted African sexual politics without the influence of Christianity.
  • Christianity was used to whitewash African culture as primitive and to demonize traditional interpretations of African intimacies.
  • The bible became the credo of African morality, disordering African sexuality to missionary positions of heteronormativity (ie. the idea that heterosexuality is the only ‘natural’ sexual orientation).

Islam and Homophobia

  • Homophobia among religious extremist bodies like ISIS are attributed to their extreme religious beliefs.
  • But homoerotic themes and pederasty could be found in many poetry and other literature written by Muslims presented in positive light belonging to the medieval period (5th to the 15th century).
  • Modern Day

Modern Day Islam

  • The modern Islamic law criminalizes homosexuality but the punishment is not part of the rule book, and it is usually left to the discretion of the local authorities on Islam, unlike

Inflation in India

Tools Used: Inflation calculator by Calculator Stack, an online tool to calculate India’s inflation between the years 1971-2016 based on Consumer Price Index

Method: calculating the worth of ₹ 100 in the concerned year over time.

Inflation in last 10 years – from 2006 to 2016

Worth of ₹ 100 in 2006, is same as ₹ 214.62 in 2016

Result: ₹ 214.62
Number of Years: 10
Average Yearly Inflation Rate : 7.97 %
Culmulative rate of inflation : 114.62 %
Year Amount Inflation Rate
2006 ₹ 100.00 N.A.
2007 ₹ 105.97 5.97 %
2008 ₹ 115.43 8.93 %
2009 ₹ 130.45 13.01 %
2010 ₹ 140.27 7.53 %
2011 ₹ 153.56 9.47 %
2012 ₹ 168.53 9.75 %
2013 ₹ 185.48 10.06 %
2014 ₹ 194.25 4.73 %
2015 ₹ 204.80 5.43 %
2016 ₹ 214.62 4.79 %

Inflation in previous decade – from 1996 to 2006

Worth of ₹ 100 in 1996, is same as ₹ 171.73 in 2006

Result: ₹ 171.73
Number of Years: 10
Average Yearly Inflation Rate : 5.58 %
Culmulative rate of inflation : 71.73 %

Year Amount Inflation Rate
1996 ₹ 100.00 N.A.
1997 ₹ 106.71 6.71 %
1998 ₹ 119.08 11.59 %
1999 ₹ 124.38 4.45 %
2000 ₹ 131.10 5.40 %
2001 ₹ 137.81 5.12 %
2002 ₹ 143.11 3.85 %
2003 ₹ 148.41 3.70 %
2004 ₹ 154.06 3.81 %
2005 ₹ 161.13 4.59 %
2006 ₹ 171.73 6.58 %
Source: inflation.eu
Historic CPI inflation India (yearly basis) – full term 1959-2015

Historic inflation India (CPI) – by year

 annual inflation (dec vs. dec) inflation annual inflation (dec vs. dec) inflation
 CPI India 2015 6.32 % CPI India 2005 5.57 %
 CPI India 2014 5.86 % CPI India 2004 3.78 %
 CPI India 2013 9.13 % CPI India 2003 3.72 %
 CPI India 2012 11.17 % CPI India 2002 3.20 %
 CPI India 2011 6.49 % CPI India 2001 5.16 %
 CPI India 2010 9.47 % CPI India 2000 3.48 %
 CPI India 2009 14.97 % CPI India 1999 0.47 %
 CPI India 2008 9.70 % CPI India 1998 15.32 %
 CPI India 2007 5.51 % CPI India 1997 6.29 %
 CPI India 2006 6.53 % CPI India 1996 10.41 %

Average inflation in India (CPI) – by Year

 average inflation inflation average inflation inflation
 CPI India 2016 5.91 % CPI India 2006 5.79 %
 CPI India 2015 5.88 % CPI India 2005 4.25 %
 CPI India 2014 6.37 % CPI India 2004 3.77 %
 CPI India 2013 10.92 % CPI India 2003 3.81 %
 CPI India 2012 9.30 % CPI India 2002 4.31 %
 CPI India 2011 8.87 % CPI India 2001 3.77 %
 CPI India 2010 12.11 % CPI India 2000 4.02 %
 CPI India 2009 10.83 % CPI India 1999 4.84 %
 CPI India 2008 8.32 % CPI India 1998 13.17 %
 CPI India 2007 6.39 % CPI India 1997 7.25 %

Top GDP contributions by Sector in India

 Total GDP

Gross domestic product: 1.877 trillion USD (2013) World Bank
Population: 1.252 billion (2013) World Bank
GDP growth rate: 5.0% annual change (2013) World Bank

Related statistics

Population
1.252 billion ‎(2013)
Gross domestic product
1.877 trillion USD ‎(2013)
GDP growth rate
5.0% annual change ‎(2013)

GDP per capita elsewhere

United States of America
53,041.98 USD ‎(2013)
China
6,807.43 USD ‎(2013)
United Kingdom
41,787.47 USD ‎(2013)

Top GDP contributions by Sector in India

  • source
  • 52% : Services sector
  • 17%  : Agriculture
  • 30% : Industry
  • Service sector includes – retail, banks, hotels, real estate, education, health, social work, computer services, recreation, media, communications, electricity, gas and water supply
  • Computer software businesses in India are increasing at a rate of 35% per year
  • In India, there has been a huge growth in service sector businesses which made up 55% of India’s GDP in 2006—2007.
Sector GVA (Rupees in Crore) at current prices
2011-12 2012-13 2013-14 % share 2014-15 % share
3 Services Sector 3,976,498 4,628,810 5,376,045 51.31 6,118,738 52.97
2 Industry Sector 2,713,467 2,954,565 3,219,942 30.73 3,466,996 30.02
3.3 Financial, real estate & prof servs 1,539,575 1,807,699 2,074,623 19.80 2,372,103 20.54
2.2 Manufacturing 1,482,158 1,654,084 1,808,370 17.26 1,984,173 17.18
1 Agriculture Sector 1,505,580 1,668,676 1,881,152 17.95 1,964,506 17.01
1.1 Agriculture,forestry & fishing 1,505,580 1,668,676 1,881,152 17.95 1,964,506 17.01
3.4 Community, social & pers. Servs 1,023,803 1,160,634 1,355,362 12.94 1,541,351 13.34
3.1 Trade, repair, hotels and restaurants 882,957 1,046,241 1,257,324 12.00 1,431,836 12.40
2.4 Construction 774,093 801,884 868,808 8.29 928,418 8.04
3.2 Transport, storage, communication & services related to broadcasting 530,163 614,236 688,736 6.57 773,448 6.70
2.3 Electricity, gas, water supply & other utility services 194,403 213,826 244,220 2.33 278,593 2.41
2.1 Mining & quarrying 262,813 284,771 298,544 2.85 275,812 2.39

List of countries by GDP growth

Economy of India

The Indian economy is the fourth largest economy of the world on the basis of Purchasing Power Parity (PPP). It is one of the most attractive destinations for business and investment opportunities due to huge manpower base, diversified natural resources and strong macro-economic fundamentals.

The spice trade between India and Europe was the main catalyst for the Age of Discovery.

The statistical work of the Cambridge historian Angus Maddison has shown, India’s share of world income collapsed from 22.6% in 1700, almost equal to Europe’s share of 23.3% at that time, to as low as 3.8% in 1952.

Estimated per capita GDP of India and United Kingdom from 1700 to 1950, inflation adjusted to 1990 US$.[84] Other estimates[85] suggest a similar stagnation in India’s per capita GDP and income during the colonial era.

es6-logo

Creating a Guitar Tuner – With modern web APIs

String Frequency Scientific pitch notation
1 (E) 329.63 Hz E4
2 (B) 246.94 Hz B3
3 (G) 196.00 Hz G3
4 (D) 146.83 Hz D3
5 (A) 110.00 Hz A2
6 (E) 82.41 Hz E2

This table can be obtained from the Guitar Tuning wiki page.

So, this is how it goes:

  1. Our objective here is to generate the frequencies when requested, like when a user presses a button
  2. We make use of the Web Audio API to generate the frequencies listed above
    • An extension to it, will be using the micro phone to match the frequencies, but that won’t be covered in this part
    • Paul Lewis has an excellent app built with the above approach
  3. To use the web api, we must create an instance of the AudioContext object
    • Akin to canvas, we must instantiate an audio context object before accessing the web audio api
    • And, to generate the frequencies, we have to create an oscillator.

// create web audio api context
var audioCtx = new (window.AudioContext || window.WebkitAudioContext);

// create Oscillator node
var oscillator = audioCtx.createOscillator();

Now, we’ve to specify the type of wave. These are four natively supported types:

  • sine
  • square
  • sawtooth
  • triangle

A custom type is also available for use. We are not getting into that.

  • We’ll use the sine wave, because that audio wave is bearable.
  • We’ve to set a frequency value at which the oscillator will produce the waves. Let’s set it to E1, i.e. 329.63 Hz
  • We’ve to connect to the destination supported by the Audio Context. The output generally the standard audio interface i.e. your speakers.
  • Next, we start the oscillator.
  • Remember, the oscillator can be started once, and only once. It can be stopped, but can’t be restarted.
  • If you make live changes to the frequency or the type of the wave, the changes are reflected in the oscillator realtime. Hence, the absence of a restart functionality won’t be felt much.

Let’s create an oscillator React component (sorry, p-react, because size matters).

Now, the markup in the snippet ahead appeared gibberish. Therefore, I’ve posted a gist instead.


# oscillator.js
import { h, Component } from 'preact';
import style from './style';

const audioContext = new (window.AudioContext || window.webkitAudioContext);

export default class Oscillator extends Component {

  play() {
    this.oscillator = audioContext.createOscillator();
    this.oscillator.type = this.props.type || 'sine';
    this.oscillator.frequency.value = this.props.frequency || 329.63; //E(1) is default
    this.oscillator.connect(audioContext.destination);  
    this.oscillator.start();
  }

  stop() {
    this.oscillator.stop();
    this.oscillator = null;
  }

  render() {
    return ( /* refer the gist */ );
  }
 }

 

The reasons for creating a new instance every time you hit the start button are

  • The start method only works once per oscillator. Hence, once stopped, there is no way to restart the oscillator.
  • There is no API to suspend and later resume the oscillator.
  • The context can be suspended and resumed later but that doesn’t stop the oscillators. And, when you resume the context after firing multiple oscillators, you hear all of them buzz simultaneously.
  • Therefore, we must create a new oscillator instance then start, every time we hit start and stop-then-destroy the instance every time we hit the stop button.

Now, we’ve to make some buzzing & humming by assigning values to the props. If you can’t see the code here, then follow this gist.

  <Oscillator note="E1" frequency="329.63" type="sine" />
  <Oscillator note="B2" frequency="246.94" type="sine" />
  <Oscillator note="G3" frequency="196.00" type="sine" />
  <Oscillator note="D4" frequency="146.83" type="sine" />
  <Oscillator note="A5" frequency="110.00" type="sine" />
  <Oscillator note="E6" frequency="82.41" type="sine" />

And, we're done.

Caution

Make sure to lower your speaker volumes. If you’re using head phones, then definitely cross check 3 times if your volume is low or not. I don’t want people testing it go all Beethoven on the first day.

Hit the start/stop buttons and tune your guitar along.

Chords

In the similar fashion, we can create a chord component (possibly in the next tutorial) that creates 3 oscillators and plays all of them simultaneously to create a resonating chord.

Hint: A frequency combination for C-major are 196.00 (G), 261.63(C) and 329.63(E). And, for creating a G-major, you can use a combination of 146.83(D), 196.00(G),  and 246.94(B).

happy humming

More

 

nginx_logo_rgb-01

ngnix virtual hosts

Setting up virtual host in nginx

# check ubuntu version
# try
lsb_release -a
# if that doesn't work, then try
cat /etc/*release

Determining the Ubuntu version helps in assuming the default locations of nginx conf file.


# create *.conf files locally
# create 2 server blocks. Only one block carries the default_server directive
server
 {
   listen 80 default_server;
   listen [::]:80 default_server ipv6only=on;
   root /var/www/example.com/public_html;
   index index.html index.htm;
   server_name example.com www.example.com;
   location / {
      try_files $uri $uri/ =404;
   }
}
# notice: The 2nd server block is non-default and it doesn't carry ipv6only directive
server {
 listen 80;
 listen [::]:80;
 root /var/www/foobar.com/public_html;
 index index.html index.htm;
 server_name foobar.com www.foobar.com;
 location / {
   try_files $uri $uri/ =404;
 }
}

# the default server responds if a domain matching fails, or if you directly hit the IP of the server

# copy them to the 'sites-available' remote dir
scp -r /Users/<username>/<path-to-dir>/foozbar.com.nginx.conf root@123.456.789.101112:/etc/nginx/sites-available/foozbar.com.nginx.conf

# remove default conf from 'sites-enabled' dir
rm /etc/nginx/sites-enabled/default

# create soft-link of the 'conf' from the '-available' to the '-enabled' dir
ln -s /etc/nginx/sites-available/foozbar.com.nginx.conf /etc/nginx/sites-enabled/


# note: the file extension is not mandatory. It has just been used as a convention

# restart nginx
# a) the signal way
nginx -s reload

# b) the service way
sudo service nginx restart

More:

That’s all folks

screen-shot-2016-09-26-at-12-28-50-am

Run a little gem: Faker

Faker @github is a ruby gem for generating fake data, albeit not guaranteed to be unique every time. It’s for general purposes of fake data generation.

# Instructions
# go to terminal
$ gem install faker

# start the interactive ruby shell
$ irb

# load the gem: Faker
irb(main):011:0> require 'Faker'
true
# returns 'true' if you're loading it for the first time.
irb(main):011:0> require 'Faker'
false
# false, because it's already loaded

# now, time to play around
irb(main):011:0> Faker::Name.name
=> "Brook Reichel"

irb(main):011:0> Faker::Address.city 
=> "West Brigitte"

# need a bitcoin wallet?
irb(main):014:0> Faker::Bitcoin.address
=> "1PfXhC3E64DYkdmYPKGwxziRh3ZzMKgzNn"


Update 1:

On the similar premises there are some other data generators you can have at your disposal