Friday, November 22, 2019

Comparing two properties having different units - Generate line chart with two axes in C3 for multiple XY column pairs

  1. Final Code Solution
  2. Plot graph with many XY column pairs in C3 - Comparing many properties having the same unit
  3. Difficulties that you may face when feeding that function with values of variables

Final Code Solution

  This graph would have two axes having its own units, one in left representing values for the property 1 and another in the right representing values for the property 2. You can give custom names to the axes using the label attribute. The following code is to generate such a graph, but with hardcoded data. It has more possibility of raising errors but hard to identify them when modifying it for a dynamic value modification. I have listed a few such issues and solutions in the last of this chapter.


Code with hardcoded Data and Settings

const chart = c3.generate({
bindTo: '#chart',
  data: {
    xs: {
// corresponding columns of x of y columns (X axes for Ys’).
      'InputSetY1':'InputSetX1',
  'InputSetY2':'InputSetX2'
    },
    columns: [
      ['InputSetX1', 10, 20, 25, 30, 40],             // length of 5
      ['InputSetY1', 50, 20, 150, 110, 170],            // length of 5
      ['InputSetX2', 10, 15, 20, 25, 35, 40],         // length of 6
      ['InputSetY2', 120, 80, 260, 210, 220, 320]        // length of 6
    ],
    axes: {
      'InputSetY1':'y',
      'InputSetY2':'y2'
    }
  },
  axis: {
    x: {
      show: true,
      label: {
        text: 'Time (X Axis Tittle)',
        position: "outer-center"
      },
      multiline: true,
    },
y: {
  label: {
        text: 'Y Left Axis Name - InputSetY1',
        position: 'outer-middle'
  }
    },
y2: {
  show:true,
      label: {
        text: 'Y Right Axis Name - InputSetY2',
        position: 'outer-middle'
      }
    }
  }

});

Dynamic data and settings fed using variables

// Data to be provided
const y1Name = 'InputSetY1';
const y2Name = 'InputSetY2';

const y1Data = [120, 80, 260, 210, 220, 320]; // length of 5
const x1Data = [10, 20, 25, 30, 40];          // length of 5

const y2Data = [50, 20, 150, 110, 170];   // length of 6
const x2Data = [10, 15, 20, 25, 35, 40];      // length of 6

// Settings to fix the errors
const xs = {};
xs[y1Name]= 'x1';
xs[y2Name]= 'x2';

const axes = {};
axes[y1Name]= 'y';
axes[y2Name]= 'y2';

const chart = c3.generate({
bindTo: '#chart',
  data: {
    xs: xs,
    columns: [
      ['x1'].concat(x1Data),
      [y1Name].concat(y1Data),
      ['x2'].concat(x2Data),
      [y2Name].concat(y2Data)
    ],
    axes: axes
  },
  axis: {
    x: {
      show: true,
      label: {
        text: 'Time (X Axis Tittle)',
        position: "outer-center"
      },
      multiline: true,
    },
y: {
  label: {
        text: y1Name,
        position: 'outer-middle'
  }
    },
y2: {
  show:true,
      label: {
        text: y2Name,
        position: 'outer-middle'
      }
    }
  }
});

Note: You must not use dot notation when you are using with variables values as keys.

For Beginners

  Graphs are good to catch more information in one view rather than merely looking at unprocessed data. C3 graph is a popular JavaScript framework used to plot graphs from columns of data given. There are several examples given in the C3 official website. Though, there may be few varieties of our needs missing. This chapter is to discuss such a graph scenario where it is needed to compare two properties in one plane but it has two axes that represent values of the properties with their unit respectively. Also, we also discuss some difficulties arisen when changing its data dynamically.

Install C3 module

  I assume that your project is managed with NPM. Installing the C3 component is easy with NPM, just invoking following command in command prompt or terminal from the project’s directory. It will install the module, add it to the dependency file (package.json) and also include it to the app module (app.module.ts). 
  npm install c3  

  First, you need to import C3 into the script where you need to plot the graph. In angular, following snippet of code import all from the c3 module.
  import * as c3 from 'c3';  

Simple Line Chart Example

  You might have got to know basics functions used to plot graph in C3 script. “generate” function is used to plot the chart initially with given axes and data initially. The following script would generate a simple line chart for set hard-coded data provided. You may change inputs of its fields into variables to dynamically plot graphs with different data inputs. The “bindTo" attribute is used to plot the graph inside a particular HTML element specified by its id rather than creating one itself.
  const chart = c3.generate({
      data: {
          bindto: '#chart',
          x: 'x axis',
          columns: [
              ['x axis', 50, 40, 90, 220, 400, 290],
              ['InputSetY1', 40, 200, 100, 300, 450, 250],
              ['InputSetY2', 150, 310, 230, 330, 150, 440]
          ]
      }
  });

  The data set for both x-axes and y axes to plot the graph are feed to the field 'columns' as an array inside the 'data' object. The first values in the arrays inside the column array are used to determine which data series belongs to which axis. You can load the chart with another set of columns using the 'load' function dynamically. It can also be used with the time-related JavaScript inbuilt functions 'setInterval' or  'setTimeOut' which will expose viewers to an animation view.
  chart.load({                                                       
      columns: [                                                     
          ['InputSetY2', 90, 140, 90, 170, 70, 140]  
      ]                                                                     
  });                                                                      

The provided columns can also be unloaded with their ids.
  chart.unload({               
      ids: 'InputSetY1'        
  });                                  

Plot graph with many XY column pairs in C3 - Comparing many properties having the same unit


It is similar to our topic here but both y-axes are properties of the same unit. So, the chart would have only one Y-axis. Hence, you do not have to specify the data set for the y-axis.

Note: You must consider inverted commas (type) of both attributes and values and it may not work otherwise.

const chart = c3.generate({
bindTo: '#chart',
  data: {
    xs: {
// corresponding columns of x and y pairs (X-axes for Ys’).  y:x
'InputSetY1':'InputSetX1',
  'InputSetY2':'InputSetX2'
    },
    columns: [
      ['InputSetX1', 10, 20, 25, 30, 40],             // length of 5
      ['InputSetY1', 50, 20, 150, 110, 170],     // length of 5
      ['InputSetX2', 10, 15, 20, 25, 35, 40],         // length of 6
      ['InputSetY2', 120, 80, 260, 210, 220, 320] // length of 6
    ],
  },
  axis: {
    x: {
      show: true,
      label: {
        text: 'Time (X Axis Tittle)',
        position: "outer-center"
      },
      multiline: true,
    },
y: {
  label: {
        text: 'Y Left Axis Name - InputSetY1',
        position: 'outer-middle'
  }
    }
  }
});



Warning: It requires meaningful names for data columns of y-axes since they are indicated below the graphs with their line colors.
Example: we are using ‘InputSetY1’ and ‘InputSetY2’  here.

Difficulties that you may face when feeding that function with values of variables

Inside the general function, a variable should not be given as a string argument inside a nested object which is an argument to the generate function. The following kind of errors may arise and difficult to detect if do so.
  1. Values of the second Y-axis in the right are not given but in decimal range 0 to 1.
  2. Error: x is not defined for id = "InputSetY1".

Solution: Define an empty object, set the values for corresponding keys(variables) and use the object as argument inside the nesting object.
const Obj1= {};
Obj1[variable_name] = ‘xInputSet1’;
Obj1[variable_name] = ‘xInputSet2’;

Note: You must not use dot notation when you are using with variables values as keys.

1. Values of the second Y-axis in the right are not given but in decimal range 0 to 1.
    If the corresponding axis is not set for the data Y2, C3 will not plot the graph with appropriate values for the second y-axis. However, two charts will appear with two axes everything as expected except the second y-axis wrong range of values problem.
Solution:
const axes = {};
axes[InputSetY1]= 'y';
axes[InputSetY2]= 'y2';
2. Error: x is not defined for id = "InputSetY1".

  ERROR Error: x is not defined for id = "x1".               
      at c3.js:6902                                                               
      at Array.forEach (<anonymous>)                              
      at ChartInternal.convertDataToTargets (c3.js:6900) 
      at ChartInternal.initWithData (c3.js:1411)                
      at ChartInternal.init (c3.js:1271)                                
      at new Chart (c3.js:83)                                               
      at Object.generate (c3.js:1249)                                  
It might be link c3.js TypeError: b.value is undefined in Mozilla browsers.
Solution:
const xs = {};
xs[InputSetY1]= ' InputSetX1';
xs[InputSetY2]= ' InputSetX2';

Complete Code.: Given at the very beginning

Tags: two-axis line chart, C3 chart with two axes, multiple set of xy data set, C3 chart, Compare properties of two units C3 chart library, C3 JavaScript chart library,  generate c3 graph with dynamic values, generate c3 chart using variables inside, c3.js TypeError: b.value is undefined, c3.js Error: x is not defined for id.

Tuesday, November 19, 2019

How to generate SSH public and private key pair, connect to an external server, configuring an nginx server and deploy an angular application

  1. Generate Public and Private SSH key pair in git bash Command Prompt/ Terminal.
  2. Connect to a Remote Server in CMD.
  3. Install NPM – Node Package Manager in a Server.
  4. Deploy or Update an Angular Application in a Server.
  5. Configure an nginx server.

Prerequisites

Interface: CMD or Terminal (Windows or Ubuntu/Linux Systems)

Prerequisites to Ubuntu/Linux or Windows Systems:
Git bash CLI installed
Windows: Download git bash installation binary package(msi) from its official site and install it like other programs. You may set path to its bin folder so that you can also access the git from CMD of windows. How to set path in windows.

Ubuntu/ Linux: Just execute following commands in terminal. It might ask you for password authentication. You do not have to set path here.
sudo apt-get update
sudo apt-get install git-core
sudo git –version                // to verify that git installed successfully

Generate Public and Private SSH key pair in git bash Command Prompt/ Terminal

Git bash consists of the SSH package by default.

Windows

   Run git bash as administrator. Right click on git bash icon, run as administrator and ok to accept warning popped up. or you may use CMD also with git command if the path set.
  1. Go to your User folder in C:/Users/<User Account>
  2. Create a directory named .ssh if not already exists. You can check existence of the director with ‘dir’ command which lists down everything inside the user directory.
  3. Generate public-private key pairs with ssh-keygen command from the directory ‘.ssh’. It will ask you for a name for the key pair. Enter any meaningful name related to the server. With or without extension does not matter. Then it asks for a pass phrase, provide if you need the feature or just hit enter otherwise.
  4. Now, the key pair has been generated. You can see them in explorer with the command “explorer .”. It would have two files, the one with the name you just provided and another with .pub extension to the name. if you add -o argument to the command it will save generated private key in a form more resistant to brute force attack.
  5. You can check with the private and public key that created inside the .ssh folder with ‘explorer .’ command.
 1. cd c:/users/<user>

 2. mkdir .ssh       
//ignore this line if the dir already exists.

 3. cd .ssh
 4. ssh-keygen -o
Enter file in which to save the key (C:\Users\<user>/.ssh/id_rsa):
                                                                             SERVER1KEY
Enter passphrase (empty for no passphrase):   ¿
Enter same passphrase again:                         ¿
Your identification has been saved in new.
Your public key has been saved in new.pub.

 5. explorer .

Ubuntu/ Linux

  1. To checkout .ssh folder, cd ~/.ssh.
  2. You can check if any ssh key already exist with command ‘ls’ from .ssh folder.
  3. You do not have to execute the ssh-keygen command from .ssh folder in Ubuntu systems. Executing the ssh-keygen command would create new key inside folder .ssh and also create .ssh folder if already not exists. 
  4. You can also copy public key with the command “cat ~/.ssh/id_rsa.pub”.
 >  cd ~/.ssh
 >  ls

 >  ssh-keygen -o
Enter file in which to save the key (/home/<user>/.ssh/id_rsa): NEW_KEY
Enter passphrase (empty for no passphrase):   ¿
Enter same passphrase again:                         ¿
Your identification has been saved in NEW_KEY.
Your public key has been saved in NEW_KEY.

 >  cat ~/.ssh/id_rsa.pub
l8JP99FWl8iyjNa1XUleoxTNkSP9mrZMpPC8fY.ZnbdDWtw7gyibMQpc
Z8DBrqszpFjwtezrAZXJABFcSdqMFm1Q=rQcEEn/75WKa3bbAQyAdlv
ATmaHE7VAoriJAhoQ8BrXpI/p+GcTG10z2dOHUoV@sWvivT3ecjC3po
ZWp3Ap/SnKkMlTri5BhEOauPrwc6syaHs6z9h/oL3nK48nDXdUcPsVM
1/biIBMFOEP6u3AR4AQV56omKWjbttaaRlljx+rlw=AX/TwRX1v2aVJV
8y/HVYry1l92ISFlwa4PdNyb1Nw+jaYlKUAkQA09E3wk1Ax7fLTxnAZ7
FnnpJXI+QAmDlrMFlfmXrNbgIIs0LkhRbD4vH+HfSLoFhm0wA81q7NA

You have successfully generated the SSH public-private key pair.

   Now you need to send your public key (the one with .pub extension) to supervisor or the person who owns the server account and ask to add your public key to the server authentication list. They will add it and provide you with the following details.

Host name: Ip address (###.###.###.###) or a domain name (www.server-url.com)
User name: Assigned by the supervisor.

Connect to a Remote Server in CLI

You can connect to the server directly via a CLI/ Terminal. If you often connect to the server, creating a config file make it easy and save time.
  1. Go to the .ssh directory.
  2. Create a text file and save it as config with no extension. (All file types and then ‘config’ as name barely).
Content of the text file:Update fields highlighted in red with your server information and save the file. The port field is optional and you do not include if it is not provided. Notice that field names are followed by a space and by corresponding values then.
Host <ANY_NAME> // will be used to connect to the server
    HostName <ip or domain name>
    User <user name assigned by the supervisor>
    IdentityFile ~/.ssh/<the key name given when generating the key pair>
    IdentitiesOnly yes
    Port <SERVER_PORT>         //It is optional and 8080 by default.
    ServerAliveInterval 60

Now you are done with the configuration and just connect to go.
  1. Run Git or CMD as administrator.
  2. Just type following command to connect to the server.
SSH ANY_NAME                  

   That is all. Now, you will have connected to the server in CLI mode. Any operation allowed by the supervisor can be done through it.

Install NPM – Node Package Manager in a Server

   NPM is distributed and installed with Node.js. We can download and install if it is a Microsoft server simply. But we often met with Ubuntu servers. We are using curl so that we would install NodeJS version of our choice. Invoke following commands in the terminal will be installing NodeJS of version v13.0.1 and corresponding NPM of version 6.12.0.

 >  sudo apt-get install curl
 >  curl -sL https://deb.nodesource.com/setup_13.x | sudo -E bash –
 >  sudo apt-get install nodejs
 To check whether installed that it installed properly and not a must
 >  sudo npm -v
          // Output will be like v13.0.1
 >  sudo npm -v
          // Output will be like 6.12.0

Now, you are done and have installed the NPM successfully.

Deploy or Update an Angular Application in a Server

   Once you have connected to a server, you will be in the home directory of the system. It is assumed that you have your project in a git repository. It is also assumed that you are using a nginx server. If you are using Apache server instead, setting up the server is easy, just copy the built outcome script in step 3 into the WWW directory by using the command “cp".

Newly Deploy an Angular APP to a server

Install NPM – Node Package Manager if not installed previously (discussed above) and You can check whether NPM exists with the command “npm -v”.
  1. Clone the project into the server. It might ask you to authenticate with user name and password. Provide them and go. If cloning is successful, it means you project source code is now on the server. You can check with the command “ls” which will list everything inside home directory and also your newly clone project.
  2. Install the application: It is to download and setup all dependencies of the project. i.e: getting node modules directory fulfilled.
  3. Build the angular application: It will optimize code and build all scripts into a form that can be run without angular CLI. 
  4. Configure NGINX file. Next lesion will be about configuring nginx. Look at there for it.
 >  git clone <remote-url>                       //You may need to sign in
Optional; listing everything inside home directory and the project
 >  ls

 >  cd <project_name>
 >  npm install

 >  ng built –prod

Update an angular app in a server

   This is almost same as new deployment but you do not need to clone project and configure the nginx. But you need to pull instead to adopt updates in the repository to the server.
  1. Pull the project: It would bring changes committed last to the repository to the server. Important: You may need to handle conflicts but I will not teach you that here.
  2. Install the application: It is required since repository may have some dependency changes in the “package.json” file.
  3. Build the angular application.
  4. If it is Apache server, copy the distribution folder and merge the one in the WWW directory with it.
 >  cd <project_name>
 >  git pull                           //You may need to sign in

 >  npm install

 >  ng built –prod
 Similar following command to copy compiled distribution
 if you use Wamp server
 >  cp ~<project_name>/dist/<project_name>  ~wamp64/www

Configure an nginx server

   I am not going to teach all the things related to configuring an nginx website configuration file in detail. I am just considering the server section of site-enable file which is basically required to configure to make your site running. If you really want in more depth, you can go with this link How to Configure NGINX or Full ExampleConfiguration at Nginx official site. Also, if your server is not installed with nginx, read Install Nginx on Ubuntu.
   Nginx server would have created a configuration file called “default.conf” inside /etc/nginx/sites-enabled/ and linked with the “nginx.conf” file (/your-app/config/nginx.conf). You may create any number of conf files as you want and define them in the “nginx.conf” file. But one is enough for a basic configuration.
1.     server {
2.         listen         80 default_server;                                       //ipv4
3.         listen         [::]:80 default_server;                                 //ipv6
4.         server_name    sample.com www.sample.com;
5.         root           /var/www/sample.com;
6.         index          index.html index.htm;
7.         try_files    $uri  $uri/  /index.html;
8.     }
  1. Search for the server section in the file. There can be one or more server sections defining roots to web applications in the server. But there will be only one in a fresh server on which the nginx just been installed. 
  2. There are 6 important fields in the section but you may be wanted to modify few where others will be kept as default. The server_name (line 4), root (line 5), index (line 6) and try_files must be ensured that they are correct.
Server_name: The browser determines that with which server it is connected.
Root: This field defines in which directory the server should be looking for application to be served at the server name.
Index: You will be defining the startup point of the web application. It can be combination of index.htm, index.php, index.html or index.
Try_files: This must be defined to avoid application retrieval failure in refresh when we are looking for sub-pages of it. Example: www.neckoverpain.com/this-is-my-page-1

It might be like following in some of the nginx versions.

 location / {
         try_files $uri $uri/ /index.html;

Tags: Linux Server, Ubuntu Server, connect to a server, install nodeJS Ubuntu, install node package manager in Ubuntu, update the server..

Whats New

How redundant uploads can be avoided in social media apps?

People spend more time on social media, and it influences the most and changes to societies. They want to share photos and videos often when...

You may also like to read

x

emailSubscribe to our mailing list to get the updates to your email inbox...

Delivered by FeedBurner