Thursday, January 31, 2019

React native : What is Expo

Expo is a free and open source toolchain built around React Native to help you build native iOS and Android projects using JavaScript and React.
They make the entire process of developing an app and publishing it very easy. You’ll as well have access to the Expo SDK, a library that provides a wide variety of native APIs on iOS and Android, like the Camera API.

Expo gives us access to DocumentPicker and ImagePicker to pick up a document or image from our phone. The code with React Native will be the following for our “PickImageorDocument” Component. An image is a document, that goes without saying, but this is only to show both options.

The “pickDocument” retrieves a document form our phone and the “pickImage” gets a picture form our phone. We set the local state of our component with the uri of the asset.

References:
https://medium.com/@aurelie.lebec/uploading-pictures-and-videos-from-your-phone-in-your-app-with-react-native-expo-cloudinary-and-d3ad4358e81a

React-native what is a prop to a Component

Props are short for Properties. The simple rule of thumb is props should not be changed. In the programming world we call it “Immutable” or in simple english “Unchangeable”

Components receive props from their parent. These props should not be modified inside the component. In React and React Native the data flows in one direction -> From the parent to the child

You can write your own components that use props. The idea behind props is that you can make a single component that is used in many different places in your app. The parent that is calling the component can set the properties, which could be different in each place.


// Parent
export default class ScreenOne extends React.Component {
  render () {
    return (
    
          
    

    )
  }
}

// Child component
export default class Heading extends React.Component {
  render () {
    return (
     
        {this.props.message}
     

    )
  }
}
Heading.propTypes = {
  message: PropTypes.string
}
Heading.defaultProps = {
  message: 'Heading One'
}

References:
https://codeburst.io/props-and-state-in-react-native-explained-in-simple-english-8ea73b1d224e


React-native : What is state?

State works differently when compared to props. State is internal to a component, while props are passed to a component.

Keep in mind not to update state directly using this.state. Always use setState to update the state objects. Using setState re-renders the component and all the child components. This is great, because you don’t have to worry about writing event handlers like other languages.

class Form extends React.Component {

  constructor (props) {
     super(props)
     this.state = {
       input: ''
     }
  }

handleChangeInput = (text) => {
    this.setState({ input: text })
  }
 
  render () {
    const { input } = this.state

    return (
      
                      onChangeText={this.handleChangeInput}
            value={input}
          />
       

      )
    }
}

In the above code snippet you can see a Form class with an input state. It renders a text input which accepts the user’s input. Once the user inputs the text, the onChangeText is triggered which in turn calls setState on input.




References:
https://codeburst.io/props-and-state-in-react-native-explained-in-simple-english-8ea73b1d224e

iOS : iCloud Container



The purpose of an iCloud container depends on what you want to do with it. (key-value, CloudKit...) You need it for an iCloud app.
The name of your iCloud container has to be the same in the Developer portal and in Xcode to let it work. Like I have an iCloud container for my app. In the Developer portal, in my app ID, iCloud is enabled and the container named "iCloud.com.xxx.xxx" (iCloud.com.name.app). In my app capabilities (in Xcode), iCloud is on and and container selected is the one with the same name.


References:
https://stackoverflow.com/questions/24191548/create-icloud-identifier-in-ios-developer-panel

React native with yarn

To add a module to a react native app, need to do the below to add react-navigation

yarn add react-navigation

Now need to link the added module to the project so that the dependancies are added in

Got this error below,
Command `link` unrecognized. Make sure that you have run `npm install` and that you are inside a react-native project.

Running the npm install is resolving this issue.
Yarn link will add these dependancies to the

References:

Thursday, January 17, 2019

React Native : Anatomy of React - Redux Connect

React provides two major mechanisms for providing data to components namely: props and state. While props are read-only and allow a parent component to pass attributes to a child component, state is local and encapsulated within the component and can change at any time in the component’s lifecycle.

Since state is a very powerful mechanism for building powerful and dynamic React apps, it becomes necessary that state is properly managed in the application. Several libraries already exist, that provide a well-structured architecture for managing application state such as Flux, Redux, MobX.

Redux is a predictable state container for JavaScript apps ranging from vanilla apps to framework apps. It has a very tiny footprint and yet allows you to write consistent apps that can run in any environment:

The react-redux package provides React bindings for the Redux state container making it very easy for a React application to be connected to a Redux store.

    Presentational Components — These components are only concerned with how things look and are not aware of the Redux state. They get their data from props and may trigger callbacks passed to them via props.
    Container Components — These components are responsible for how things work and are fully aware of the Redux state. They are often created using React Redux and may dispatch Redux actions. They also subscribe to changes in the Redux state.

The react-redux package exposes a very simple interface, and all you should be interested in is just the following:

     — Wraps the React application and makes the Redux state available to all container components in the application’s hierarchy
    connect([mapStateToProps], [mapDispatchToProps], [mergeProps], [options]) — Creates a higher-order component for making container components out of base React components

the react-redux connect() API is used for creating container elements that are connected to the Redux store. The Redux store to be connected to is derived from the topmost ancestor of the component using the React context mechanism. You have no need for connect() if you are only creating a presentational component.

Whether you want to just get data from the Redux store, or you want to dispatch actions on the Redux store, or you want to do both in your React component, you can make the component a container component by wrapping it in a higher-order component returned by react-redux connect()



References:
https://blog.logrocket.com/react-redux-connect-when-and-how-to-use-it-f2a1edab2013

React Native: What is reducer


The reducer is a pure function that takes the previous state and an action, and returns the next state. (previousState, action) => newState. It's called a reducer because it's the type of function you would pass to Array.prototype.reduce(reducer, ?initialValue) .

Reducers specify how the application's state changes in response to actions sent to the store. Remember that actions only describe what happened, but don't describe how the application's state changes.

Designing the State Shape

In Redux, all the application state is stored as a single object. It's a good idea to think of its shape before writing any code. What's the minimal representation of your app's state as an object?

For our todo app, we want to store two different things:

    The currently selected visibility filter.
    The actual list of todos.

You'll often find that you need to store some data, as well as some UI state, in the state tree. This is fine, but try to keep the data separate from the UI state.

{
  visibilityFilter: 'SHOW_ALL',
  todos: [
    {
      text: 'Consider using Redux',
      completed: true
    },
    {
      text: 'Keep all state in a single tree',
      completed: false
    }
  ]
}


Handling Actions

Now that we've decided what our state object looks like, we're ready to write a reducer for it. The reducer is a pure function that takes the previous state and an action, and returns the next state.


It's called a reducer because it's the type of function you would pass to Array.prototype.reduce(reducer, ?initialValue). It's very important that the reducer stays pure. Things you should never do inside a reducer:

    Mutate its arguments;
    Perform side effects like API calls and routing transitions;
    Call non-pure functions, e.g. Date.now() or Math.random().


We'll start by specifying the initial state. Redux will call our reducer with an undefined state for the first time. This is our chance to return the initial state of our app:

Below is an example where more actions are handled

import {
  ADD_TODO,
  TOGGLE_TODO,
  SET_VISIBILITY_FILTER,
  VisibilityFilters
} from './actions'

...

function todoApp(state = initialState, action) {
  switch (action.type) {
    case SET_VISIBILITY_FILTER:
      return Object.assign({}, state, {
        visibilityFilter: action.filter
      })
    case ADD_TODO:
      return Object.assign({}, state, {
        todos: [
          ...state.todos,
          {
            text: action.text,
            completed: false
          }
        ]
      })
    default:
      return state
  }
}

we never write directly to state or its fields, and instead we return new objects. The new todos is equal to the old todos concatenated with a single new item at the end. The fresh todo was constructed using the data from the action.

References:
https://redux.js.org/basics/reducers

React Native - Data Storage options

Quick and dirty: just use Redux + react-redux + redux-persist + AsyncStorage for react-native.
It fits almost perfectly the react native world and works like a charm for both android and ios. Also, there is a solid community around it, and plenty of information.

With react native, you probably want to use redux and redux-persist. It can use multiple storage engines. AsyncStorage and redux-persist-filesystem-storage are the options for RN.

Using redux + redux-persist you can define what is persisted and what is not. When not persisted, data exists while the app is running. When persisted, the data persists between app executions (close, open, restart phone, etc).

AsyncStorage has a default limit of 6MB on Android. It is possible to configure a larger limit (on Java code) or use redux-persist-filesystem-storage as storage engine for Android.

Using redux + redux-persist + AsyncStorage the setup is exactly the same on android and iOS.

Using redux, offiline access is almost automatic thanks to its design parts (action creators and reducers).

All data you fetched and stored are available, you can easily store extra data to indicate the state (fetching, success, error) and the time it was fetched. Normally, requesting a fetch does not invalidate older data and your components just update when new data is received.

The same apply in the other direction. You can store data you are sending to server and that are still pending and handle it accordingly.

React promotes a reactive way of creating apps and Redux fits very well on it. You should try it before just using an option you would use in your regular Android or iOS app. Also, you will find much more docs and help for those.



References:
https://stackoverflow.com/questions/44376002/what-are-my-options-for-storing-data-when-using-react-native-ios-and-android

Create Native App Tool



Its a new tool that makes it significantly easier to get started with a React Native project!

With Create React Native App, there’s no need to use Xcode or Android Studio, and you can develop for your iOS device using Linux or Windows.
This is accomplished using the Expo app, which loads and runs CRNA projects written in pure JavaScript without compiling any native code.

$ npm i -g create-react-native-app
$ create-react-native-app my-project
$ cd my-project
$ npm start

This will start the React Native packager and print a QR code. Open it in the Expo app to load your JavaScript. Calls to console.log are forwarded to your terminal. You can make use of any standard React Native APIs as well as the Expo SDK.

Native code with Create React Native

Many React Native projects have Java or Objective-C/Swift dependencies that need to be compiled. The Expo app does include APIs for camera, video, contacts, and more, and bundles popular libraries like Airbnb’s react-native-maps, or Facebook authentication. However if you need a native code dependency that Expo doesn’t bundle then you’ll probably need to have your own build configuration for it. Just like Create React App, “ejecting” is supported by CRNA.

You can run npm run eject to get a project very similar to what react-native init would generate. At that point you’ll need Xcode and/or Android Studio just as you would if you started with react-native init , adding libraries with react-native link will work, and you’ll have full control over the native code compilation process.

Now with the above theory. Tried to create the project actually and below was the results

It asked whether require Expo CLI.
This command requires Expo CLI.
Do you want to install it globally [Y/n]? Y



References:
https://facebook.github.io/react-native/blog/2017/03/13/introducing-create-react-native-app

What is difference between CRNA and Expo?

create-react-native-app is the quickest way to start a new React Native project. It uses the Expo client and some of the Expo devtools but not all of them. For example, you don't need to create an Expo developer account to use CRNA and we've found it's faster to get started with CRNA than with XDE (the Expo development app).

Since CRNA projects run in the Expo client, you do have access to most of the Expo APIs such as native maps, audio, OpenGL, and more. There are a couple of exceptions like push notifications that only Expo projects can use, but there are many more similarities than differences between CRNA projects and Expo projects.

CRNA was also designed to give you several paths forward as your app grows. The three paths are:

    Use Expo: You actually can open a CRNA project with the Expo XDE app if you want all the features of Expo including push notifications and IPA / APK files for the App Store / Play Store.
    Eject to ExpoKit: ExpoKit is a native library that includes React Native and the Expo APIs. This path creates Xcode and Android Studio projects with ExpoKit so that most Expo APIs keep working if you were using them before. You then build IPA / APK files the way you would as any other native app.
    Eject to bare React Native: This path gives you a plain React Native project with separate Xcode and Android Studio projects. All modules that come with React Native will work but Expo APIs won't work (use ExpoKit above for that) because this is bare React Native.

Note that when you eject, CRNA won't manage upgrades for you so you're responsible for upgrading React Native.


References
https://github.com/react-community/create-react-native-app/issues/153

What is ssh-add?

ssh-add is a command for adding SSH private keys into the SSH authentication agent for implementing single sign-on with SSH. The agent process is called ssh-agent; see that page to see how to run it.

The cool thing about ssh-agent and ssh-add is that they allow the user to use any number of servers, spread across any number of organizations, without having to type in a password every time when moving between servers. This is commonly used by system administrators to move among the machine they administer. It is also widely used in universities and research institutions for accessing computing resources. However, it has also lead to proliferation of SSH keys in enterprises, and that is something administrators should be aware of and audit should take steps to address.

References:
https://www.ssh.com/ssh/add

iOS : Visual format language

Below are the essential syntax elements for visual layout

[button]-[textField] => Specifies standard spacing between button and textfield
[button(>=50)] => Specifies the minimum width of 50.
|-50-[purpleBox]-50-| => Specifies connection to super view, | indicates super view
V:[topField]-10-[bottomField] => Specifies vertical layout, spacing between top and bottom field being 10px.
[maroonView][blueView] => Flushing views, this means no spacing with the adjacent views. 
[button(100@20)] => This tells that the priority is 20 for the button to have width as 100
[button1(==button2)] => Equal widths for buttons button1 and button2
[flexibleButton(>=70,<=100)] => This is a multiple predicate scenario, where the width lies between 70 and 100px
|-[find]-[findNext]-[findField(>=20)]-| => This declares find and find next and find field is having standard spacing horizontally. Find and FindField is having spacing with the border of 20px. FindField is having width of at least 20px.

References:
https://developer.apple.com/library/archive/documentation/UserExperience/Conceptual/AutolayoutPG/VisualFormatLanguage.html#//apple_ref/doc/uid/TP40010853-CH27-SW1

Tuesday, January 15, 2019

WebRTC : WebAssembly role


WebAssembly in WebRTC will enable vendors to create differentiation in their products, probably favoring the more established, larger players.
WebAssembly (abbreviated Wasm) is a binary instruction format for a stack-based virtual machine. Wasm is designed as a portable target for compilation of high-level languages like C/C++/Rust, enabling deployment on the web for client and server applications.

WebAssembly is a JVM for your browser. The same as Java is a language that gets compiled into a binary code that then gets interpreted and executed on a virtual machine, WebAssembly, or Wasm, allows developers to take the hard core languages (which means virtually any language), “compile” it to a binary representation that a Wasm virtual machine can execute efficiently. And this Wasm virtual machine just happen to be available on all web browsers.


WebAssembly allows vendors to do some really cool things – things that just weren’t possible to do with JavaScript. JavaScript is kinda slow compared to using C/C++ and a lot of hard core stuff that’s already written in C/C++ can now be ported/migrated/compiled using WebAssembly and used inside a browser.

Construct 3 decided to use Opus in browsers. Even when it isn’t available – by implementing Opus with Wasm
Zoom uses WebAssembly in order NOT to use WebRTC (probably because it doesn’t want to transcode at the edge of its network)
Unity, the popular gaming engine has adopted Wasm for its Unity WebGL target


Below are some more use case

Multiparty voice and video communications for online gaming – mainly more control on how streams are created, consumed and controlled
Improved support in mobile networks – the ability to manage and switch across network connections
Better support for media servers
New file sharing capabilities
Internet of Things – giving some love, care and attention to the data channel
Funny hats – enabling AI (computer vision) on video streams
Machine learning – like funny hats, but a bit more generic in its nature and requirements
Virtual reality – ability to synchronize audio/video with the data channel


references:
https://bloggeek.me/webassembly-in-webrtc/

Javascript : How to play short beep file?

Below is an awesome method. we are passing in the audio data itself as arguments. Now to get this audio base 64 data, the below site can be used. Nice one!

https://dopiaza.org/tools/datauri/index.php

function beep() {
    var snd = new Audio("data:audio/wav;base64,//uQRAAAAWMSLwUIYAAsYkXgoQwAEaYLWfkWgAI0wWs/ItAAAGDgYtAgAyN+QWaAAihwMWm4G8QQRDiMcCBcH3Cc+CDv/7xA4Tvh9Rz/y8QADBwMWgQAZG/ILNAARQ4GLTcDeIIIhxGOBAuD7hOfBB3...."); 
    snd.play();
}
beep();


references:
https://stackoverflow.com/questions/879152/how-do-i-make-javascript-beep

Sails JS : Disabling CORS

Below was my config/cors.js configuration to allow all origins

allRoutes: true,
origin: '*',
credentials: false,
methods: 'GET, POST, PUT, DELETE, OPTIONS, HEAD',
headers: 'content-type,apikey,token'

apikey, token were the extra headers passed in from app side.

references:
https://medium.com/@makarakao/sails-js-cors-problem-954f94ccf676

Wednesday, January 9, 2019

AWS: Ubuntu synching with NTP server

Below are the few steps

Connect to your instance and use apt to install the chrony package.
ubuntu:~$ sudo apt install chrony

Open the /etc/chrony/chrony.conf file using a text editor (such as vim or nano). Add the following line before any other server or pool statements that are already present in the file, and save your changes:

server 169.254.169.123 prefer iburst

Restart the chrony service.
ubuntu:~$ sudo /etc/init.d/chrony restart

Verify that chrony is using the 169.254.169.123 IP address to synchronize the time.

ubuntu:~$ chronyc sources -v

210 Number of sources = 7

  .-- Source mode  '^' = server, '=' = peer, '#' = local clock.
 / .- Source state '*' = current synced, '+' = combined , '-' = not combined,
| /   '?' = unreachable, 'x' = time may be in error, '~' = time too variable.
||                                                 .- xxxx [ yyyy ] +/- zzzz
||      Reachability register (octal) -.           |  xxxx = adjusted offset,
||      Log2(Polling interval) --.      |          |  yyyy = measured offset,
||                                \     |          |  zzzz = estimated error.
||                                 |    |           \
MS Name/IP address         Stratum Poll Reach LastRx Last sample
===============================================================================
^* 169.254.169.123               3   6    17    12    +15us[  +57us] +/-  320us
^- tbag.heanet.ie                1   6    17    13  -3488us[-3446us] +/- 1779us
^- ec2-12-34-231-12.eu-west-     2   6    17    13   +893us[ +935us] +/- 7710us
^? 2a05:d018:c43:e312:ce77:6     0   6     0   10y     +0ns[   +0ns] +/-    0ns
^? 2a05:d018:d34:9000:d8c6:5     0   6     0   10y     +0ns[   +0ns] +/-    0ns
^? tshirt.heanet.ie              0   6     0   10y     +0ns[   +0ns] +/-    0ns
^? bray.walcz.net                0   6     0   10y     +0ns[   +0ns] +/-    0ns

Verify the time synchronization metrics that are reported by chrony.

ubuntu:~$ chronyc tracking

Reference ID    : 169.254.169.123 (169.254.169.123)
Stratum         : 4
Ref time (UTC)  : Wed Nov 29 07:41:57 2017
System time     : 0.000000011 seconds slow of NTP time
Last offset     : +0.000041659 seconds
RMS offset      : 0.000041659 seconds
Frequency       : 10.141 ppm slow
Residual freq   : +7.557 ppm
Skew            : 2.329 ppm
Root delay      : 0.000544 seconds
Root dispersion : 0.000631 seconds
Update interval : 2.0 seconds
Leap status     : Normal



references:
https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/set-time.html

AWS how to reboot instance?


Its pretty easy. An instance reboot is equivalent to an operating system reboot. In most cases, it takes only a few minutes to reboot your instance. When you reboot an instance, it remains on the same physical host, so your instance keeps its public DNS name (IPv4), private IPv4 address, IPv6 address (if applicable), and any data on its instance store volumes.

Rebooting an instance doesn't start a new instance billing period (with a minimum one-minute charge), unlike stopping and restarting your instance.

AWS recommend that you use the Amazon EC2 console, a command line tool, or the Amazon EC2 API to reboot your instance instead of running the operating system reboot command from your instance. If you use the Amazon EC2 console, a command line tool, or the Amazon EC2 API to reboot your instance, we perform a hard reboot if the instance does not cleanly shut down within four minutes. If you use AWS CloudTrail, then using Amazon EC2 to reboot your instance also creates an API record of when your instance was rebooted.

To reboot an instance using the console

Open the Amazon EC2 console.

In the navigation pane, choose Instances.

Select the instance and choose Actions, Instance State, Reboot.

Choose Yes, Reboot when prompted for confirmation.


references:
https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-reboot.html

Firebase : What is the main reason for this error?

I was deploying an AWS sails js app on Ubuntu EC2 instance and came across the below issue. Definitely the credential to the firebase was all correct, so the only issue left out was the time on the EC2 instance.

Amazingly it was 6 mins ahead of the GMT.

chronyc tracking
Reference ID    : 169.254.169.123 (169.254.169.123)
Stratum         : 4
Ref time (UTC)  : Wed Jan  9 18:07:53 2019
System time     : 386.305358887 seconds fast of NTP time
Last offset     : 0.000310425 seconds
RMS offset      : 0.000310425 seconds
Frequency       : 0.000 ppm fast
Residual freq   : 74.519 ppm
Skew            : 1000000.000 ppm
Root delay      : 0.000746 seconds
Root dispersion : 19.008415 seconds
Update interval : 0.0 seconds
Leap status     : Normal


Reading few posts, i could sense that the EC2 was not using NTP server time. Installed the NTP server sync on EC2 and after a reboot of the instance, the time was only off by a few nano millis!

[2019-01-09T18:18:20.225Z]  @firebase/database: FIREBASE WARNING: {"code":"app/invalid-credential","message":"Credential implementation provided to initializeApp() via the \"credential\" property failed to fetch a valid Google OAuth2 access token with the following error: \"Error fetching access token: invalid_grant (Invalid JWT: Token must be a short-lived token (60 minutes) and in a reasonable timeframe. Check your iat and exp values and use a clock with skew to account for clock differences between systems.)\". There are two likely causes: (1) your server time is not properly synced or (2) your certificate key file has been revoked. To solve (1), re-sync the time on your server. To solve (2), make sure the key ID for your key file is still present at https://console.firebase.google.com/iam-admin/serviceaccounts/project. If not, generate a new key file at https://console.firebase.google.com/project/_/settings/serviceaccounts/adminsdk."}

Tuesday, January 8, 2019

Firebase: How to set up a custom domain?

Need to navigate to https://console.firebase.google.com/u/0/project//hosting/main

Press on Connect Domain. This will show up a text field to enter the domain name. Once enter the domain, Google prepares a TXT record value to be added in big rock or the domain name providers page. In the Domain name providers page, enter the host as @ or leave empty and set the value as the value given by Google. Also add a CNMAe record with the domain that firebase temporarily gives. After this, press on verify. It is said that sometimes the TXT record refresh take max upto 72 hrs, but practically in my case, it just took only 30 mins. Once the verification is done successfully, Google gave 2 A records that had to be added to the Name providers. This is going to take some time to reflect it seems. Still waiting for it.

references:
https://console.firebase.google.com/u/0/project/pinkymind-6e0d9/hosting/main