Monthly Archives: June 2017

What is Angular 2 or Angular 4? High level overview, feature and fundamentals.

By S Sharif In this article, we will see a high-level overview of Angular 2 or Angular 4. Also, we will see some unique features of Angular 2 and Angular 4. These features make it more powerful and…

The post What is Angular 2 or Angular 4? High level overview, feature and fundamentals. appeared first on Technical Diary.

Visit www.technicaldiary.com to read, full article.

Source:: TECHNICALDIARY

Announcing Angular Master Class in Houston

AMC Houston Event Location

While we just returned from Denmark and announced another upcoming Angular Master Class in Berlin, we know that people want us to run our training all around the world.

It’s been a couple of month since we’ve last run our training in the US so we are very pleased to announce that our Angular Master Class is coming to Houston in August!

We’ve found the perfect, artsy venue to get into the right piece of mind to learn Angular in and out.

The event takes place on the 22nd to 25th August 2017 in the Bisong Art Gallery.

The bulk of the training happens on the first three days whereas day four is optional and covers Redux and ngrx. Join us for a couple of days of learning and fun including things like

  • Components and Modules
  • Fetching data using Http
  • Advanced Dependency Injection
  • Basic Forms
  • Observables deep-dive
  • Architectural patterns
  • ContentChildren and ViewChildren
  • Template-driven Forms
  • Reactive Forms
  • Observables deep-dive
  • Children routes and lazy-loading
  • Redux and ngrx

…and many more!

Tickets on sale now

The early bird round of tickets is on sale now. You can save up to 150,00 USD so you’ll better be fast. Seats are very limited with only 5 early bird tickets available!

Come to our training… have a blast and get the best acceleration into Angular possible. You can find more information on our official event page, or grab your ticket right here!

See you in Houston!

Source:: Thoughtram

Node.js Weekly Update - 23 June

By Ferenc Hamori

Node.js Weekly Update - 23 June

Below you can find RisingStack‘s collection of the most important Node.js updates, projects, tutorials & Node related conferences from this week:

Node.js Will Overtake Java Within a Year

Mikeal Rogers has been with the Node.js Foundation since day one. His job as community manager for the foundation involved hands-on oversight of operations, from communications and marketing to conference planning, to running board meetings

Node.js Weekly Update - 23 June

Rogers spoke with The New Stack to talk about his experience getting started in the open source world, working at the Node.js Foundation and becoming an open source governance principals guru.

Building a Node.js App with TypeScript Tutorial

This tutorial teaches how you can build, structure, test and debug a Node.js application written in TypeScript. To do so, we use an example project which you can access anytime later.

Node.js Weekly Update - 23 June

Managing large-scale JavaScript projects can be challenging, as you need to guarantee that the pieces fit together. You can use unit tests, types (which JavaScript does not really have), or the two in combination to solve this issue.

his is where TypeScript comes into the picture. TypeScript is a typed superset of JavaScript that compiles to plain JavaScript.

Here’s what you need to know about npm 5

I’m sure you’ve heard the news by now, npm5 is here and it’s faster, stabler, and more secure than ever!

Node.js Weekly Update - 23 June

Testing Node.js Applications (Webinar)

The “Testing Node.js Applications” course takes four weeks, with 2-hour webinars (3 in total) and a 1-on-1 session tailored for your special needs.

Node.js Weekly Update - 23 June

This course is for you if

  • you want to learn how to properly test Node.js applications,
  • you want to ship software with fewer bugs,
  • you want to work on features more instead of fixing bugs.

Creating a project generator with Node

By the end of this tutorial, you’ll be able to type $ generate anywhere on your computer, choose which starter project you want to create and what name you’d like to give it, and it will be created for you.

Node.js Weekly Update - 23 June

In this post, I’ll walk you through how to create a simple project generator built with NodeJS that can be installed globally on your computer and used to create a starter project wherever you want, whenever you want.

Enterprise Conversations Episode 13: Node.js and Intel

Monica Ene-Pietrosanu of Intel discusses how Intel uses Node.js, and the company’s efforts in contributing to open source technologies and diversity.

Gathering weak npm credentials

Or how I obtained direct publish access to 13% of npm packages (including popular ones). The estimated number of packages potentially reachable through dependency chains is 52%.

Node.js Weekly Update - 23 June

In this post, I speak about three ways of gathering credentials — bruteforce attack, known accounts leaks from other sources (not npm), and npm credentials leaks on GitHub (and other places).

Upcoming Node.js & JavaScript Events

Source: The Node Foundation Newsletter

Previously in the Node.js Weekly Update

In the previous Node.js Weekly Update we read about two factor authentication with Node.js, Hacker Habits, the latest Node.js Survey, and much more..

We help you to stay up-to-date with Node.js on a daily basis too. Check out our Node.js news page and its Twitter feed!

Source:: risingstack.com

Announcing Angular Master Class in Berlin

AMC Berlin Event Location

We just returned from Denmark after running yet another Angular Master Class with a very diverse group of attendees from a wide range of different countries.

If you haven’t had the chance to join us in Denmark you really missed out on a fun event! However, here are good news: We are bringing our Angular Master Class to Berlin soon!

We are happy to team up with Westernacher Solutions AG to run the training in a really cool atmosphere with lots of room to teach, learn and have fun!

AMC Berlin Event Location

The event takes place on the 18th to 20th September 2017 in one of the most vibrant parts of the city.

We will have three (3) days of fun and learning the ins and outs of Angular including things like

  • Components and Modules
  • Fetching data using Http
  • Advanced Dependency Injection
  • Basic Forms
  • Observables deep-dive
  • Architectural patterns
  • ContentChildren and ViewChildren
  • Redux and ngrx

…and many more!

Tickets on sale now

The early bird round of tickets is on sale now. You can save up to 125,00 € so you’ll better be fast. Seats are very limited with only 5 early bird tickets available!

Come to our training… have a blast and get the best acceleration into Angular possible. You can find more information on our official event page, or grab your ticket right here!

See you in Berlin!

Source:: Thoughtram

Quick Tip: Snippets to Add Styles to Angular v2+ Templates

By Chris Sevilleja

Angular allows for many different ways to add classes to your templates. We’ll explore the different ways including:

  • class property bindings: [class] and [className]
  • style property bindings: [style]
  • The ngClass directive
  • The ngStyle directive

Using Property Bindings

With property bindings, Angular allows us to grab the HTML attributes directly. This way, don’t have to remember any extra directives. We can just use the HTML attributes we already know.

In this example, we’ll be using [class] and [style] with the Angular property bindings [].

Using the class Property Binding

We can call class and the class name that we want to use. Whatever is on the right side of the = will be evaluated to be truthy or falsy. If truthy, Angular will apply the class.

// using class
<div [class.isActive]="myIsActiveVariable"></div>

// using className
<div [className]="'goBlue'"></div>

<div [className]="myClassVariable"></div>

Using the style Property Binding

In addition to binding to class and className, we can bind to style.

// a simple implementation
[style.color]="'blue'"
// in the class
myColor = 'red';
[style.color]="myColor"

// both of the following work
[style.background-color]="myColor"
[style.backgroundColor]="myColor"

Using ngClass

The ngClass Angular directive provides us many different ways we can bind classes to our elements.

The benefit of using ngClass is that it will be easy to bind multiple classes:

<!-- bind 2 classes directly with an array -->
<div [ngClass]="['firstClass', 'secondClass']"></div>

<!-- same result, bind 2 classes as a full string -->
<div [ngClass]="'firstClass secondClass'"></div>

<!-- evaulate each class to see if it should be applied -->
<div [ngClass]="{ firstClass: isFirstActive, secondClass: isSecondActive }"></div>

Using ngStyle

The ngStyle Angular directive allows us to bind styles directly to an element’s style attribute. Instead of adding a class, we can directly apply the style.

<!-- a simple ngstyle usage -->
<div [ngStyle]="{ color: red }"></div>

<div [ngStyle]="{ color: isDanger }"></div>

<!-- when binding to an attribute with a dash, make sure you use single quotes -->
<div [ngStyle]="{ 'background-color': 'blue', 'font-size': '17px' }"></div>

<!-- bind the width as a specific measurement -->
<div [ngStyle]="{ 'width.%': myVariable }"></div>
<div [ngStyle]="{ 'width.px': myVariable }"></div>

Conclusion

Using the above tactics, it’s easy to add styling to your Angular v2+ templates!

Source:: scotch.io

Integrating Monaca with API.AI

By Khemry Khourn

Import the project into Monaca Cloud IDE

In this article, you will learn how to create a conversational app with Monaca Cloud IDE and api.ai. api.ai is a natural language interactions platform created by Google. We will demonstrate how to integrate Google’s api.ai with Monaca Cloud IDE using Angular 1 and Onsen UI v2. The integration is done based on apiai-cordova-client plugin.

The implemented features of this sample application are:

  • text conversation in a predefined languages: English and Japanese
  • voice conversation in a predefined languages: English and Japanese
  • language settings: currently available languages are English and Japanese

Tested Environments: Android 7.0 & iOS 10.1

Getting Started with api.ai

API.AI is a natural language understanding platform that makes it easy for developers (and non-developers) to design and integrate intelligent and sophisticated conversational user interfaces into mobile apps, web applications, devices, and bots.

An API.AI agent represents a conversational interface of the application. An intent determines what kind of user requests should be understood and to what actionable data (JSON response) those requests should be converted.

In this sample application, we created two simple agents:

  • MonacaAI_EN: a conversational interface in English
  • MonacaAI_JA: a conversational interface in Japanese

Each agent has the same number of intents about daily conversation such as food, weather, greeting and so on.

Note: We won’t talk about how to create an agent or an intent in this article. Please refer to the official documentation on how to get started with api.ai.

Step 1: Prerequisite

In order to integrate api.ai with Monaca, Client access token of an agent is required to initialize with apiai-cordova-client plugin.

In order to find the Client access token of an agent, please do as follows:

  1. Go to api.ai console.
  2. Select an agent.
  3. Click on Settings icon (see the screenshot below)

Settings icon

  1. Then, the following page will be shown and you can find the Client access token here.

Client Access Token

Step 2: Importing This Project into Monaca Cloud IDE

Step 3: Understanding the Application

File Tree

In this sample application, there are 3 main files such as:

  • index.html : The startup page consists of HTML, Onsen UI v2 and Angular 1 elements.
  • style.css: This is a stylesheet for the application.
  • app.js: An Angular 1 file containing a service and a controller used in the application.

index.html

This is, of course, the main page of the application, the one loaded by default. As you can see, this application has 3 tabs represented by 3 pages: text.html, voice.html and lang.html. These 3 pages are created using ons-template within index.html file.

Text Converation (English)

In this section, we will explain how each page components are created. Firstly, we start by creating a tabbar component using ons-tabbar. Here is a code snippet of the tabbar containing 3 tabs:

[...]
<ons-tabbar var="myTabbar">
    <ons-tab label="Text" page="text.html" active><ons-icon icon="ion-android-textsms" size="30px"></ons-icon></ons-tab>
    <ons-tab label="Voice" page="voice.html"><ons-icon icon="ion-mic-a" size="30px"></ons-icon></ons-tab>
    <ons-tab label="Settings" page="lang.html"><ons-icon icon="fa-language" size="30px"></ons-icon></ons-tab>
</ons-tabbar>
[...]

Now let’s start creating each required page using ons-template component. The first page is text.html for a text conversation. Here is a code snippet of this page:

[...]
<ons-template id="text.html">
    <ons-page>
        <ons-toolbar>
            <div class="center">Monaca x API.AI</div>
        </ons-toolbar>

        <div class="page">
            <h4>Text Conversation ({{current_lang}})</h4>
            <ons-list>
                <ons-list-item ng-repeat="rowContent in textRows" modifier="nodivider">
                    <ons-row class="question"><span>{{rowContent.question}}</span></ons-row>
                    <ons-row class="answer"><span>{{rowContent.answer}}</span></ons-row>
                </ons-list-item>
            </ons-list>
        </div>
        <div class="stay_bottom">
            <ons-input type="text" ng-model="question" id="text-question" placeholder="Type your question here..."></ons-input>
            <ons-button modifier="quiet" class="float-right" ng-click="sendText(question)"><ons-icon icon="ion-android-send" size="20px"></ons-icon></ons-button>
        </div>    
    </div>    
    </ons-page>
</ons-template>
[...]

Text Conversation (English)

The second page is voice.html for a voice conversation. In this page, a user will start asking a question by tapping on START RECORDING button. Then, the question will be sent and reply will be displayed. Here is a code snippet of this page:

[...]
<ons-template id="voice.html">
    <ons-page>
        <ons-toolbar>
            <div class="center">Monaca x API.AI</div>
        </ons-toolbar>

        <div class="page">
            <h4>Voice Converation ({{current_lang}})</h4>
            <ons-list>
                <ons-list-item ng-repeat="rowContent in voiceRows" modifier="nodivider">
                    <ons-row class="question"><span>{{rowContent.question}}</span></ons-row>
                    <ons-row class="answer"><span>{{rowContent.answer}}</span></ons-row>
                </ons-list-item>
            </ons-list>

            <div class="stay_bottom voice">
                <ons-button ng-click="sendVoice()">{{recordButton}}</ons-button>
                <!--<ons-button ng-click="stop()">Stop Recording</ons-button>-->
            </div>    
        </div>
    </ons-page>
</ons-template>
[...]

Voice Conversation (English)

The last page is lang.html for setting the language of the conversation. In this page, the predefined languages will be displayed. Here is a code snippet of this page:

[...]
<ons-template id="lang.html">
    <ons-page>
        <ons-toolbar>
            <div class="center">Monaca x API.AI</div>
        </ons-toolbar>

        <div class="page">
            <h4>Language Configuration</h4>
            <p style="text-align: left">Selected Language: <b>{{current_lang}}</b></p>

            <ons-list style="text-align: left">
                <ons-list-header>Currently available languages</ons-list-header>
                <ons-list-item ng-repeat="language in languages" ng-click="updateLanguage($index)" tappable>
                    {{language.title}}
                </ons-list-item>
            </ons-list>
        </div>
    </ons-page>
</ons-template>
[...]

Language Setting

style.css

This is a stylesheet file for styling each page of the application. Here is a complete code for it.

body {
    width: 100%;
    height: 100%;
    text-align: center;
}

.list-item{
    padding: 0 !important;
}
.list-item__center{
    padding-right: 0 !important;
}

div.page {
    width: 100%
    text-align: center;
    margin: 0px 10px 60px 10px;
    overflow: scroll;
}

.question {
    display: inline-block;
    float: right;
    float: right;
    margin: 0 0 5px 50px;
    text-align: right;
}

.answer {
    display: inline-block;
    float: left;
    text-align: left;
    margin: 0 50px 5px 0;
}

span {
    display: inline-block;
    padding: 5px;
    border-radius: 5px;
}

.question span {
    border-radius: 5px;
    background-color: #0096ff;
}

.answer span {    
    background-color: #ff7e79;
}

.stay_bottom {
  position: fixed;
  /*z-index: 200;*/
  right: 0;
  bottom: 50px;
  left: 0;
  text-align: left;
  text-align: center;
  border: 1px solid #777;
  border-radius: 3px;
  width: inherit;
  margin: 10px;
}

.voice {
    border: 0;
}

#text-question {
    width: 80%;
    display: inline-block;
    text-align: left;
    padding: 5px;
    float: left;
}

span.input-label {
    display: none;
}

app.js

This is an Angular 1 file containing a factory and a controller used in the application. In this sample application, we created two agents in api.ai representing Japanese and English conversations. The LanguageSettings factory is used to change the language of the conversation. It has the predefined information of the existing agents and a method to config which agent is used in the application. For example, you want to set the default language to English. This factory should be triggered as soon as the page is loaded. When it is called, it will trigger ApiAIPlugin.init() function to initialize the apiai-cordova-client plugin with the selected agent, in this case it is the agent for English conversation. Here is the code snippet of this factory:

app.factory('LanguageSettings', function() {
    var language = {};
    var languages = [
        {
            title: 'English',
            clientAccessToken: '4d723adba6c8403ea4d4c2b5acc34045',
            lang: 'en'
        },
        {
            title: '日本語',
            clientAccessToken: 'af2dc88346fc45fbade8f71a106a9dfb',
            lang: 'ja'
        }
    ];
    language.all_languages = languages;

    language.selectedLanguage = {};

    language.setSelectedLanguage = function(value) {
        this.selectedLanguage = value;        
        try {
            ApiAIPlugin.init(
                {
                    clientAccessToken: value.clientAccessToken,
                    lang: value.lang
                },
                function () {
                    console.log("Init success");

                },
                function (error) {
                    alert("Init errorn" + error);
                });
        } catch (e) {
            alert(e);
        }
    };

    return language;
});

Next, we will talk about the HomeCtrl controller. In this controller, there are 3 main functions such as:

  • sendText(): send the user’s text question to api.ai with the corresponding agent. After successfully receive a response, both question and corresponding answer will be displayed on text.html page.
  • sendVoice(): send the user’s voice question to api.ai with the corresponding agent. After successfully receive a response, both question and corresponding answer will be displayed (as text) on text.html page.
  • updateLanguage(): update the language of the conversation based on the predefined agents.

Here is the code snippet of this controller:

app.controller('HomeCtrl', function($scope, LanguageSettings, $timeout) {
    var language = {};
    $scope.textRows = [];
    $scope.voiceRows = [];
    $scope.recordButton = "Start Recording";

    ons.ready(function() {
        //set default language to English
        language = LanguageSettings;
        language.setSelectedLanguage(language.all_languages[0]);
    });

    $timeout(function(){
        $scope.current_lang = language.selectedLanguage.title;
        $scope.languages = language.all_languages;
    }, 3000);

    $scope.sendText = function(inputText){
        try {
            ApiAIPlugin.requestText(
                {
                    query: inputText
                },
                function (response) {
                    $scope.$apply(function () {
                        var answer = response['result']['fulfillment']['speech'];
                        $scope.textRows.push({
                            question: inputText,
                            answer: answer
                        });
                        $scope.question = "";
                    });
                },
                function (error) {
                    alert(error);
                });
        } catch (e) {
            alert(e);
        }
    }

    $scope.sendVoice = function() {
        console.log("voice");
        try {
            ApiAIPlugin.setListeningStartCallback(function () {
                console.log("listening started");
                $scope.$apply(function () {
                    $scope.recordButton = "Recording now...";
                });
            });
            ApiAIPlugin.requestVoice(
                {}, // empty for simple requests, some optional parameters can be here
                function (response) {                   
                    $scope.$apply(function () {
                        $scope.recordButton = "Start Recording";
                        var question = response['result']['resolvedQuery'];
                        var answer = response['result']['fulfillment']['speech'];
                        $scope.voiceRows.push({
                            question: question,
                            answer: answer
                        });
                    });
                },
                function (error) {
                    ApiAIPlugin.stopListening();
                    console.log("listening stopped");        
                    $scope.$apply(function () {
                        $scope.recordButton = "Start Recording";
                    });
                    alert(error);
                }
            );        
        } catch (e) {
            alert(e);
            ApiAIPlugin.stopListening();
            console.log("listening stopped");
            $scope.$apply(function () {
                $scope.recordButton = "Start Recording";
            });
        }
    }

    $scope.updateLanguage = function(index){
        language.setSelectedLanguage(language.all_languages[index]);
        $scope.current_lang = language.selectedLanguage.title;
        $scope.textRows = [];
        $scope.voiceRows = [];
    }  
});

Conclusion

Now that you understand how to create a conversational app with Monaca using api.ai. Now, you can start testing your app with Monaca Debugger. Then, try to build and install it on your device.

Source:: https://onsen.io/

Build a Mini Netflix with React in 10 Minutes

By Prosper Otemuyiwa

Developers are constantly faced with challenges of building complex products every single day. And there are constraints on the time needed to build out the features of these products.

Engineering and Product managers want to beat deadlines for projects daily. CEOs want to roll out new products as fast as possible. Entrepreneurs need their MVPs like yesterday. With this in mind, what should developers do?

In this tutorial, we’ll quickly build out a Mini Netflix in 10 minutes. In fact, I think we might build it less time.

MVP Challenge

An excited entrepreneur just approached you to build a video service. A service where users can quickly upload short videos and share on twitter for their friends to view. Let’s list out the features of this app.

Features

  • Users should be able to sign up and log in.
  • Registered/Logged-in users should be able to upload short videos of about 20 – 30 seconds.
  • Registered/Non-registered users should be able to view all uploaded videos on the platform on a dashboard.
  • Users should be able to share any of the videos on twitter.

Now, here’s the catch! T’challa of Wakanda wants to invest in some startups today, so the entrepreneur needs to demo the MVP of the video service in 10 minutes from now.

http://cloudinary-res.cloudinary.com/video/upload/v1497373918/T_challay.mp4

I know you are screaming your heart right now. It’s totally okay to cry and let the world know about your problems and challenges, but after much ado shedding tears, will the app be ready in 8 minutes? Well, sorry – tears can’t build an app!

Solution

It’s possible to build the MVP our entrepreneur is asking for. Let me show you how! Ready your editor, your command line and anxious fingers. Let’s get to work!!!

1) Flesh Out The App

We’ll use React to build out the app. Facebook has a tool, create-react-app that can scaffold a progressive web app out of the box in less than a minute. If you don’t have it installed, please install and run the command below in your terminal:

create-react-app miniflix
cd miniflix

Go ahead and open up public/index.html. Pull in bootstrap and add it just after the link to the favicon.

…
 <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
…

2. Set up Authentication & Views

Go ahead and install the following packages from your terminal:

npm install auth0-js react-router@3.0.0 jwt-decode axios

auth0-js – For authentication
react-router – For routing within our app
jwt-decode – For decoding the JSON Web Token in our app
axios – For making network requests.

Open up your src directory and create a components and utils folder. In the utils folder, create a file, AuthService.js and add the code here to it. I explained how to handle the authentication in this tutorial, so check it out to ensure you are on the right track.

We’ll create 4 components in the components folder. Callback.js, Display.js, Nav.js and Upload.js

The Callback component basically stores our authentication credentials and redirects back to the upload route in our app.

The Display component will be dashboard for viewing all videos.

The Nav component will be the navigation that all pages in the app will share.

The Upload component will handle uploading of videos by registered users.

Add this piece of code below to components/Callback.js :

import { Component } from 'react';
import { setIdToken, setAccessToken } from '../utils/AuthService';

class Callback extends Component {

  componentDidMount() {
    setAccessToken();
    setIdToken();
    window.location.href = "/";
  }

  render() {
    return null;
  }
}

export default Callback;

Add this piece of code to components/Nav.js :

import React, { Component } from 'react';
import { Link } from 'react-router';
import { login, logout, isLoggedIn } from '../utils/AuthService';
import '../App.css';

class Nav extends Component {

  render() {
    return (
      <nav className="navbar navbar-default">
        <div className="navbar-header">
          <Link className="navbar-brand" to="/">Miniflix</Link>
        </div>
        <ul className="nav navbar-nav">
          <li>
            <Link to="/">All Videos</Link>
          </li>
          <li>
            {
             ( isLoggedIn() ) ? <Link to="/upload">Upload Videos</Link> :  ''
            }
          </li>
        </ul>
        <ul className="nav navbar-nav navbar-right">
          <li>
           {
             (isLoggedIn()) ? ( <button className="btn btn-danger log" onClick={() => logout()}>Log out </button> ) : ( <button className="btn btn-info log" onClick={() => login()}>Log In</button> )
           }
          </li>
        </ul>
      </nav>
    );
  }
}
export default Nav;

In the Nav component, you must have observed that we imported a css file. Open the App.css file and add this code here to it.

Add this piece of code to components/Display.js:

import React, { Component } from 'react';
import { Link } from 'react-router';
import Nav from './Nav';
import { isLoggedIn } from '../utils/AuthService';
import axios from 'axios';

class Display extends Component {

  render() {

    return (
      <div>
        <Nav />
        <h3 className="text-center"> Latest Videos on Miniflix </h3>
        <hr/>

        <div className="col-sm-12">

        </div>
      </div>
    );
  }
}

export default Display;

Add this piece of code to components/Upload.js:

import React, { Component } from 'react';
import { Link } from 'react-router';
import Nav from './Nav';

class Upload extends Component {

  render() {

    return (
      <div>
        <Nav />
        <h3 className="text-center">Upload Your 20-second Video in a Jiffy</h3>
        <hr/>

        <div className="col-sm-12">
          <div className="jumbotron text-center">
            <button className="btn btn-lg btn-info"> Upload Video</button>
          </div>
        </div>
      </div>
    );
  }
}

export default Upload;

Lastly, open up index.js and add replace it with the code here to set up your routes.

Now, when you run your app with npm start, you should have views like this:

3. Upload Videos

We need a storage space for the videos our users will upload. Cloudinary is a cloud-based service that provides an end-to-end image and video management solution including uploads, storage, administration, manipulation and delivery. Head over to Cloudinary.com and create an account for free.

Let’s make use of Cloudinary’s Upload Widget. This widget allows you to upload videos or any type of file from your local computer, facebook, dropbox and Google Photos. Wow, very powerful. And the integration is seamless.

Go ahead and reference the cloudinary widget script in your index.html:

 <script src="//widget.cloudinary.com/global/all.js" type="text/javascript"></script>

Note: You can add it just after the links.

Now in Upload.js, modify the code to look like this:

import React, { Component } from 'react';
import { Link } from 'react-router';
import Nav from './Nav';

class Upload extends Component {

  uploadWidget = () => {
    window.cloudinary.openUploadWidget(
      { cloud_name: cloud_name',
        upload_preset: 'unsigned-preset',
        tags: ['miniflix'],
        sources: ['local', 'url', 'google_photos', 'facebook', 'image_search']
      },
      function(error, result) {
          console.log("This is the result of the last upload", result);
      });
  }

  render() {
    return (
      <div>
        <Nav />
        <h3 className="text-center">Upload Your 20-second Video in a Jiffy</h3>
        <hr/>

        <div className="col-sm-12">
          <div className="jumbotron text-center">
            <button onClick={this.uploadWidget} className="btn btn-lg btn-info"> Upload Video</button>
          </div>
        </div>
      </div>
    );
  }
}

export default Upload;

In the code above, we added a third argument, tags. Cloudinary provides this for automatic video tagging. Every video that is uploaded to this app will be automatically tagged, miniflix. In addition, you can provide as many tags as you want. This feature is very useful when you want to search for videos too!

In the uploadWidget function, we called the cloudinary.openUploadWidget function and attached it to the “Upload Video” button. When the user clicks the button, it opens the widget. Replace the cloud_name & upload_preset values with your credentials from Cloudinary dashboard.

Sign in to your app, head over to the upload videos route and try uploading a video.


Upload Widget


Uploading the video…

It uploads the video straight to Cloudinary and returns a response object about the recently uploaded video that contains so many parameters such as the unique publicid, secureurl, url, originalfilename, thumbnailurl, createdat, duration and so many others.

4. Display Videos

We need a dashboard to display all the videos uploaded for users to see at a glance. Here, we will make use of Cloudinary’s react component. Install it:

npm install cloudinary-react

Now, open up components/Display.js and modify the code to be this below:

import React, { Component } from 'react';
import { Link } from 'react-router';
import Nav from './Nav';
import { isLoggedIn } from '../utils/AuthService';
import { CloudinaryContext, Transformation, Video } from 'cloudinary-react';
import axios from 'axios';

class Display extends Component {

  state = { videos: [] };

  getVideos() {
    axios.get('http://res.cloudinary.com/unicodeveloper/video/list/miniflix.json')
          .then(res => {
            console.log(res.data.resources);
            this.setState({ videos: res.data.resources});
    });
  }

  componentDidMount() {
    this.getVideos();
  }

  render() {

    const { videos }  = this.state;

    return (
      <div>
        <Nav />
        <h3 className="text-center"> Latest Videos on Miniflix </h3>
        <hr/>

        <div className="col-sm-12">
          <CloudinaryContext cloudName="unicodeveloper">
            { videos.map((data, index) => (
                <div className="col-sm-4" key={index}>
                  <div className="embed-responsive embed-responsive-4by3">
                    <Video publicId={data.public_id} width="300" height="300" controls></Video>
                  </div>
                  <div> Created at {data.created_at} </div>

                </div>
              ))
            }
          </CloudinaryContext>
        </div>
      </div>
    );
  }
}

export default Display;

In the getVideos code above, we take advantage of a very slick Cloudinary trick that helps grab all videos with a particular tag, when using just one tag. Check it out again:


http://res.cloudinary.com/unicodeveloper/video/list/miniflix.json

So we if had a tag like vimeo, our url will end up with …/vimeo.json. So in the code below, we got all the videos and stored in the videos state.

axios.get('http://res.cloudinary.com/unicodeveloper/video/list/miniflix.json')
          .then(res => {
            console.log(res.data.resources);
            this.setState({ videos: res.data.resources});
    });

The Cloudinary React SDK has 4 major components: Image, Video, Transformation and CloudinaryContext. We are interested in the Video and CloudinaryContext for now. Christian explained how these components work here.

In the render method, we simply just looped through the videos state and passed the public_id of each video into the Cloudinary Video component. The Video component does the job of resolving the public_id from Cloudinary, getting the video url, and displaying it using HTML5 video on the webpage. An added advantage is this: Cloudinary automatically determines the best video type for your browser. Furthermore, it allows the user have the best experience possible by choosing the best from the range of available video types and resolutions.

Run your app, and try to see the list of all videos. It should be similar to this:

You can also manipulate your videos on the fly, with the help of Cloudinary via the Transformation component.

5. Share on Twitter

Go ahead install the react twitter widget component:

npm install react-twitter-widgets

In the components/Display.js file, import the component at the top:

import { Share } from 'react-twitter-widgets'
…
…

Now, add this piece of code just after the div that shows the time the video was created.

…
…
<Share url={`http://res.cloudinary.com/unicodeveloper/video/upload/${data.public_id}.mp4`} />

Check your app again. It should be similar to this:

Now, try to tweet.

Simple! It’s really not that hard. The source code for this tutorial is on GitHub.

Conclusion

Our MVP is ready. Our entrepreneur. Now sit back, relax and watch your account become flooded with investor money! Wait a minute, there is a 90% probability that you’ll called to add more features to this app. Well, I think Cloudinary can still help you with more features such as:

  • Automatic Subtitles and translation
  • Video briefs – short video, based on few gif images that will extract from the uploaded video.
  • Automatic and/or manual video markers – marking specific locations in the video so the user can wait patiently to watch them, or jump directly to these points
  • Find Similar videos by automatic video tagging

Cloudinary provides many options for uploading, transforming and optimizing your videos. Feel free to dive in and explore them.

Source:: scotch.io

Getting Started With Vue Router

By Ed Zynda

Vue is already a great Javascript library that allows you to create some really cool, dynamic, front-end applications. Vue is also great for single page applications (SPA). SPAs work a little differently that your standard backend web application built in something like PHP. Instead of making requests to different routes on the backend and getting a fully rendered page as a response, a SPA does all the page rendering on the front-end and only sends requests to the server when new data is needed or needs to be refreshed or saved.

This can improve the responsiveness of your web application because you can render the pages once and display them dynamically based on the current context of the application. In order to make this work, you need a way to distinguish the different views or pages from eachother. In SPAs this is done with a router. Luckily Vue has a fully supported first-party router library called vue-router.

In this tutorial we’ll setup a simple SPA that will show some information about popular cryptocurrencies. We’ll call it “Crypto Info”. It will have a few pages and link those pages using vue-router. You should already be familiar with Vue as well as creating and using Vue components. Having experience with .vue files is helpful but not required.

Setup

To get started, let’s use the handy Vue command line installer. Open a terminal and run the following.

# install vue-cli
$ npm install --global vue-cli
# create a new project using the "webpack" template
$ vue init webpack router-app

When prompted, answer the questions displayed on the screen like so. Make sure to answer “yes” for installing vue-router.

 This will install Vue 2.x version of the template.

 For Vue 1.x use: vue init webpack#1.0 router-app

? Project name router-app <Enter>
? Project description A Vue.js project  <Enter>
? Author  <Enter>
? Vue build standalone  <Enter>
? Install vue-router? Yes
? Use ESLint to lint your code? No
? Setup unit tests with Karma + Mocha? No
? Setup e2e tests with Nightwatch? No

Once the app is setup, install all the dependencies and start up a dev server.

# install dependencies and go!
$ cd router-app
$ npm install
$ npm run dev

You should now be able to point a browser at http://localhost:8080 and see something like this.

Digging In

The great thing about the Vue command line tool is that it will wire up vue-router for us. To get a better understanding of how it works, we can take a look the boilerplate that was created. Open /src/router/index.js

import Vue from 'vue'
import Router from 'vue-router'
import Hello from '@/components/Hello'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'Hello',
      component: Hello
    }
  ]
})

The first two lines are importing vue and vue-router. The third line is importing a component called Hello. We will discuss why in a bit. The @ is just a nice alias for the /src directory that was setup in webpack by the Vue command line tool.

Next we tell Vue to use the vue-router plugin. Finally the router is configured with a single route. The router uses Vue components as pages. In the above example we want to render the Hello component whenever a user navigates to the / route.

Next open /src/main.js

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  template: '<App/>',
  components: { App }
})

The first line is importing Vue again. The second line is bringing in a component called App. This will serve as the root component for the application. The third line is importing the router setup we looked at earlier. The next line tells Vue whether or not to show tips and warnings in the developer console of your browser. In this case it is set to false.

Finally a new Vue instance is created and mounted to the #app div in our html and then it instantiated the App component. We also inject the router configuration from earlier.

Now open /src/App.vue

<template>
  <div id="app">
    <img src="./assets/logo.png">
    <router-view></router-view>
  </div>
</template>

<script>
export default {
  name: 'app'
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

This, like I mentioned before, is the root component. It will serve as the point from which our page components will be rendered. Note that all the components we will use are in .vue files which allows us to save the template, javascript and styling into a single file.

Within the tag we just have some simple markup. The important piece though is the tag. The router uses this tag as a container for rendering the different components tied to the different routes. Just think of it as a placeholder.

The tag just contains a simple Vue component object that does nothing. The tag just contains some nice styling boilerplate provided by the Vue command line tool.

Now open /src/components/Hello.vue

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <h2>Essential Links</h2>
    <ul>
      <li><a href="https://vuejs.org" target="_blank">Core Docs</a></li>
      <li><a href="https://forum.vuejs.org" target="_blank">Forum</a></li>
      <li><a href="https://gitter.im/vuejs/vue" target="_blank">Gitter Chat</a></li>
      <li><a href="https://twitter.com/vuejs" target="_blank">Twitter</a></li>
      <br>
      <li><a href="http://vuejs-templates.github.io/webpack/" target="_blank">Docs for This Template</a></li>
    </ul>
    <h2>Ecosystem</h2>
    <ul>
      <li><a href="http://router.vuejs.org/" target="_blank">vue-router</a></li>
      <li><a href="http://vuex.vuejs.org/" target="_blank">vuex</a></li>
      <li><a href="http://vue-loader.vuejs.org/" target="_blank">vue-loader</a></li>
      <li><a href="https://github.com/vuejs/awesome-vue" target="_blank">awesome-vue</a></li>
    </ul>
  </div>
</template>

<script>
export default {
  name: 'hello',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
  font-weight: normal;
}

ul {
  list-style-type: none;
  padding: 0;
}

li {
  display: inline-block;
  margin: 0 10px;
}

a {
  color: #42b983;
}
</style>

This is very similar to the App component. Again, within the tag there is the HTML markup for the component. In this case it’s all the links and text shown when we pointed our browser to http://localhost:8080. This is because in our router config, we specified that / or the root path of our application should point to Hello.vue.

Now let’s get rid of the default content and create a simpler home page. Edit Hello.vue to look like the following:

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
  </div>
</template>

<script>
  export default {
    name: 'Hello',
    data () {
      return {
        msg: 'Welcome to Crypto Info'
      }
    }
  }
</script>

If you reload, you should now see a page like this.

Creating and Linking to Routes

Now let’s create a new page and add some links for navigating between the two. Open /src/router/index.js and edit it to look like the following.

import Vue from 'vue'
import Router from 'vue-router'
import Hello from '@/components/Hello'
import About from '@/components/About'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'Hello',
      component: Hello
    },
    {
      path: '/about',
      name: 'About',
      component: About
    }
  ]
})

We’ve added a new route /about that points to a new component called About. We’ve also imported the new component at the top. We will create this shortly.

Now open /src/App.vue and edit the section to look like this.

<template>
  <div id="app">
    <img src="./assets/logo.png">
    <router-link :to="{ name: 'Hello' }">Home</router-link>
    <router-link to="/about">About</router-link>
    <router-view></router-view>
  </div>
</template>

As you can see, we added two tags using two different methods. The router uses to create html links to routes you created. The first method uses a named route. If you recall, in /src/router/index.js we added the name parameter to our routes. In this case the name of the route is Hello just like the component it points to. The second method is the standard method and just specifies the path we want to link to.

If you refresh the browser, you should see the original welcome page but with two links added.

If you click the About link, you will get a blank page. This is because we haven’t created the component yet. Let’s fix this be creating /src/components/About.vue.

<template>
  <div class="about">
    <h1>What is a Crypto-Currency?</h1>
    <p>
      It's a digital currency in which encryption techniques are used to regulate the generation of units of currency 
      and verify the transfer of funds, operating independently of a central bank.
    </p>
  </div>
</template>

<script>
export default {
  name: 'About'
}
</script>

Now if you refresh the browser and click About you should see the new page.

Dynamic Routes

So we can create a new page and a route to point to it but what about passing parameters? We’ll need a page that displays some useful info about various crypto currencies based on a string id passed in the URL. Let’s make that happen. Open /src/router/index.js again and add a third route.

...
import Users from '@/components/Coins'

...

export default new Router({
  routes: [
    ...
   {
      path: '/coins/:id',
      name: 'Coins',
      component: Coins
    }
  ]
})

In order to display up-to-date information on the various currencies, we’ll use the popular axios http client to fetch data from the free Coin Market Capitalization API. We’ll accept a string parameter in the URL called :id. This will be passed to the API to retrieve the relevant data.

First we need to install axios.

npm install --save axios

Next create a file called /src/components/Coins.vue

<template>
  <div>
    <p>Name: {{ coin.name }}</p>
    <p>Symbol: {{ coin.symbol }}</p>
    <p>Price (USD): {{ coin.price_usd }}</p>
  </div>
</template>
<script>
  import axios from 'axios'

  export default {
    name: 'Coins',

    data() {
      return {
        coin: {}
      }
    },

    created() {
      this.fetchData()
    },

    watch: {
      '$route': 'fetchData'
    },

    methods: {
      fetchData() {
        axios.get('https://api.coinmarketcap.com/v1/ticker/'+this.$route.params.id+'/')
        .then((resp) => {
          this.coin = resp.data[0]
          console.log(resp)
        })
        .catch((err) => {
          console.log(err)
        })
      }
    }
  }
</script>

You’ll notice that in the data object of our component, we declare an empty object called coin. This will store our coin information after it is fetched. In the section we have some markup to display the name, symbol and US dollar price of the coin. The created method is a special hook used by Vue that is called before the component is rendered. In this case we are calling the fetchData method which is making a GET request with axios to the Coin Market Capitalization API and passing the :id parameter at the end.

We get the parameter from the $route object params property. This object is auto injected by VueRouter. The paramater we want is the :id parameter which we defined in our router file. On success, as defined in the the then promise method, we save the data returned into our coin object. This is then rendered on in the template.

One other thing we need is to add a watch hook for the $route object. VueRouter components are only rendered once for speed. If you need to rerender, you need to do that manually so in this case we want to rerender when the :id parameter in $route changes and then fetch new data.

Now lets create a few more links in /src/App.vue to see how this new page might be used.

<template>
  <div id="app">
    <img src="./assets/logo.png">
    <router-link :to="{ name: 'Hello' }">Home</router-link>
    <router-link to="/about">About</router-link>
    <router-link to="/coins/ethereum">Ethereum</router-link>
    <router-link to="/coins/bitcoin">Bitcoin</router-link>
    <router-view></router-view>
  </div>
</template>

If you refresh the browser and click on Ethereum you should see something like this.

Now click on Bitcoin and you should see relevant information for that coin as well. If you want to try out other coins, have a look at https://api.coinmarketcap.com/v1/ticker/ and paste a few ids from the list into the URL of our app.

Conclusion

That’s how easy it is to get started with Vue Router. There are a bunch of other great features as well and you can read about them in the official documentation. I hope this tutorial is enough to get you started making some cool SPAs in Vue!

Source:: scotch.io