Ubuntu Quick Reference

change folder ownership

sudo chown -R $USER /var/www  

Rename folder

mv CodeIgniter-3.1.6/ codeignitor316  

Copy Folder (Please make sure folder path is from root directory and not the relative path)

sudo cp -r /var/www/mediawiki /var/www/mediawiki  

Copy File

sudo cp filename1.py /var/www/filename2.py  

unfiz tar file

tar xzf file.tar.gz  

List of installed softwares. Second command will save this list in text file.

apt list --installed  
dpkg --get-selections > list.txt  

Uninstall app

sudo apt remove <app_name>

NGINX start and stop

sudo ln -s /etc/nginx/sites-available/techtrekking.com /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl restart nginx
# Error log
tail -f /var/log/nginx/error.log

Update local host file

sudo -i gedit /etc/hosts

 

Upgrade sublime text

sudo apt-get install --only-upgrade sublime-text

Some useful commands

Activity command
start
sudo service postgresql start
stop
sudo service postgresql stop
restart
sudo service postgresql restart
Update Host file
sudo nano /etc/hosts
Reboot
sudo reboot

Getting started with PHP

Your PHP code goes inside the

<?php  
code here  
?>

To display text in HTML output page

echo "this is output";  

Make sure to end your line of PHP code with a semicolon

;
String Manipulations
<?php  
$name = "Luke Perry";
echo strlen($name); // 10  
echo substr($name, 0, 3); // Luk  
echo strtoupper($name); // LUKE PERRY  
echo strpos($name, "e Perry"); // 3  
// concatenation
echo "hello" . "user";  
?>
Variables

All variable names in PHP start with a dollar sign

$temp
Comment

comment is started with either of following code

//

or

#
Operators
> Greater than
< Less than  
<= Less than or equal to  
>= Greater than or equal to
== Equal to
!= Not equal to
Conditional Sentence
    if ( 2 > 10) {
        echo " ok";
        }
    else if ( 2 == 33 ) {
        echo "ccc";
        }
    else if ( 3 == 34) {
        echo "this is 3";
    }
    else {
        echo "nothing mathcn";
        }
switch
    switch (2) {
        case 0:
            echo 'The value is 0';
            break;
        case 1:
            echo 'The value is 1';
            break;
        case 2:
            echo 'The value is 2';
            break;
        default:
            echo "The value isn't 0, 1 or 2";
    }

Using or clause with switch

    switch ($i) {
        case 0:
            echo '$i is 0.';
            break;
        case 1:
        case 2:
        case 3:
        case 4:
        case 5:
            echo '$i is somewhere between 1 and 5.';
            break;
        case 6:
        case 7:
            echo '$i is either 6 or 7.';
            break;
        default:
            echo "I don't know how much $i is.";
    }
Working with Array

defining array and adding new element

      <?php
        // Add your array elements after
        // "Beans" and before the final ")"
        $array = array("Egg", "Tomato", "Beans" );        
      ?>
<?php  
$states = array();
$array = array_push($states, "Montana");
$array = array_push($states, "North Carolina");
$array = array_push($states, "California");
echo $array; // returns 3  
var_dump($states);  
?>

Pushing multiple elements together

<?php  
$states = array(); // target array
$array = array_push($states, 
"Montana", 
"North Carolina", 
"California");
echo $array; // returns 3  
var_dump($games);  
?>

Print array

<?php  
echo $tens[2];  
echo $tens{2};  
?>

Modify and delete array element

$languages[1] = "green";
unset($array[2]);  
unset($array);  
Loop
        foreach($languages as $lang) {
          print "<p>$lang</p>";
        }

another example

      <?php
        // Echoes the first five even numbers
        for ($i = 2; $i < 11; $i = $i + 2) {
          echo $i;
        }
      ?>

ngnix redirect non www to www

if you want to redirect non www to www domain you need to add one more serverblock at the top of your nginx config file as beloww

server {  
        listen 80;
        server_name techtrekking.net;
        # $scheme will get the http protocol
        return 301 $scheme://www.techtrekking.net$request_uri;
}

This works for normal website as well as ghost blog.
For example if you type techtrekking.net or www.techtrekking.net it will get redirected to www.techtrekking.net.

Sample server block. THis serves following purpose

  • redirect non www to www
  • add blog in subfolder /blog
server {  
        listen 80;
        server_name yoursite.com;
        # $scheme will get the http protocol
        return 301 $scheme://www.yoursite.com$request_uri;
}

server {  
        listen 80;
        listen [::]:80;

        root /var/www/html;

        index index.html index.htm index.nginx-debian.html;

        server_name techtrekking.com www.techtrekking.com;

        location / {
                proxy_pass http://yoursite:3000;
                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection 'upgrade';
                proxy_set_header Host $host;
                proxy_cache_bypass $http_upgrade;
        }

        location /blog {
                proxy_pass http://yoursite:3100;
                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection 'upgrade';
                proxy_set_header Host $host;
                proxy_cache_bypass $http_upgrade;

        }


        location ~ /.well-known {
                allow all;
        }

}

Apache redirect non www to www using .htaccess

Its ok to allow users to access your website using www and non www address but for consistency and SEO considerations its desiratble to use one version. If you are using apache web server this can be achived by using htaccess file.

Non Www To Www

301 re-write rule in your .htaccess file so that both addresses (http://example.com and http://www.example.com) resolve to the same URL.

If you want to redirect http://www.example.com to http://example.com, you can use this:

RewriteCond %{HTTP_HOST} ^www.example.com$  
RewriteRule ^/?$ "http://example.com/" [R=301,L]  

If you want to redirect http://example.com to http://www.example.com, you can use this:

RewriteCond %{HTTP_HOST} !^www.example.com$ [NC]  
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301]  

Http To Https

RewriteEngine On  
 RewriteCond %{HTTPS} !=on
 RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]

Please note this can be used when you are using apache webserver and this is not recommended if you are using nginx. IF you wan to try it using nginx please see post
how to redirect non www to www for nginx

Webpack for react sub apps

Webpack is used to pre-compile your react component into ES5 so that it can be recognised by browsers. But what if you are webapp is hybrid and react is taking over only small portion of your webapp.

Lets suppose you have two react components, lets call them app1 and app2. Both will take over different div tag on two different pages on your website.

In this case, you can use following webpack code to precompile both of them.

var webpack = require('webpack')  
var path = require('path')

module.exports = {  
    entry:{
        app1: './src/app1.js',
        app2:  './src/app2.js'
    },
    output:{
        path: path.join(__dirname, "public/build"),
        filename: '[name].js'

    },
    devtool: '#source-map',
    module:{    
        loaders: [
            { 
                test: /.jsx?$/,
                exclude:/(node_modules)/,
                loader: 'babel-loader',
                query:{
                    presets:['react','es2015']
                }
            }
        ]

    }
}

This will create app1.js app1.js.map for app1 and app2.js app2.js.map for app2 at the destination folder.

This is working fine for me, please let me know if you run into any issues while using this.

Making server request in React Components using Axios

Axios is Promise based HTTP client for the browser and node.js. This library can be used in react component to fetch data from RESTful APIs.

Installation
$ npm install axios --save
Example
import React, { Component } from 'react'  
var axios = require('axios');  
...
        axios.get('/api/family')
            .then(response => {
            console.log(response);
            console.log(response.data);
            this.setState({
              family: response.data
            });

            console.log("family :" + this.state.family);

            })
          .catch(function (error) {
            console.log(error);
          })
...
Use of arrow function

Arrow function does not attach ‘this’ to current object and hense old this is preserved. This is needed to update state and get it reflected on rendered object.

Sample project

Please refer to this Github repo for complete code
https://github.com/conquistadorjd/react-05-mysql-api

Live project.

Please refer to following heroku site for live demo
https://react-05-mysql-api.herokuapp.com/

JSX Basics and Advanced Concepts

Take a look at following code from official react documentation

const element = <h1>Hello, world!</h1>;  

This is neither a string nor HTML. It is called JSX, and it is a syntax extension to JavaScript. It is recommended to use it with React to describe what the UI should look like.

It also means that JSX is not valid JavaScript. Web browsers can’t read it! That means file will have to be compiled before it reaches a web browser, a JSX compiler will translate any JSX into regular JavaScript.

Example

A basic unit of JSX is called a JSX element. Example of JSX element

<h1>Hello world</h1>  

JSX elements are treated as JavaScript expressions. They can go anywhere that JavaScript expressions can go.

const navBar = <nav>I am a nav bar</nav>;  

Attributes

JSX elements can have attributes, just like HTML elements can.

A JSX attribute is written using HTML-like syntax: a name, followed by an equals sign, followed by a value.

const panda = <img src="images/panda.jpg" alt="panda" width="500px" height="500px" />;  

You can nest JSX elements inside of other JSX elements, just like in HTML.
a JSX expression must have exactly one outermost element.
You can embed any JavaScript expression in JSX by wrapping it in curly braces.

Since JSX is closer to JavaScript than HTML, React DOM uses camelCase property naming convention instead of HTML attribute names.

Rendering of JSX element

ReactDOM.render(<h1>Hello world</h1>, document.getElementById('app'));  
  • One special thing about ReactDOM.render() is that it only updates DOM elements that have changed and this is what makes React very fast.
Advanced JSX

Syntax in JSX is mostly the same as in HTML, but there are subtle differences.

  • In JSX, you can’t use the word class! You have to use className instead.
<h1 class="big">Hey</h1>  
<h1 className="big">Hey</h1>  

This is because JSX gets translated into JavaScript, and class is a reserved word in JavaScript. When JSX is compiled, className gets translated into class.

  • in JSX for you have to include slash for closing tag. in HTML closing slash is not madatory for tags such as ‘< image>’ and ‘< br>’
  • Any code in between the tags of a JSX element will be read as JSX, not as regular JavaScript. You need to use curlt braces to inject JavaScript inJSX. The curly braces themselves won’t be treated as JSX nor as JavaScript. They are markers that signal the beginning and end of a JavaScript injection into JSX.
const pi = (  
  <div>
    <h1>
      PI, YALL!
    </h1>
    <p>
      {Math.PI.toFixed(20)}
    </p>
  </div>
);

Variables can be used as JSX element properties as well.

const pics = {  
  panda: "http://bit.ly/1Tqltv5",
  owl: "http://bit.ly/1XGtkM3",
  owlCat: "http://bit.ly/1Upbczi"
};
const sideLength = "200px";  
const owlCat = (  
  <img 
    src={pics.owlCat} 
    alt="Ghastly Abomination"
     height={sideLength}  />
);

Event Handling

JSX elements can have event listeners, just like HTML elements can. Programming in React means constantly working with event listeners.

<img onClick={myFunc} />  

An event listener attribute’s value should be a function. The above example would only work if myFunc were a valid function that had been defined elsewhere:

list of valid events can be found here

If Else

Tertiary operator

The ternary operator works the same way in React as it does in regular JavaScript. However, it shows up in React surprisingly often.

x ? y : z  

x is evaluated as either “true” or “false”.
If x is “true” tertiary operator returns y
If x is “false” tertiary operator returns z

Usage
const headline = (  
  <h1>
    { age >= drinkingAge ? 'Buy Drink' : 'Do Teen Stuff' }
  </h1>
);

JSX Conditionals: &&

.map in JSX

The array method .map() comes up often in React. If you want to create a list of JSX elements, then .map() is often your best bet.

const strings = ['Home', 'Shop', 'About Me'];

const listItems = strings.map(string => <li>{string}</li>);

<ul>{listItems}</ul>  

Learning React

React is not like Angular where many decisions are already made for you. In React, you have to make many decisions. Also, learning react means you need to learn multiple components like react-router, Redux etc.

This could be overwhelming and it could get you confused. So I decided to take a step by step approach to learn React.

Step#1 : Learning Path

  • Learn ES6 (At least overview and few concept like map and reduce)
  • What is React
  • JSX
  • Virtual DOM
  • Rendering
  • Components
  • Props
  • State
  • Event handling
  • Routing
  • Redux

Step#2 : Resources : getting started

There are tons of material and don’t confuse yourself with these. Stick to Most reliable and widely use approach and chances of distraction will be very less.

Step#2 : Resources : advanced (to be updated)

This is no way complete list and I will keep updating it as and when I find relevant material. If you have come across any good material, please let me know.

How to migrate Ghost blog from SQLite3 To MySQL

Migrating Ghost blog from SQLite3 to MySQL is fairly simple process. You need to export your posts, configure MySQL for Ghost and lastly, you need to import previously exported posts and you are done. Please follow below mentioned steps.

Step#1: Exporting the Ghost Blog posts.
Login to ghost blog as admin using following link
http://yourblog.com/ghost/ OR http://yourblog.com/admin

Go to labs option and clock on export.

It will create a json file. Keep this file handy as we will import same file after we have configured MySQL.

Step#2: Install MySQL
Please ensure MySQL is installed on your machine. You can follow how to install MySQL on ubuntu.

Step#3: create user for ghost blog
Login to MySQL as root using following command. It will ask for root password.

$ mysql -u root -p

Create database as well as user by using following commands

mysql> create database ghost;  
mysql> CREATE USER 'ghost'@'localhost' IDENTIFIED BY 'password';  

Now add grant user to database

mysql> grant create, delete, insert, select, update, alter,references ON ghost.* TO 'ghost'@'localhost';  

and now flush the newly added access.

mysql> flush privileges;  

Step#4: edit config file to use MySQL
Configure to use production database as mentioned in this post.
Your final config file snippet is as below:

        database: {
            client: 'mysql',
            connection: {
                host: 'localhost',
                user: 'username',
                password: 'password',
                database: 'ghost',
                charset: 'utf8'
            },
            debug: true
        },

Step#4: Now run your blog in production mode as mentioned in post using ghost in production and development mode.

$ npm start --production

Step#5 Importing previously exported blog dump.
Again Login to ghost blog as admin using following link
http://yourblog.com/ghost/ OR http://yourblog.com/admin

Go to labs option and clock on import and use the previously exported file.

This worked well for me, please let me know if you run into any issues…

Recommendations.
Having seen that, I would recommend using SQLite3 as a database someone has said, don’t fix it until its broken and considering SQLite can handle 100k hits per days (which cover most of the websites) there is no need to create extra work for yourself by moving database to MySQL. However you must note that, GhostPro uses MySQL database and ghost officially has dropped support for PostgreSQL.

Please refer to SQLite documentation for further clarification.