text:
layout: post
title: "Angular 2 Authentication Tutorial"
description: "Angular 2.0 has officially been released. Learn how to quickly build apps and add authentication the right way."
date: 2016-09-29 08:30
category: Technical Guide, Angular, Angular2
banner:
  text: "Auth0 makes it easy to add authentication to your AngularJS application."
author:
  name: "Ado Kukic"
  url: "https://twitter.com/kukicado"
  mail: "ado@auth0.com"
  avatar: "https://s.gravatar.com/avatar/99c4080f412ccf46b9b564db7f482907?s=200"
design:
  image: https://cdn.auth0.com/blog/angular/logo3.png
  bg_color: "#012C6C"
tags:
- angular2
- angular2-jwt
- angular2-authentication
related:
- angular-2-ngmodules
- introducing-angular2-jwt-a-library-for-angular2-authentication
- create-a-desktop-app-with-angular-2-and-electron
---

  Get the "Migrating an Angular 1 App to Angular 2 book" for Free. Spread the word and download it now!

---

**TL;DR** Angular 2.0 has finally been released. In this tutorial we are going to look at how to build applications with Angular 2 as well as how to add token based authentication to Angular 2 apps the right way. Check out the completed code example from our [Github repo](https://github.com/auth0-blog/angular-2-authentication-tutorial).

---

[Angular 2](https://angular.io/) finally hit the major [2.0 release](http://angularjs.blogspot.com/2016/09/angular2-final.html) milestone just a few weeks ago. The final release of Angular 2 did not have many breaking changes. The Release Candidate 5 (RC5) release, made available just a few weeks prior to final, introduced major breaking changes and additions such as the [@NgModule decorator](https://angular.io/docs/ts/latest/guide/ngmodule.html), [Ahead-of-Time (AOT)](http://blog.mgechev.com/2016/08/14/ahead-of-time-compilation-angular-offline-precompilation/) compiler and more.

In today's tutorial, we are going to utilize some of these new features to build an entire Angular 2 application. Components, @NgModule, route guards, services, and more are just some of the topics we'll touch on. Finally, we'll implement token based authentication with [Auth0](https://auth0.com).

## The Angular 2 Ecosystem

[Angular 1.x](https://angularjs.org/) was highly regarded as a robust framework for building single page applications (SPAs). It did a lot of things well, fell short on some, but overall allowed developers to quickly build powerful applications.

While Angular 1.x is a framework, [Angular 2](https://angular.io/) is an entire platform for building modern applications. Alongside the core Angular 2 library, the platform ships with a powerful Command Line Interface (CLI) called [Angular CLI](https://cli.angular.io) that allows developers to easily scaffold their applications as well as control the build system. [Angular Universal](https://universal.angular.io) brings server-side rendering to Angular 2 applications. [Angular Material 2](https://material.angular.io) is the official implementation of [Google Material Design](https://material.google.com/) which allows developers to build beautiful applications with ease.

Angular 2.0 has officially shipped, but the other components of the platform are still in alpha and beta stages. For our application today, we will make use of the Angular CLI and the core Angular 2 framework, but we'll let the other components bake a little longer.

{% include tweet_quote.html quote_text="While Angular 1 is a framework, Angular 2 is an entire platform for building modern applications" %}

## Our App: Daily Deals

![Daily Deals App](https://cdn.auth0.com/blog/angular2-auth-dd/daily-deals.png)

The app we are building today is called Daily Deals. The Daily Deals app displays a list of deals and discounts on various products. We'll have a list of publicly available deals that anyone can see and a list of private deals available only to registered members. The private deals are exclusive to registered members, and should hopefully be better.

### Serving the Daily Deals

We'll have to get our daily deals from somewhere. Let's build a very simple [Node.js](https://nodejs.org) backend to serve the deals. We'll have a publically accessible route serving public deals and a protected route that can only be called by authenticated users. For now, we'll make both of the routes public and worry about the authentication piece later. Take a look at our implementation below:

```js
'use strict';
// Load dependencies
const express = require('express');
const app = express();
const cors = require('cors');
const bodyParser = require('body-parser');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors());

// Public route
app.get('/api/deals/public', (req, res)=>{
  let deals = [
    // Array of public deals here
  ];
  res.json(deals);
})

// Private route
app.get('/api/deals/private', (req,res)=>{
  let deals = [
    // Array of Private Deals here
  ];
  res.json(deals);
})

app.listen(3001);
console.log('Serving deals on localhost:3001');
```

Both our server and the Angular 2 app we are building will require Node.js and [NPM](https://npmjs.com), so be sure to have those installed before continuing. Check out the [Github repo](https://github.com/auth0-blog/angular-2-authentication-tutorial) to get our list of daily deals or create your own. The model for each deal will be as follows:

```js
 {
    id: 1234,
    name: 'Name of Product',
    description: 'Description of Product',
    originalPrice: 19.99, // Original price of product
    salePrice: 9.99 // Sale price of product
}
```

When you are happy with the public and private deals, launch the server by running `node server` and navigate to both `localhost:3001/api/deals/public` and `localhost:3001/api/deals/private` to make sure you can see the list of deals you added. Next, let's set up our Angular 2 front-end.

### Angular 2 Front-End Setup

One of the best ways to start building a new Angular 2 app is with the official Angular 2 CLI. The CLI can take care of scaffolding the initial app, adding additional components, takes care of the build system and much more. In this tutorial we will scaffold our initial app with the CLI.

If you don't already have it installed, run `npm install angular-cli -g` to install the Angular CLI. We'll interact with the CLI using the `ng` command. To create a new application, choose a directory and run `ng init`. This will create a new Angular 2 application in selected directory, download all of the required NPM packages, and basically set everything up for us.

Once `ng init` is finished, run the `ng serve` command and the Webpack based build system will take care of compiling our app from TypeScript to JavaScript and will serve our app on `localhost:4200`. The `ng serve` command will also kick off a live sync process, so any time we make a change our app will automatically recompile.

Let's head over the `localhost:4200` for now to make sure that everything is working as expected so far. If you see a message saying "app works!" you are golden. Next, let's examine how our Angular 2 app is scaffolded.

The `ng init` command scaffolded our Angular 2 app and added a lot of files. Many of these we can ignore for now like the `e2e` folder, which would contain our end to end tests. Open up the `src` directory. In the `src` directory, we can see some familiar files like `index.html`, `styles.css`, and so on. Open up the `app` directory.

The `app` directory contains the bulk of our application. By default we are presented with the following files:

```
- app.component.css - // Holds the CSS styles for our root component
- app.component.html - // Holds the HTML view for our root component
- app.component.spec - // Holds the tests for our root component
- app.component.ts - // Holds the TypeScript logic for our root component
- app.module.ts - // Defines our global app dependencies
- index.ts - // Exports our application
- shared - // This directory holds any shared components we may have
```

Each Angular 2 component we write will have at a minimum the `*.component.ts` file, the others are optional. Our application is going to have three components. The main or root component, a component to display the public deals, and a component to display private deals. For our root component, we'll inline the template, and we won't write any tests so let's make the following edits:

* Delete `app.component.css`, `app.component.html` and `app.component.spec` files. We'll define all we need for our root component in the `app.component.ts` file.
* Create a `public-deals.component.ts`, `public-deals.component.html`, and `public-deals.component.css` file. This component will take care of getting and displaying the public deals data.
* Create a `private-deals.component.ts`, `private-deals.component.html`, and `private-deals.component.css` file. This component will take care of getting and displaying the private deals data.
* Create a `deal.ts` file. This component will hold our `deal` class which will let Angular 2 know the structure of a `deal`.
* Create a `deal.service.ts` file. Here we'll add the functionality to get and retrieve the deal data from our API.
* Finally, create an `app.routing.ts` file which will take care of our routes.

### Building the Root Component

Every Angular 2 application must have a root component. We can name it whatever we want, but the important thing is that we have one. In our application, the `app.component.ts` file will be our root component. Let's take a look at our implementation of this component.

```js
// Import the Component decorator
import { Component } from '@angular/core';

@Component({
  // We'll call our root component daily-deals
  selector: 'daily-deals',
  template: `
  <div class="container">
    <nav class="navbar navbar-default">
        <div class="navbar-header">
          <a class="navbar-brand" routerLink="/dashboard">{{title}}</a>
        </div>
        <!-- On the left side of our navbar we'll display the two links for public and private deals -->
        <ul class="nav navbar-nav">
          <li>
            <a routerLink="/deals" routerLinkActive="active">Deals</a>
          </li>
          <li>
            <a routerLink="/special" routerLinkActive="active">Private Deals</a>
          </li>
        </ul>
        <!-- On the right side of our navbar we'll display the login and logout actions depending on user state -->
        <ul class="nav navbar-nav navbar-right">
          <li>
            <a>Log In</a>
          </li>
          <li>
            <a>Log Out</a>
          </li>
        </ul>
    </nav>
    <div class="col-sm-12">
      <!-- The router-outlet directive will display the component based on the route we are on, more on this soon -->
      <router-outlet></router-outlet>
    </div>
  </div>
  `,
  // We'll add an inline style to properly display the navbar
  styles : ['.navbar-right { margin-right: 0px !important}']
})
export class AppComponent {

  title = 'Daily Deals';

  constructor() {}
}
```

We've created our root component. We added an inline template and some inline styles. We haven't added all the functionality yet, so every user will be able to see all the links and the login and logout buttons. We'll wait to implement those a little bit.

To use this component, open the `index.html` file in your directory and replace `<my-app></my-app>` with `<daily-deals></daily-deals>`. We left the class name `AppComponent` so we don't need to make any edits to our `app.module.ts` file. We can just navigate to `localhost:4200` and see our app displayed. We won't see much yet, just the top navbar.

### The Deal Type

[TypeScript](https://www.typescriptlang.org/) allows us to define the structure or type of our objects. This serves a bunch of useful purposes. For one, if we define the structure of an object, we'll be able to get all of the object's data via intellisense. We can additionally test our components easier by knowing the data structure or type of object we are dealing with.

For our app, we'll create one such type. In the `deal.ts` file, we'll define a type of Deal. Let's see how we'll accomplish this.

```
export class Deal {
  id: number;
  name: string;
  description: string;
  originalPrice: number;
  salePrice: number;
}
```

Now we can declare objects in our Angular 2 application to be a type of `deal`. These objects will gain all of the properties and methods of the deal type. We are only defining properties here, we won't have any methods.

### Public and Private Deals components

The public and private deals components are very similar. In fact, the only difference between the two implementations is that one will display deals from the public API and the other will display deals from the private API. For posterity, we'll just show one of the component implementations. Let's implement the `public-deals.component.ts`.

```js
import { Component, OnInit } from '@angular/core';
import { Deal } from './deal';
// We haven't defined these services yet
import { AuthService } from './auth.service';
import { DealService } from './deal.service';

@Component({
  selector: 'public-deals',
  // We'll use an external file for both the CSS styles and HTML view
  templateUrl: 'public-deals.component.html',
  styleUrls: ['public-deals.component.css']
})
export class PublicDealsComponent implements OnInit {
  publicDeals: Deal[];

  // Note: We haven't implemented the Deal or Auth Services yet.
  constructor(
    private dealService: DealService,
    private authService: AuthService) {
  }
  // When this component is loaded, we'll call the dealService and get our public deals.
  ngOnInit(): void {
    this.dealService.getPublicDeals()
      .then(deals => this.publicDeals = deals);
  }

  purchase(item){
    alert("You bought the: " + item.name);
  }
}
```

Next, let's build the view of our public deals component. We'll do this in the `public-deals.component.html` file. Our view will be a mixture of HTML and Angular 2 sugar. Let's take a look at our implementation.

```html
  <h3 class="text-center">Daily Deals</h3>

  <!-- We are going to get an array of deals stored in the publicDeals variable. We'll loop over that variable here using the ngFor directive -->
  <div class="col-sm-4" *ngFor="let deal of publicDeals">
    <div class="panel panel-default">
      <div class="panel-heading">
        <h3 class="panel-title">{{deal.name}}</h3>
      </div>
      <div class="panel-body">
        {{deal.description}}
      </div>
      <div class="panel-footer">
        <ul class="list-inline">
          <li>Original</li>
          <li class="pull-right">Sale</li>
        </ul>
        <ul class="list-inline">
          <li><a class="btn btn-danger">${{deal.originalPrice | number}}</a></li>
          <li class="pull-right"><a class="btn btn-success">${{deal.salePrice | number}}</a></li>
        </ul>
      </div>
    </div>
  </div>

  <!-- We are going to use the authService.loggedIn() method to see if the user is logged in or not. If they are not logged in we'll encourage them to login, otherwise if they are logged in, we'll provide a handy link to private deals. We haven't implemented the authService yet, so don't worry about the functionality just yet -->
  <div class="col-sm-12" *ngIf="!authService.loggedIn()">
    <div class="jumbotron text-center">
      <h2>Get More Deals By Logging In</h2>
    </div>
  </div>

  <div class="col-sm-12" *ngIf="authService.loggedIn()">
    <div class="jumbotron text-center">
      <h2>View Private Deals</h2>
      <a class="btn btn-lg btn-success" routerLink="/special">Private Deals</a>
    </div>
  </div>
```

Finally, let's add a custom style. In the `public-deals.component.css` file add the following:

```css
.panel-body {
	min-height: 100px;
}
```

This will ensure that each of the products displays nicely on our page.

Our private deals component will look very similar. For posterity, we won't display the scaffold. We'll cover the changes a little later on. If you'd like to see what it looks like, you can view it from our [Github repo](https://github.com/auth0-blog/angular-2-authentication-tutorial).

### Accessing our Deals API

Earlier in the tutorial we wrote a very simple API that exposed two routes. Now, let's write an Angular 2 service that will interact with these two endpoints. We'll do this in the `deal.service.ts` file. The implementation is as follows:

```
import { Injectable } from '@angular/core';
import { Headers, Http, Response } from '@angular/http';

import 'rxjs/add/operator/toPromise';

import { Deal } from './deal';

@Injectable()
export class DealService {
  // Define the routes we are going to interact with
  private publicDealsUrl = 'http://localhost:3001/api/deals/public';
  private privateDealsUrl = 'http://localhost:3001/api/deals/private';

  constructor(private http: Http) { }

  // Implement a method to get the public deals
  getPublicDeals() {
    return this.http
      .get(this.publicDealsUrl)
      .toPromise()
      .then(response=>response.json() as Deal[])
      .catch(this.handleError);
  }

  // Implement a method to get the private deals
  getPrivateDeals() {
    return this.http
      .get(this.privateDealsUrl)
      .toPromise()
      .then(response=>response.json() as Deal[])
      .catch(this.handleError);
  }

  // Implement a method to handle errors if any
  private handleError(error: any): Promise<any> {
    console.error('An error occurred', error);
    return Promise.reject(error.message || error);
  }
}
```

Now you can see where the getPublicDeals() method fits in from our `public-deals.component.ts` file. We also have written a `getPrivateDeals()` method that will get our list of private deals. Implement this method in your `private-deals.component.ts` file.

### Implementing the Routes

Now that we have our two components created, let's implement routing so that we can display the appropriate component. Routing in Angular 2 has changed a couple of different times. The new new new router is really great though and supports many features developers have been asking for such as lazy loading.

For our application, we will create two routes. The `/deals` route will display the publically available deals, and the `/special` route will display the exclusive private deals that only registered users will have access to. We'll also add a redirect, so that when the user lands on the homepage, we'll automatically redirect them to the deals page. Let's see how we are going to implement this.

```js
import { Routes, RouterModule} from '@angular/router';

// Import our components
import { PublicDealsComponent } from './public-deals.component';
import { PrivateDealsComponent } from './private-deals.component';

const appRoutes: Routes = [
  // Add the redirect
  {
    path: '',
    redirectTo: '/deals',
    pathMatch: 'full'
  },
  // Add our routes
  {
    path: 'deals',
    component: PublicDealsComponent
  },
  {
    path: 'special',
    component: PrivateDealsComponent
  }
];
// Here we are exporting our routes
export const routing = RouterModule.forRoot(appRoutes);
// Here we are combining our routing components into a single array. We will use this a little later when we update our root module
export const routedComponents = [PublicDealsComponent, PrivateDealsComponent];
```

Our routing is looking good. Our entire application should be ready to test now. Before we test our application, there is one final thing we need to do to ensure that everything works correctly. *Note: If you decide to test your application before the conclusion of the tutorial, you will need to remove the `AuthService` from your deals components, otherwise Angular will complain.*

We need to update our root @NgModule to include all of the new components and services we've written. To do this, open the `app.module.ts` file. In this file, you'll see the root module that the Angular bootstrap created for us. We are going to edit it as follows:

```js
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

// Import our dependencies
import { AppComponent } from './app.component';
import { routing, routedComponents } from './app.routing';

import { DealService } from './deal.service';

@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    // Include the routing module
    routing,
    HttpModule,
  ],
  declarations: [
    AppComponent,
    // Include our array of routing components. This saves us from having to type out the entire list of components twice
    routedComponents
  ],
  providers: [
    // Add our deal service we created earlier
    DealService
  ],
  // Declare our root component, which is the AppComponent
  bootstrap: [AppComponent]
})
export class AppModule { }
```

Now we are ready to test our app. If you would like more information on how @NgModule works, check out this post. Navigate to `localhost:4200` and you should see be redirected to the deals page automatically. Notice that you can freely navigate to the `/secret` route and see the exclusive deals as well. You can do this because we haven't added user authentication yet. Let's do that now.

## Adding Authentication to Your Angular 2 App

The majority of apps require some type of authentication. Our application today is no different. In the next section I am going to show you how to add authentication to your Angular 2 application the right way. We are going to be using [Auth0](https://auth0.com) as our identity platform. We'll use Auth0 as it allows us to easily issue [JSON Web Tokens (JWTs)](https://jwt.io), but the concepts we'll cover can be applied to any token based authentication system. If you don't already have an Auth0 account, [sign up](javascript:signup\(\)) for a free one now.

Login to your Auth0 [management dashboard](https://manage.auth0.com) and let's create a new API client. If you don't already have the APIs menu item, you can enable it by going to your [Account Settings](https://manage.auth0.com/#/account/advanced) and in the **Advanced** tab, scroll down until you see **Enable APIs Section** and flip the switch.

From here, click on the APIs menu item and then the **Create API** button. You will need to give your API a name and an identifier. The name can be anything you choose, so make it as descriptive as you want. The identifier will be used to identify your API, this field cannot be changed once set. For our example, I'll name the API **Daily Deals API** and for the identifier I'll set it as **daily-deals-api**. We'll leave the signing algorithm as RS256 and click on the **Create API** button.

![Creating Auth0 API](https://cdn.auth0.com/blog/angular2-auth-dd/creating-api.png)

Next, let's define some scopes for our API. Scopes allow us to manage access to our API. We can define as few or as many scopes as we want. For our simple example, we'll just create a single scope that will grant users full access to the API.

![Adding Scope to API](https://cdn.auth0.com/blog/angular2-auth-dd/adding-scope.png)

This is all we need to do for now. Let's secure our server using this new API that we created.

### Securing our server

Before we implement authentication on the front end in our Angular 2 application, let's secure our backend server. Open up the `server.js` file located in your `server` directory and make the following edits:

```js
'use strict';

const express = require('express');
const app = express();
// Import the required dependencies
const jwt = require('express-jwt');
const jwks = require('jwks-rsa');
const cors = require('cors');
const bodyParser = require('body-parser');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors());

// We are going to implement a JWT middleware that will ensure the validity of our token. We'll require each protected route to have a valid access_token sent in the Authorization header
const authCheck = jwt({
  secret: jwks.expressJwtSecret({
        cache: true,
        rateLimit: true,
        jwksRequestsPerMinute: 5,
        jwksUri: "https://{YOUR-AUTH0-DOMAIN}.auth0.com/.well-known/jwks.json"
    }),
    // This is the identifier we set when we created the API
    audience: '{YOUR-API-AUDIENCE-ATTRIBUTE}',
    issuer: "https://{YOUR-AUTH0-DOMAIN}.auth0.com/",
    algorithms: ['RS256']
});

app.get('/api/deals/public', (req, res)=>{
  let deals = [
    // Array of public deals
  ];
  res.json(deals);
})

// For the private route, we'll add this authCheck middleware
app.get('/api/deals/private', authCheck, (req,res)=>{
  let deals = [
    // Array of private deals
  ];
  res.json(deals);
})

app.listen(3001);
console.log('Listening on localhost:3001');
```

That's all we'll need to do on the server. Restart the server and try to navigate to `localhost:3001/api/deals/private` and you'll see an error message saying missing authorization header. Our private API route is now secured. Let's get to implementing authentication in our Angular 2 app.

![API with No Auth Token](https://cdn.auth0.com/blog/angular2-auth-dd/no-auth-token.png)

### Adding Authentication to the Front-end

We'll make use of the [Angular 2 JWT library](https://github.com/auth0/angular2-jwt) to provide us the foundation for implementing authentication in our app. You can get the library for your app by running `npm install angular2-jwt --save`.

 We'll first start by creating an authentication service that we can use throughout our app. Create a new file titled `auth.service.ts`. Out auth service implementation follows:

```js
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { AUTH_CONFIG } from './auth0-variables';
import { tokenNotExpired } from 'angular2-jwt';

// Avoid name not found warnings
declare var auth0: any;

@Injectable()
export class AuthService {
  // Create Auth0 web auth instance
  // @TODO: Update AUTH_CONFIG and remove .example extension in src/app/auth/auth0-variables.ts.example
  auth0 = new auth0.WebAuth({
    clientID: AUTH_CONFIG.CLIENT_ID,
    domain: AUTH_CONFIG.CLIENT_DOMAIN
  });

  // Create a stream of logged in status to communicate throughout app
  loggedIn: boolean;
  loggedIn$ = new BehaviorSubject<boolean>(this.loggedIn);

  constructor(private router: Router) {
    // If authenticated, set local profile property and update login status subject
    if (this.authenticated) {
      this.setLoggedIn(true);
    }
  }

  setLoggedIn(value: boolean) {
    // Update login status subject
    this.loggedIn$.next(value);
    this.loggedIn = value;
  }

  login() {
    // Auth0 authorize request
    // Note: nonce is automatically generated: https://auth0.com/docs/libraries/auth0js/v8#using-nonce
    this.auth0.authorize({
      responseType: 'token id_token',
      redirectUri: AUTH_CONFIG.REDIRECT,
      audience: AUTH_CONFIG.AUDIENCE,
      scope: AUTH_CONFIG.SCOPE
    });
  }

  handleAuth() {
    // When Auth0 hash parsed, get profile
    this.auth0.parseHash((err, authResult) => {
      if (authResult && authResult.accessToken && authResult.idToken) {
        window.location.hash = '';
        this._getProfile(authResult);
        this.router.navigate(['/']);
      } else if (err) {
        this.router.navigate(['/']);
        console.error(`Error: ${err.error}`);
      }
    });
  }

  private _getProfile(authResult) {
    // Use access token to retrieve user's profile and set session
    this.auth0.client.userInfo(authResult.accessToken, (err, profile) => {
      this._setSession(authResult, profile);
    });
  }

  private _setSession(authResult, profile) {
    // Save session data and update login status subject
    localStorage.setItem('token', authResult.accessToken);
    localStorage.setItem('id_token', authResult.idToken);
    localStorage.setItem('profile', JSON.stringify(profile));
    this.setLoggedIn(true);
  }

  logout() {
    // Remove tokens and profile and update login status subject
    localStorage.removeItem('token');
    localStorage.removeItem('id_token');
    localStorage.removeItem('profile');
    this.router.navigate(['/']);
    this.setLoggedIn(false);
  }

  get authenticated() {
    // Check if there's an unexpired access token
    return tokenNotExpired('token');
  }

}
```

We will use the Auth0 Hosted Lock option for authenticating our users. This is the most secure way to authenticate a user and get an `access_token` in an OAuth compliant manner. With our authentication service created, let's continue building our authentication workflow.

### Angular 2 Authentication All In

The Angular 2 router comes with a powerful feature called [route guards](https://angular.io/docs/ts/latest/guide/router.html#!#guards) that allows us to programmatically determine whether a user can access the route or not. Route guards in Angular 2 can be compared to middleware in Express.js for example.

We'll create an authentication route guard that will check to see if a user is logged in before displaying the route. Create a new file titled `auth-guard.service.ts` and add the following code:

```js
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { CanActivate } from '@angular/router';
// Import our authentication service
import { AuthService } from './auth.service';

@Injectable()
export class AuthGuard implements CanActivate {

  constructor(private auth: AuthService, private router: Router) {}

  canActivate() {
    // If the user is not logged in we'll send them back to the home page
    if (!this.auth.authenticated) {
      this.router.navigate(['']);
      return false;
    }
    return true;
  }

}
```

To implement this route guard in our routes, let's go ahead and open our `app.routing.ts` file. Here, we'll include our auth guard service and enable it on our secret route. Let's take a look at the implementation.

```js
// Here we're also including the CanActivate API
import { Routes, RouterModule, CanActivate } from '@angular/router';
// Add the AuthGuard service
import { AuthGuard } from './auth-guard.service';

import { PublicDealsComponent } from './public-deals.component';
import { PrivateDealsComponent } from './private-deals.component';

const appRoutes: Routes = [
  {
    path: '',
    redirectTo: '/deals',
    pathMatch: 'full'
  },
  {
    path: 'deals',
    component: PublicDealsComponent
  },
  {
    path: 'special',
    component: PrivateDealsComponent,
    // We'll use the canActivate API and pass in our AuthGuard. Now any time the /special route is hit, the AuthGuard will run first to make sure the user is logged in before activating and loading this route.
    canActivate: [AuthGuard]
  }
];

export const routing = RouterModule.forRoot(appRoutes);

export const routedComponents = [PublicDealsComponent, PrivateDealsComponent];
```

That's all there is to it. Our route is now protected at the routing level.

If you recall we included a stub for the AuthService in our deal components. Since the authentication service is now implemented our placeholder functionality will just work. We'll see the correct behavior displayed based on user state.

We will need to update our root component though as we didn't include authentication specific functionality there. I did this on purpose so we could go through the example line by line. Let's do that next.

```js
import { Component } from '@angular/core';
// First and foremost we'll include our authentication service
import { AuthService } from './auth.service';

@Component({
  selector: 'daily-deals',
  template: `
  <div class="container">
    <nav class="navbar navbar-default">
        <div class="navbar-header">
          <a class="navbar-brand" routerLink="/dashboard">{{title}}</a>
        </div>
        <ul class="nav navbar-nav">
          <li>
            <a routerLink="/deals" routerLinkActive="active">Deals</a>
          </li>
          <li>
            <a routerLink="/special" *ngIf="authService.authenticated" routerLinkActive="active">Private Deals</a>
          </li>
        </ul>
        <ul class="nav navbar-nav navbar-right">
          <li>
            <a *ngIf="!authService.authenticated" (click)="authService.login()">Log In</a>
          </li>
          <li>
            <a (click)=authService.logout() *ngIf="authService.authenticated">Log Out</a>
          </li>
        </ul>
    </nav>
    <div class="col-sm-12">
      <router-outlet></router-outlet>
    </div>
  </div>
  `,
  styles : ['.navbar-right { margin-right: 0px !important}']
})
export class AppComponent {
  title = 'Daily Deals';

  // We'll need to include a reference to our authService in the constructor to gain access to the API's in the view
  constructor(private authService: AuthService) {
  }
}
```

When the user clicks on the login link, they will be taken to a hosted Lock login page on the Auth0 domain. They will enter their credentials here and if correct, they will be redirected back to the application.

Before we test out this functionality, we'll need to ensure that we have the right credentials so that our authentication service knows which parameters to pass to the hosted Lock page. Create a new file called `auth0-variables.ts` and paste the following:

```js
interface AuthConfig {
  CLIENT_ID: string;
  CLIENT_DOMAIN: string;
  AUDIENCE: string;
  REDIRECT: string;
  SCOPE: string;
}

export const AUTH_CONFIG: AuthConfig = {
  CLIENT_ID: 'YOUR-AUTH0-CLIENT-ID',
  CLIENT_DOMAIN: 'YOUR-AUTH0-DOMAIN.auth0.com',
  AUDIENCE: 'YOUR-AUTH0-API-IDENTIFIER',
  REDIRECT: 'http://localhost:4200/callback',
  SCOPE: 'openid'
};

```

We are already importing this file in the `auth.service.ts` file, so once it is created we will not have to do anything else except change the `YOUR-AUTH0-CLIENT-ID`, `YOUR-AUTH0-DOMAIN`, and `YOUR-AUTH0-API-IDENTIFIER` for your actual values. The `YOUR-AUTH-CLIENT-ID` will be an Auth0 client that will hold your users. When you created your API, Auth0 also created a test client which you can use. Additionally, you can use any existing Auth0 client found in Clients section of your [management dashboard](https://manage.auth0.com/#/clients).

The client that was created for me is called **Daily Deals API (Test Client)**, and I will use this client for our application as it is already setup to work with the API. Open up your client, and you will want to copy the **Client ID**. This value will replace the `YOUR-AUTH0-CLIENT-ID` parameter. Likewise, do the same for the other two placeholders.

![Daily Deals API Test Client](https://cdn.auth0.com/blog/angular2-auth-dd/dd-client.png)

While you're viewing your client in the Auth0 dashboard, scroll down to find a section titled **Allowed Callback URLs**. Here you will add the URL that Auth0 will redirect to after successfully authenticating or creating a user. Since we are using the Angular CLI, and it defaults to `localhost:4200`, in our **Allowed Callback URLs** section we will add:

```
http://localhost:4200/callback
```

### Creating the Callback Component

We will create a new component and call it `CallbackComponent`. This component will be activated when the `localhost:4200/callback` route is called and it will process the redirect from Auth0 and ensure we recieved the right data back after a successful authentication. The component will make extensive use of the `AuthService` we created earlier. Let's take a look at the implementation:

```js
import { Component } from '@angular/core';
import { AuthService } from './auth.service';

@Component({
  template: ``
})
export class CallbackComponent {

  constructor(private authService: AuthService) {
    this.authService.handleAuth();
  }
}
```

Once a user is authenticated, Auth0 will redirect back to our application and call the `/callback` route. Auth0 will also append the `id_token` as well as the `access_token` to this request, and our CallbackComponent will make sure to properly process and store those tokens in localStorage. If all is well, meaning we recieved an `id_token` and an `access_token`, we will be redirected back to the `/deals` page and will be in a logged in state.

Before we move on, let's make sure to register the `/callback` route in our routes file.

```js
import { Routes, RouterModule, CanActivate } from '@angular/router';
import { AuthGuard } from './auth-guard.service';

import { PublicDealsComponent } from './public-deals.component';
import { PrivateDealsComponent } from './private-deals.component';
import { CallbackComponent } from './callback.component';

const appRoutes: Routes = [
  {
    path: '',
    redirectTo: '/deals',
    pathMatch: 'full'
  },
  {
    path: 'deals',
    component: PublicDealsComponent
  },
  {
    path: 'special',
    component: PrivateDealsComponent,
    canActivate: [AuthGuard]
  },
  {
    path: 'callback',
    component: CallbackComponent,
  }
];

export const routing = RouterModule.forRoot(appRoutes);

export const routedComponents = [PublicDealsComponent, PrivateDealsComponent, CallbackComponent];
```

There is one final update we need to make. If you try to access the `/secret` route now, even if you are logged in, you won't get the list of secret deals. This is because we are not passing the `access_token` to the backend. We'll have to update our deal service.

### Updating the Deal Service

We need to update the call to the `/api/deals/private` to include our `access_token`. There are a couple of different ways to accomplish this. We could use the existing `http` call and add the correct header, but there is an easier way. The Angular 2 JWT library comes with an AuthHTTP method that will take care of this for us. Let's see how we're going to implement this in our application.

```js
  // Be sure to include the HttpAuth API from the Angular 2 JWT library
  import { AuthHttp } from 'angular2-jwt';

  ...

  // We'll need to include the AuthHTTP method in our constructor
  constructor(private http: Http, private authHttp: AuthHttp) { }

  ...
  getPrivateDeals() {
    // Instead of this.http, we'll use the this.authHttp method. Everything else remains the same.
    return this.authHttp
      .get(this.privateDealsUrl)
      .toPromise()
      .then(response=>response.json() as Deal[])
      .catch(this.handleError);
  }
```

Now when a call is made to our API withe the `authHttp` service, we will automatically append the `access_token` to the call in an `Authorization` header and in the correct format. Let's try it out in the next section to make sure that it works.

### Putting it all together

![Auth0 Hosted Lock](https://cdn.auth0.com/blog/angular2-auth-dd/hosted-lock.png)

That's it. We are now ready to test our application. If your Node.js server is not running, make sure to start it up first. Head over to `localhost:4200` and you should automatically be redirected to `localhost:4200/deals` and see the list of public deals.

![Daily Deals Authenticated](https://cdn.auth0.com/blog/angular2-auth-dd/authenticated.png)

Next, click on the login screen and you will be redirected to your Auth0 domain and the hosted Lock login widget will be displayed. Login or sign up and you will be redirected back to the callback route, and then the deals page, but now the UI will look slightly different. The main menu will have a new option for Private Deals, and the message at the bottom will also show you a link to the private deals. Instead of the Login link in the navbar, you'll also be presented with a Logout link instead. Finally click on the Private Deals link to see our list of exclusive private deals.

![Consent Dialog](https://cdn.auth0.com/blog/angular2-auth-dd/consent.png)

**Note:** Since we are using `localhost` for our domain, once a user logs in the first time, or if the scope changes in the future, a consent dialog will be displayed asking the user if they wish to grant access to the API. This consent dialog will not be displayed if you are using a non-localhost domain, and the client is a first-party client.

![Exclusive Daily Deals](https://cdn.auth0.com/blog/angular2-auth-dd/secret-deals.png)

You just wrote and authenticated an Angular 2.0 app. Congrats!

## Conclusion

Angular 2 is finally out and ready for prime time. It's been a long time coming, but it's finally here and I couldn't be more excited. In this tutorial, we looked at some of the ways you can write Angular 2 components and services. We implemented token based authentication with Auth0 and Lock. But that's just scratching the surface.

Angular 2 provides a lot of great features out of the box like pipes, i18n, and much more. Auth0 can help secure your Angular 2 apps with not just state of the art authentication, but enhanced features like [multifactor auth](https://auth0.com/docs/multifactor-authentication), [anomaly detection](https://auth0.com/docs/anomaly-detection), [enterprise federation](https://auth0.com/docs/identityproviders), [single sign on (SSO)](https://auth0.com/docs/sso), and more. [Sign up](javascript:signup\(\)) today so you can focus on building features unique to your app.


text:
<?php

namespace Google\ApiCore\Tests\Unit;

use Google\ApiCore\CredentialsWrapper;
use Google\Auth\ApplicationDefaultCredentials;
use Google\Auth\Cache\MemoryCacheItemPool;
use Google\Auth\Cache\SysVCacheItemPool;
use Google\Auth\CredentialsLoader;
use Google\Auth\FetchAuthTokenCache;
use Google\Auth\FetchAuthTokenInterface;
use Google\Auth\HttpHandler\HttpHandlerFactory;
use Google\Auth\UpdateMetadataInterface;
use PHPUnit\Framework\TestCase;
use Prophecy\Argument;

class CredentialsWrapperTest extends TestCase
{

    /**
     * @dataProvider buildDataWithoutExplicitKeyFile
     */
    public function testBuildWithoutExplicitKeyFile($args, $expectedCredentialsWrapper)
    {
        $appDefaultCreds = getenv('GOOGLE_APPLICATION_CREDENTIALS');
        putenv('GOOGLE_APPLICATION_CREDENTIALS=' . __DIR__ . '/testdata/json-key-file.json');

        $actualCredentialsWrapper = CredentialsWrapper::build($args);
        $this->assertEquals($expectedCredentialsWrapper, $actualCredentialsWrapper);

        putenv('GOOGLE_APPLICATION_CREDENTIALS=' . $appDefaultCreds);
    }

    /**
     * @dataProvider buildDataWithKeyFile
     */
    public function testBuildWithKeyFile($args, $expectedCredentialsWrapper)
    {
        $actualCredentialsWrapper = CredentialsWrapper::build($args);
        $this->assertEquals($expectedCredentialsWrapper, $actualCredentialsWrapper);
    }

    public function buildDataWithoutExplicitKeyFile()
    {
        $appDefaultCreds = getenv('GOOGLE_APPLICATION_CREDENTIALS');
        putenv('GOOGLE_APPLICATION_CREDENTIALS=' . __DIR__ . '/testdata/json-key-file.json');
        $scopes = ['myscope'];
        $defaultAuthHttpHandler = HttpHandlerFactory::build();
        $authHttpHandler = HttpHandlerFactory::build();
        $asyncAuthHttpHandler = function ($request, $options) use ($authHttpHandler) {
            return $authHttpHandler->async($request, $options)->wait();
        };
        $defaultAuthCache = new MemoryCacheItemPool();
        $authCache = new SysVCacheItemPool();
        $authCacheOptions = ['lifetime' => 600];
        $quotaProject = 'my-quota-project';

        $testData = [
            [
                [],
                new CredentialsWrapper(ApplicationDefaultCredentials::getCredentials(null, $defaultAuthHttpHandler, null, $defaultAuthCache), $defaultAuthHttpHandler),
            ],
            [
                ['scopes' => $scopes],
                new CredentialsWrapper(ApplicationDefaultCredentials::getCredentials($scopes, $defaultAuthHttpHandler, null, $defaultAuthCache), $defaultAuthHttpHandler),
            ],
            [
                ['scopes' => $scopes, 'authHttpHandler' => $asyncAuthHttpHandler],
                new CredentialsWrapper(ApplicationDefaultCredentials::getCredentials($scopes, $asyncAuthHttpHandler, null, $defaultAuthCache), $asyncAuthHttpHandler),
            ],
            [
                ['enableCaching' => false],
                new CredentialsWrapper(ApplicationDefaultCredentials::getCredentials(null, $defaultAuthHttpHandler, null, null), $defaultAuthHttpHandler),
            ],
            [
                ['authCacheOptions' => $authCacheOptions],
                new CredentialsWrapper(ApplicationDefaultCredentials::getCredentials(null, $defaultAuthHttpHandler, $authCacheOptions, $defaultAuthCache), $defaultAuthHttpHandler),
            ],
            [
                ['authCache' => $authCache],
                new CredentialsWrapper(ApplicationDefaultCredentials::getCredentials(null, $defaultAuthHttpHandler, null, $authCache), $defaultAuthHttpHandler),
            ],
            [
                ['quotaProject' => $quotaProject],
                new CredentialsWrapper(ApplicationDefaultCredentials::getCredentials(null, $defaultAuthHttpHandler, null, $defaultAuthCache, $quotaProject), $defaultAuthHttpHandler),
            ],
        ];

        putenv('GOOGLE_APPLICATION_CREDENTIALS=' . $appDefaultCreds);

        return $testData;
    }

    public function buildDataWithKeyFile()
    {
        $keyFilePath = __DIR__ . '/testdata/json-key-file.json';
        $keyFile = json_decode(file_get_contents($keyFilePath), true);

        $scopes = ['myscope'];
        $authHttpHandler = function () {};
        $defaultAuthCache = new MemoryCacheItemPool();
        $authCache = new SysVCacheItemPool();
        $authCacheOptions = ['lifetime' => 600];
        $quotaProject = 'my-quota-project';
        return [
            [
                ['keyFile' => $keyFile],
                $this->makeExpectedKeyFileCreds($keyFile, null, $defaultAuthCache, null, null),
            ],
            [
                ['keyFile' => $keyFilePath],
                $this->makeExpectedKeyFileCreds($keyFile, null, $defaultAuthCache, null, null),
            ],
            [
                ['keyFile' => $keyFile, 'scopes' => $scopes],
                $this->makeExpectedKeyFileCreds($keyFile, $scopes, $defaultAuthCache, null, null),
            ],
            [
                ['keyFile' => $keyFile, 'scopes' => $scopes, 'authHttpHandler' => $authHttpHandler],
                $this->makeExpectedKeyFileCreds($keyFile, $scopes, $defaultAuthCache, null, $authHttpHandler),
            ],
            [
                ['keyFile' => $keyFile, 'enableCaching' => false],
                $this->makeExpectedKeyFileCreds($keyFile, null, null, null, null),
            ],
            [
                ['keyFile' => $keyFile, 'authCacheOptions' => $authCacheOptions],
                $this->makeExpectedKeyFileCreds($keyFile, null, $defaultAuthCache, $authCacheOptions, null),
            ],
            [
                ['keyFile' => $keyFile, 'authCache' => $authCache],
                $this->makeExpectedKeyFileCreds($keyFile, null, $authCache, null, null),
            ],
            [
                ['keyFile' => $keyFile, 'quotaProject' => $quotaProject],
                $this->makeExpectedKeyFileCreds(
                    $keyFile + ['quota_project_id' => $quotaProject],
                    null,
                    $defaultAuthCache,
                    null,
                    null
                ),
            ],
        ];
    }

    private function makeExpectedKeyFileCreds($keyFile, $scopes, $cache, $cacheConfig, $httpHandler)
    {
        $loader = CredentialsLoader::makeCredentials($scopes, $keyFile);
        if ($cache) {
            $loader = new FetchAuthTokenCache($loader, $cacheConfig, $cache);
        }
        return new CredentialsWrapper($loader, $httpHandler);
    }

    /**
     * @dataProvider getBearerStringData
     */
    public function testGetBearerString($fetcher, $expectedBearerString)
    {
        $credentialsWrapper = new CredentialsWrapper($fetcher);
        $bearerString = $credentialsWrapper->getBearerString();
        $this->assertSame($expectedBearerString, $bearerString);
    }

    public function getBearerStringData()
    {
        $expiredFetcher = $this->prophesize(FetchAuthTokenInterface::class);
        $expiredFetcher->getLastReceivedToken()
            ->willReturn([
                'access_token' => 123,
                'expires_at' => time() - 1
            ]);
        $expiredFetcher->fetchAuthToken(Argument::any())
            ->willReturn([
                'access_token' => 456,
                'expires_at' => time() + 1000
            ]);
        $eagerExpiredFetcher = $this->prophesize(FetchAuthTokenInterface::class);
        $eagerExpiredFetcher->getLastReceivedToken()
            ->willReturn([
                'access_token' => 123,
                'expires_at' => time() + 1
            ]);
        $eagerExpiredFetcher->fetchAuthToken(Argument::any())
            ->willReturn([
                'access_token' => 456,
                'expires_at' => time() + 10 // within 10 second eager threshold
            ]);
        $unexpiredFetcher = $this->prophesize(FetchAuthTokenInterface::class);
        $unexpiredFetcher->getLastReceivedToken()
            ->willReturn([
                'access_token' => 123,
                'expires_at' => time() + 100,
            ]);
        $insecureFetcher = $this->prophesize(FetchAuthTokenInterface::class);
        $insecureFetcher->getLastReceivedToken()->willReturn(null);
        $insecureFetcher->fetchAuthToken(Argument::any())
            ->willReturn([
                'access_token' => '',
            ]);
        $nullFetcher = $this->prophesize(FetchAuthTokenInterface::class);
        $nullFetcher->getLastReceivedToken()->willReturn(null);
        $nullFetcher->fetchAuthToken(Argument::any())
            ->willReturn([
                'access_token' => null,
            ]);
        return [
            [$expiredFetcher->reveal(), 'Bearer 456'],
            [$eagerExpiredFetcher->reveal(), 'Bearer 456'],
            [$unexpiredFetcher->reveal(), 'Bearer 123'],
            [$insecureFetcher->reveal(), ''],
            [$nullFetcher->reveal(), '']
        ];
    }

    /**
     * @dataProvider getAuthorizationHeaderCallbackData
     */
    public function testGetAuthorizationHeaderCallback($fetcher, $expectedCallbackResponse)
    {
        $credentialsWrapper = new CredentialsWrapper($fetcher);
        $callback = $credentialsWrapper->getAuthorizationHeaderCallback('audience');
        $actualResponse = $callback();
        $this->assertSame($expectedCallbackResponse, $actualResponse);
    }

    public function getAuthorizationHeaderCallbackData()
    {
        $expiredFetcher = $this->prophesize();
        $expiredFetcher->willImplement(FetchAuthTokenInterface::class);
        $expiredFetcher->willImplement(UpdateMetadataInterface::class);
        $expiredFetcher->getLastReceivedToken()
            ->willReturn([
                'access_token' => 123,
                'expires_at' => time() - 1
            ]);
        $expiredFetcher->updateMetadata(Argument::any(), 'audience')
            ->willReturn(['authorization' => ['Bearer 456']]);
        $expiredInvalidFetcher = $this->prophesize(FetchAuthTokenInterface::class);
        $expiredInvalidFetcher->getLastReceivedToken()
            ->willReturn([
                'access_token' => 123,
                'expires_at' => time() - 1
            ]);
        $expiredInvalidFetcher->fetchAuthToken(Argument::any())
            ->willReturn(['not-a' => 'valid-token']);
        $unexpiredFetcher = $this->prophesize();
        $unexpiredFetcher->willImplement(FetchAuthTokenInterface::class);
        $unexpiredFetcher->getLastReceivedToken()
            ->willReturn([
                'access_token' => 123,
                'expires_at' => time() + 100,
            ]);

        $insecureFetcher = $this->prophesize(FetchAuthTokenInterface::class);
        $insecureFetcher->getLastReceivedToken()->willReturn(null);
        $insecureFetcher->fetchAuthToken(Argument::any())
            ->willReturn([
                'access_token' => '',
            ]);
        $nullFetcher = $this->prophesize(FetchAuthTokenInterface::class);
        $nullFetcher->getLastReceivedToken()->willReturn(null);
        $nullFetcher->fetchAuthToken(Argument::any())
            ->willReturn([
                'access_token' => null,
            ]);

        $customFetcher = $this->prophesize();
        $customFetcher->willImplement(FetchAuthTokenInterface::class);
        $customFetcher->getLastReceivedToken()->willReturn(null);
        $customFetcher->fetchAuthToken(Argument::any())
            ->willReturn([
                'access_token' => 123,
                'expires_at' => time() + 100,
            ]);

        return [
            [$expiredFetcher->reveal(), ['authorization' => ['Bearer 456']]],
            [$expiredInvalidFetcher->reveal(), []],
            [$unexpiredFetcher->reveal(), ['authorization' => ['Bearer 123']]],
            [$insecureFetcher->reveal(), []],
            [$nullFetcher->reveal(), []],
            [$customFetcher->reveal(), ['authorization' => ['Bearer 123']]],
        ];
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.eagle.example.notificationplugin;

import backtype.storm.spout.SpoutOutputCollector;
import backtype.storm.task.TopologyContext;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.topology.base.BaseRichSpout;
import backtype.storm.tuple.Values;
import backtype.storm.utils.Utils;
import com.typesafe.config.Config;
import org.apache.eagle.dataproc.impl.storm.StormSpoutProvider;
import org.apache.eagle.datastream.ExecutionEnvironments;
import org.apache.eagle.datastream.storm.StormExecutionEnvironment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.TreeMap;

/**
 * Created on 2/16/16.
 */
public class NotificationPluginTestMain {
    public static void main(String[] args){
        System.setProperty("config.resource", "/application-plugintest.conf");
        StormExecutionEnvironment env = ExecutionEnvironments.getStorm();
        env.fromSpout(createProvider(env.getConfig())).withOutputFields(2).nameAs("testSpout").alertWithConsumer("testStream", "testExecutor");
        env.execute();
    }

    public static StormSpoutProvider createProvider(Config config) {
        return new StormSpoutProvider(){

            @Override
            public BaseRichSpout getSpout(Config context) {
                return new TestSpout();
            }
        };
    }

    public static class TestSpout extends BaseRichSpout {
        private static final Logger LOG = LoggerFactory.getLogger(TestSpout.class);
        private SpoutOutputCollector collector;
        public TestSpout() {
        }

        @Override
        public void declareOutputFields(OutputFieldsDeclarer declarer) {
        }

        @Override
        public void open(Map conf, TopologyContext context, SpoutOutputCollector collector) {
            this.collector = collector;
        }

        @Override
        public void nextTuple() {
            Utils.sleep(5000);
            LOG.info("emitted tuple ...");
            Map<String, Object> map = new TreeMap<>();
            map.put("testAttribute", "testValue");
            collector.emit(new Values("testStream", map));
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="Encoding" useUTFGuessing="true" native2AsciiForPropertiesFiles="false">
    <file url="file://$PROJECT_DIR$" charset="UTF-8" />
    <file url="file://$PROJECT_DIR$/puissance4-core" charset="UTF-8" />
    <file url="file://$PROJECT_DIR$/puissance4-web" charset="UTF-8" />
  </component>
</project>


text: require("./../src/cli");


text:
body {
  background-color: #1b1b1b;  /* Fallback background if image could not be loaded */
  background-image: url(../img/background.png);
  margin-bottom: 45px;  /* separates content from the bottom of the page, noticeable in mobile view */
}

.container-fluid {
  max-width: 800px;  /* prevents content from growing too large */

  padding-left: 35px;  /* prevents content from "touching" the edges of the screen */
  padding-right: 35px;
}

#logo {
  margin-top: 40px;
  margin-bottom: 50px;
  max-height: 90px;    /* makes the image smaller keeping original ratio */
}

#quote-container {
  padding: 20px;
  margin-bottom: 20px;  /* distance from the two buttons */
  /*opacity: 0.1; -> nope, it makes child elements transparent too */
  background-color: #0a0a0a;  /* Fallback background color, suggested by CSSLint*/
  background: rgba(0%, 0%, 0%, 0.3);  /* pure black with 30% opacity */
  border-radius: 10px;
}

#authorimg {
  padding: 8px;  /* increases size of thumbnail's white frame */
}

#quote {
  color: #ddd;  /* a brighter color to make the quote more readable */
  font-size: 20px;
  /* Adjustments to Bootstrap's default style */
  padding-right: 0px;
  margin-bottom: 0px;
  margin-left: -7px;
}

/* This CSS is applied only when the screen width is < 768px, since according to Bootstrap docs under that value "mobile view" is activated.
Thanks --> http://stackoverflow.com/questions/16410659/bootstrap-removing-padding-or-margin-when-screen-size-is-smaller */
@media (max-width: 767px) {
  #quote {
    margin-top: 20px;
    margin-left: 0px;
  }
}

.btn {
  /* Increases font size in the buttons ("button" selector is not enough, have to override this class) */
  font-size: 16px;
}

#footer-note {
  color: #ddd;
  margin-top: 55px;
}


text:
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;

namespace PrismSample
{
    public class NavigationPath
    {
        public NavigationPath(string page, bool clear)
        {
            Page = page;
            Clear = clear;
        }

        public NavigationPath(string page, bool clear, params (string Name, string Value)[] parameters)
        {
            Page = page;
            Clear = clear;
            AddParameter(parameters);
        }

        private bool Clear { get; set; }

        private NavigationPath Parent { get; set; }

        private NavigationPath Child { get; set; }

        public string Page { get; }

        public IEnumerable<(string Name, string Value)> Parameters => _parameters.Select(x => x).ToList().AsReadOnly();

        List<(string Name, string Value)> _parameters = new List<(string Name, string Value)>();

        public NavigationPath AddParameter(params (string Name, string Value)[] parameters)
        {
            _parameters.AddRange(parameters);
            return this;
        }

        public NavigationPath AddPage(string page)
        {
            return (Child = new NavigationPath(page, false) { Parent = this });
        }

        public NavigationPath AddPage(string page, params (string Name, string Value)[] parameters)
        {
            return (Child = new NavigationPath(page, false, parameters) { Parent = this });
        }

        public override string ToString()
        {
            return Build();
        }

        public string Build()
        {
            var page = this;
            while (page.Parent != null)
            {
                page = page.Parent;
            }
            var sb = new StringBuilder();
            if (page.Clear)
            {
                sb.Append("/");
            }
            Append(page, ref sb);
            while (page.Child != null)
            {
                page = page.Child;
                sb.Append("/");
                Append(page, ref sb);
            }
            return sb.ToString();
        }

        private void Append(NavigationPath path, ref StringBuilder sb)
        {
            sb.Append(path.Page ?? "null");
            if (path._parameters.Any())
            {
                sb.Append("?");
                foreach (var item in path._parameters)
                {
                    var name = WebUtility.UrlEncode(item.Name);
                    var value = WebUtility.UrlEncode(item.Value);
                    sb.Append($"{name}={value}&");
                }
            }
        }
    }
}


text:
"""Utilities for debugging garbage collection, leaked memory, etc."""

from __future__ import division

import gc

def get_objects_by_typename():
    gc.collect()
    x = {}
    for obj in gc.get_objects():
        t = type(obj).__name__
        if t in x:
            x[t].append(obj)
        else:
            x[t] = [obj]
    return x

def get_objects_by_livecount(obj_dict=None):
    if not obj_dict:
        obj_dict = get_objects_by_typename()
    else:
        gc.collect()
    lst = [(len(val), k) for (k, val) in obj_dict.iteritems()]
    lst.sort()
    return lst

def get_referrers(obj, path=None):
    if not path:
        path = []
    referrers = gc.get_referrers(obj)
    for edge in path:
        referrers = gc.get_referrers(referrers[edge])
    return referrers

def count_object_by_name(name):
    objects = get_objects_by_livecount()
    for (count, oName) in objects:
        if oName==name:
            return count
    return 0


text:
namespace eja
{
	class unfocus_proxy : public QProxyStyle
	{
	public:
		unfocus_proxy(QStyle *baseStyle = 0) : QProxyStyle(baseStyle) {}

		void drawPrimitive(PrimitiveElement element, const QStyleOption *option, QPainter *painter, const QWidget *widget) const
		{
			if (element == QStyle::PE_FrameFocusRect)
				return;

			QProxyStyle::drawPrimitive(element, option, painter, widget);
		}
	};
}

#endif


text:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading;

namespace Sun.Plasma.ViewModel
{
    /// <summary>
    /// ViewModel for the news control
    /// </summary>
    public class ViewModelNews : ViewModelBase
    {
        public ViewModelNews()
        {

        }

        private IEnumerable<Core.Feeds.NewsFeedEntry> _newsFeeds;
        public IEnumerable<Core.Feeds.NewsFeedEntry> NewsFeeds
        {
            get
            {
                return this._newsFeeds;
            }
            set
            {
                this._newsFeeds = value;
                OnPropertyChanged("NewsFeeds");
            }
        }

        /// <summary>
        /// Loads the news feeds from the SUN forum
        /// </summary>
        public void LoadNewsFeeds()
        {
            var url = ConfigurationManager.AppSettings["NewsFeedUrl"];
            if (string.IsNullOrEmpty(url))
            {
                ViewModelTools.Logger.ErrorFormat("No Rss feed url defined in the application configuration file!");
                throw new ConfigurationErrorsException("No Rss feed url defined in the application configuraito file!");
            }

            var reader = new Core.Feeds.RssNewsFeedReader();
            this.NewsFeeds = reader.GetNewsFeeds(url).OrderByDescending(x => x.PublishDate).Take(10);
        }
    }
}


text:
import { Geometric3, Unit } from '@geometryzen/multivectors';
import { Block3 } from './Block3';

const KILOGRAM = Unit.KILOGRAM;
const METER = Unit.METER;
// const SECOND = Unit.SECOND;
// const MOTION = KILOGRAM.mul(METER).div(SECOND);

describe("Block3", function () {
    describe("updateAngularVelocity", function () {
        it("should accurately update Ω", function () {
            const body = new Block3(Geometric3.scalar(2), Geometric3.scalar(3), Geometric3.scalar(5));
            const w = body.width;
            const h = body.height;
            const d = body.depth;
            const ww = w.a * w.a;
            const hh = h.a * h.a;
            const dd = d.a * d.a;
            body.M = Geometric3.scalar(Math.random());
            body.L.yz = 0;
            body.L.zx = 0;
            body.L.xy = 1;
            body.updateAngularVelocity();
            expect(body.Ω.yz).toBe((12 / body.M.a) * body.L.yz / (hh + dd));
            expect(body.Ω.zx).toBe((12 / body.M.a) * body.L.zx / (ww + dd));
            expect(body.Ω.xy).toBe((12 / body.M.a) * body.L.xy / (ww + hh));
        });
    });
    describe("moment of inertia tensor", function () {
        // Set random block dimensions in the constructor but override later.
        const body = new Block3(Geometric3.scalar(Math.random(), METER));

        body.width = Geometric3.scalar(4, METER);
        body.height = Geometric3.scalar(3, METER);
        body.depth = Geometric3.scalar(5, METER);
        body.M = Geometric3.scalar(12, KILOGRAM);

        it("should be a scaled identity matrix", function () {
            const w = body.width.a;
            const h = body.height.a;
            const d = body.depth.a;
            expect(body.I.getElement(0, 0)).toBe(h * h + d * d);
            expect(body.I.getElement(0, 1)).toBe(0);
            expect(body.I.getElement(0, 2)).toBe(0);
            expect(body.I.getElement(1, 0)).toBe(0);
            expect(body.I.getElement(1, 1)).toBe(w * w + d * d);
            expect(body.I.getElement(1, 2)).toBe(0);
            expect(body.I.getElement(2, 0)).toBe(0);
            expect(body.I.getElement(2, 1)).toBe(0);
            expect(body.I.getElement(2, 2)).toBe(w * w + h * h);
        });
        it("M", function () {
            expect(body.I.uom.dimensions.M.numer).toBe(1);
            expect(body.I.uom.dimensions.M.denom).toBe(1);
        });
        it("L", function () {
            expect(body.I.uom.dimensions.L.numer).toBe(2);
            expect(body.I.uom.dimensions.L.denom).toBe(1);
        });
        it("T", function () {
            expect(body.I.uom.dimensions.T.numer).toBe(0);
            expect(body.I.uom.dimensions.T.denom).toBe(1);
        });
        it("Q", function () {
            expect(body.I.uom.dimensions.Q.numer).toBe(0);
            expect(body.I.uom.dimensions.Q.denom).toBe(1);
        });
    });
});


text:
# Migrating from v0.x to v1.x

In version 1.x, We've switched from a *synchronous* API to an *asynchronous* one using [Promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
because synchronous ajax calls are [deprecated](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests#Synchronous_request)
and frowned upon due to performance implications.

> **HEADS UP:** StackTrace.JS does *NOT* provide a Promises polyfill by default, but we do distribute a [version with polyfills](https://raw.githubusercontent.com/stacktracejs/stacktrace.js/master/dist/stacktrace-with-polyfills.min.js)!
> Check [the Promises page on caniuse.com](http://caniuse.com/#feat=promises) to determine if you need one.

All methods now return [stackframe](https://github.com/stacktracejs/stackframe)s.
This Object representation is modeled closely after StackFrame representations in Gecko and V8.
All you have to do to get stacktrace.js v0.x behavior is call `.toString()` on a stackframe.

### Use Case: Give me a trace from wherever I am right now

v0.x:
```js
printStackTrace();
//===> Array[String]
```

v1.x:
```js
StackTrace.get().then(callback).catch(errback);
//===> Promise(Array[StackFrame], Error)
```

`StackTrace.get()` returns a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)

### Use Case: Parse this error

v0.x:
```js
var error = new Error('Boom');
printStackTrace({e: error});
//===> Array[String]
```

v1.x:
```js
var error = new Error('Boom');
StackTrace.fromError(error).then(callback).catch(errback);
//===> Promise(Array[StackFrame], Error)
```

If this is all you need, you don't even need the full stacktrace.js library! Just use [error-stack-parser](https://github.com/stacktracejs/error-stack-parser)!
```js
ErrorStackParser.parse(new Error('boom'));
```

### Use Case: Give me a trace anytime this function is called

Instrumenting now takes `Function` references instead of `String`s.

v0.x:
```js
function interestingFn() {/* ... */}

var p = new printStackTrace.implementation();
p.instrumentFunction(this, 'interestingFn', logStackTrace);
//===> Function (instrumented)

p.deinstrumentFunction(this, 'interestingFn');
//===> Function (original)
```

v1.x:
```js
function interestingFn() {/* ... */}

StackTrace.instrument(interestingFn, callback, errback);
//===> Function (instrumented)

StackTrace.deinstrument(interestingFn);
//===> Function (original)
```


text:
package android.graphics.drawable;

import android.annotation.ColorInt;
import android.annotation.DrawableRes;
import android.content.res.ColorStateList;
import android.content.ContentResolver;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PorterDuff;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.TextUtils;
import android.util.Log;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Objects;

/**
 * An umbrella container for several serializable graphics representations, including Bitmaps,
 * compressed bitmap images (e.g. JPG or PNG), and drawable resources (including vectors).
 *
 * Much ink
 * has been spilled on the best way to load images, and many clients may have different needs when
 * it comes to threading and fetching. This class is therefore focused on encapsulation rather than
 * behavior.
 */

public final class Icon implements Parcelable {
    private static final String TAG = "Icon";

    /** @hide */
    public static final int TYPE_BITMAP   = 1;
    /** @hide */
    public static final int TYPE_RESOURCE = 2;
    /** @hide */
    public static final int TYPE_DATA     = 3;
    /** @hide */
    public static final int TYPE_URI      = 4;

    private static final int VERSION_STREAM_SERIALIZER = 1;

    private final int mType;

    private ColorStateList mTintList;
    static final PorterDuff.Mode DEFAULT_TINT_MODE = Drawable.DEFAULT_TINT_MODE; // SRC_IN
    private PorterDuff.Mode mTintMode = DEFAULT_TINT_MODE;

    // To avoid adding unnecessary overhead, we have a few basic objects that get repurposed
    // based on the value of mType.

    // TYPE_BITMAP: Bitmap
    // TYPE_RESOURCE: Resources
    // TYPE_DATA: DataBytes
    private Object          mObj1;

    // TYPE_RESOURCE: package name
    // TYPE_URI: uri string
    private String          mString1;

    // TYPE_RESOURCE: resId
    // TYPE_DATA: data length
    private int             mInt1;

    // TYPE_DATA: data offset
    private int             mInt2;

    /**
     * @return The type of image data held in this Icon. One of
     * {@link #TYPE_BITMAP},
     * {@link #TYPE_RESOURCE},
     * {@link #TYPE_DATA}, or
     * {@link #TYPE_URI}.
     * @hide
     */
    public int getType() {
        return mType;
    }

    /**
     * @return The {@link android.graphics.Bitmap} held by this {@link #TYPE_BITMAP} Icon.
     * @hide
     */
    public Bitmap getBitmap() {
        if (mType != TYPE_BITMAP) {
            throw new IllegalStateException("called getBitmap() on " + this);
        }
        return (Bitmap) mObj1;
    }

    private void setBitmap(Bitmap b) {
        mObj1 = b;
    }

    /**
     * @return The length of the compressed bitmap byte array held by this {@link #TYPE_DATA} Icon.
     * @hide
     */
    public int getDataLength() {
        if (mType != TYPE_DATA) {
            throw new IllegalStateException("called getDataLength() on " + this);
        }
        synchronized (this) {
            return mInt1;
        }
    }

    /**
     * @return The offset into the byte array held by this {@link #TYPE_DATA} Icon at which
     * valid compressed bitmap data is found.
     * @hide
     */
    public int getDataOffset() {
        if (mType != TYPE_DATA) {
            throw new IllegalStateException("called getDataOffset() on " + this);
        }
        synchronized (this) {
            return mInt2;
        }
    }

    /**
     * @return The byte array held by this {@link #TYPE_DATA} Icon ctonaining compressed
     * bitmap data.
     * @hide
     */
    public byte[] getDataBytes() {
        if (mType != TYPE_DATA) {
            throw new IllegalStateException("called getDataBytes() on " + this);
        }
        synchronized (this) {
            return (byte[]) mObj1;
        }
    }

    /**
     * @return The {@link android.content.res.Resources} for this {@link #TYPE_RESOURCE} Icon.
     * @hide
     */
    public Resources getResources() {
        if (mType != TYPE_RESOURCE) {
            throw new IllegalStateException("called getResources() on " + this);
        }
        return (Resources) mObj1;
    }

    /**
     * @return The package containing resources for this {@link #TYPE_RESOURCE} Icon.
     * @hide
     */
    public String getResPackage() {
        if (mType != TYPE_RESOURCE) {
            throw new IllegalStateException("called getResPackage() on " + this);
        }
        return mString1;
    }

    /**
     * @return The resource ID for this {@link #TYPE_RESOURCE} Icon.
     * @hide
     */
    public int getResId() {
        if (mType != TYPE_RESOURCE) {
            throw new IllegalStateException("called getResId() on " + this);
        }
        return mInt1;
    }

    /**
     * @return The URI (as a String) for this {@link #TYPE_URI} Icon.
     * @hide
     */
    public String getUriString() {
        if (mType != TYPE_URI) {
            throw new IllegalStateException("called getUriString() on " + this);
        }
        return mString1;
    }

    /**
     * @return The {@link android.net.Uri} for this {@link #TYPE_URI} Icon.
     * @hide
     */
    public Uri getUri() {
        return Uri.parse(getUriString());
    }

    private static final String typeToString(int x) {
        switch (x) {
            case TYPE_BITMAP: return "BITMAP";
            case TYPE_DATA: return "DATA";
            case TYPE_RESOURCE: return "RESOURCE";
            case TYPE_URI: return "URI";
            default: return "UNKNOWN";
        }
    }

    /**
     * Invokes {@link #loadDrawable(Context)} on the given {@link android.os.Handler Handler}
     * and then sends andThen to the same Handler when finished.
     *
     * @param context {@link android.content.Context Context} in which to load the drawable; see
     *                {@link #loadDrawable(Context)}
     * @param andThen {@link android.os.Message} to send to its target once the drawable
     *                is available. The {@link android.os.Message#obj obj}
     *                property is populated with the Drawable.
     */
    public void loadDrawableAsync(Context context, Message andThen) {
        if (andThen.getTarget() == null) {
            throw new IllegalArgumentException("callback message must have a target handler");
        }
        new LoadDrawableTask(context, andThen).runAsync();
    }

    /**
     * Invokes {@link #loadDrawable(Context)} on a background thread and notifies the
     * {@link OnDrawableLoadedListener#onDrawableLoaded listener}  on the {@code handler}
     * when finished.
     *
     * @param context {@link Context Context} in which to load the drawable; see
     *                {@link #loadDrawable(Context)}
     * @param listener to be {@link OnDrawableLoadedListener#onDrawableLoaded notified} when
     *                 {@link #loadDrawable(Context)} finished
     * @param handler {@link Handler} on which to notify the {@code listener}
     */
    public void loadDrawableAsync(Context context, final OnDrawableLoadedListener listener,
            Handler handler) {
        new LoadDrawableTask(context, handler, listener).runAsync();
    }

    /**
     * Returns a Drawable that can be used to draw the image inside this Icon, constructing it
     * if necessary. Depending on the type of image, this may not be something you want to do on
     * the UI thread, so consider using
     * {@link #loadDrawableAsync(Context, Message) loadDrawableAsync} instead.
     *
     * @param context {@link android.content.Context Context} in which to load the drawable; used
     *                to access {@link android.content.res.Resources Resources}, for example.
     * @return A fresh instance of a drawable for this image, yours to keep.
     */
    public Drawable loadDrawable(Context context) {
        final Drawable result = loadDrawableInner(context);
        if (result != null && (mTintList != null || mTintMode != DEFAULT_TINT_MODE)) {
            result.mutate();
            result.setTintList(mTintList);
            result.setTintMode(mTintMode);
        }
        return result;
    }

    /**
     * Do the heavy lifting of loading the drawable, but stop short of applying any tint.
     */
    private Drawable loadDrawableInner(Context context) {
        switch (mType) {
            case TYPE_BITMAP:
                return new BitmapDrawable(context.getResources(), getBitmap());
            case TYPE_RESOURCE:
                if (getResources() == null) {
                    // figure out where to load resources from
                    String resPackage = getResPackage();
                    if (TextUtils.isEmpty(resPackage)) {
                        // if none is specified, try the given context
                        resPackage = context.getPackageName();
                    }
                    if ("android".equals(resPackage)) {
                        mObj1 = Resources.getSystem();
                    } else {
                        final PackageManager pm = context.getPackageManager();
                        try {
                            ApplicationInfo ai = pm.getApplicationInfo(
                                    resPackage, PackageManager.GET_UNINSTALLED_PACKAGES);
                            if (ai != null) {
                                mObj1 = pm.getResourcesForApplication(ai);
                            } else {
                                break;
                            }
                        } catch (PackageManager.NameNotFoundException e) {
                            Log.e(TAG, String.format("Unable to find pkg=%s for icon %s",
                                    resPackage, this), e);
                            break;
                        }
                    }
                }
                try {
                    return getResources().getDrawable(getResId(), context.getTheme());
                } catch (RuntimeException e) {
                    Log.e(TAG, String.format("Unable to load resource 0x%08x from pkg=%s",
                                    getResId(),
                                    getResPackage()),
                            e);
                }
                break;
            case TYPE_DATA:
                return new BitmapDrawable(context.getResources(),
                    BitmapFactory.decodeByteArray(getDataBytes(), getDataOffset(), getDataLength())
                );
            case TYPE_URI:
                final Uri uri = getUri();
                final String scheme = uri.getScheme();
                InputStream is = null;
                if (ContentResolver.SCHEME_CONTENT.equals(scheme)
                        || ContentResolver.SCHEME_FILE.equals(scheme)) {
                    try {
                        is = context.getContentResolver().openInputStream(uri);
                    } catch (Exception e) {
                        Log.w(TAG, "Unable to load image from URI: " + uri, e);
                    }
                } else {
                    try {
                        is = new FileInputStream(new File(mString1));
                    } catch (FileNotFoundException e) {
                        Log.w(TAG, "Unable to load image from path: " + uri, e);
                    }
                }
                if (is != null) {
                    return new BitmapDrawable(context.getResources(),
                            BitmapFactory.decodeStream(is));
                }
                break;
        }
        return null;
    }

    /**
     * Load the requested resources under the given userId, if the system allows it,
     * before actually loading the drawable.
     *
     * @hide
     */
    public Drawable loadDrawableAsUser(Context context, int userId) {
        if (mType == TYPE_RESOURCE) {
            String resPackage = getResPackage();
            if (TextUtils.isEmpty(resPackage)) {
                resPackage = context.getPackageName();
            }
            if (getResources() == null && !(getResPackage().equals("android"))) {
                final PackageManager pm = context.getPackageManager();
                try {
                    // assign getResources() as the correct user
                    mObj1 = pm.getResourcesForApplicationAsUser(resPackage, userId);
                } catch (PackageManager.NameNotFoundException e) {
                    Log.e(TAG, String.format("Unable to find pkg=%s user=%d",
                                    getResPackage(),
                                    userId),
                            e);
                }
            }
        }
        return loadDrawable(context);
    }

    /** @hide */
    public static final int MIN_ASHMEM_ICON_SIZE = 128 * (1 << 10);

    /**
     * Puts the memory used by this instance into Ashmem memory, if possible.
     * @hide
     */
    public void convertToAshmem() {
        if (mType == TYPE_BITMAP &&
            getBitmap().isMutable() &&
            getBitmap().getAllocationByteCount() >= MIN_ASHMEM_ICON_SIZE) {
            setBitmap(getBitmap().createAshmemBitmap());
        }
    }

    /**
     * Writes a serialized version of an Icon to the specified stream.
     *
     * @param stream The stream on which to serialize the Icon.
     * @hide
     */
    public void writeToStream(OutputStream stream) throws IOException {
        DataOutputStream dataStream = new DataOutputStream(stream);

        dataStream.writeInt(VERSION_STREAM_SERIALIZER);
        dataStream.writeByte(mType);

        switch (mType) {
            case TYPE_BITMAP:
                getBitmap().compress(Bitmap.CompressFormat.PNG, 100, dataStream);
                break;
            case TYPE_DATA:
                dataStream.writeInt(getDataLength());
                dataStream.write(getDataBytes(), getDataOffset(), getDataLength());
                break;
            case TYPE_RESOURCE:
                dataStream.writeUTF(getResPackage());
                dataStream.writeInt(getResId());
                break;
            case TYPE_URI:
                dataStream.writeUTF(getUriString());
                break;
        }
    }

    private Icon(int mType) {
        this.mType = mType;
    }

    /**
     * Create an Icon from the specified stream.
     *
     * @param stream The input stream from which to reconstruct the Icon.
     * @hide
     */
    public static Icon createFromStream(InputStream stream) throws IOException {
        DataInputStream inputStream = new DataInputStream(stream);

        final int version = inputStream.readInt();
        if (version >= VERSION_STREAM_SERIALIZER) {
            final int type = inputStream.readByte();
            switch (type) {
                case TYPE_BITMAP:
                    return createWithBitmap(BitmapFactory.decodeStream(inputStream));
                case TYPE_DATA:
                    final int length = inputStream.readInt();
                    final byte[] data = new byte[length];
                    inputStream.read(data, 0 /* offset */, length);
                    return createWithData(data, 0 /* offset */, length);
                case TYPE_RESOURCE:
                    final String packageName = inputStream.readUTF();
                    final int resId = inputStream.readInt();
                    return createWithResource(packageName, resId);
                case TYPE_URI:
                    final String uriOrPath = inputStream.readUTF();
                    return createWithContentUri(uriOrPath);
            }
        }
        return null;
    }

    /**
     * Compares if this icon is constructed from the same resources as another icon.
     * Note that this is an inexpensive operation and doesn't do deep Bitmap equality comparisons.
     *
     * @param otherIcon the other icon
     * @return whether this icon is the same as the another one
     * @hide
     */
    public boolean sameAs(Icon otherIcon) {
        if (otherIcon == this) {
            return true;
        }
        if (mType != otherIcon.getType()) {
            return false;
        }
        switch (mType) {
            case TYPE_BITMAP:
                return getBitmap() == otherIcon.getBitmap();
            case TYPE_DATA:
                return getDataLength() == otherIcon.getDataLength()
                        && getDataOffset() == otherIcon.getDataOffset()
                        && getDataBytes() == otherIcon.getDataBytes();
            case TYPE_RESOURCE:
                return getResId() == otherIcon.getResId()
                        && Objects.equals(getResPackage(), otherIcon.getResPackage());
            case TYPE_URI:
                return Objects.equals(getUriString(), otherIcon.getUriString());
        }
        return false;
    }

    /**
     * Create an Icon pointing to a drawable resource.
     * @param context The context for the application whose resources should be used to resolve the
     *                given resource ID.
     * @param resId ID of the drawable resource
     */
    public static Icon createWithResource(Context context, @DrawableRes int resId) {
        if (context == null) {
            throw new IllegalArgumentException("Context must not be null.");
        }
        final Icon rep = new Icon(TYPE_RESOURCE);
        rep.mInt1 = resId;
        rep.mString1 = context.getPackageName();
        return rep;
    }

    /**
     * Version of createWithResource that takes Resources. Do not use.
     * @hide
     */
    public static Icon createWithResource(Resources res, @DrawableRes int resId) {
        if (res == null) {
            throw new IllegalArgumentException("Resource must not be null.");
        }
        final Icon rep = new Icon(TYPE_RESOURCE);
        rep.mInt1 = resId;
        rep.mString1 = res.getResourcePackageName(resId);
        return rep;
    }

    /**
     * Create an Icon pointing to a drawable resource.
     * @param resPackage Name of the package containing the resource in question
     * @param resId ID of the drawable resource
     */
    public static Icon createWithResource(String resPackage, @DrawableRes int resId) {
        if (resPackage == null) {
            throw new IllegalArgumentException("Resource package name must not be null.");
        }
        final Icon rep = new Icon(TYPE_RESOURCE);
        rep.mInt1 = resId;
        rep.mString1 = resPackage;
        return rep;
    }

    /**
     * Create an Icon pointing to a bitmap in memory.
     * @param bits A valid {@link android.graphics.Bitmap} object
     */
    public static Icon createWithBitmap(Bitmap bits) {
        if (bits == null) {
            throw new IllegalArgumentException("Bitmap must not be null.");
        }
        final Icon rep = new Icon(TYPE_BITMAP);
        rep.setBitmap(bits);
        return rep;
    }

    /**
     * Create an Icon pointing to a compressed bitmap stored in a byte array.
     * @param data Byte array storing compressed bitmap data of a type that
     *             {@link android.graphics.BitmapFactory}
     *             can decode (see {@link android.graphics.Bitmap.CompressFormat}).
     * @param offset Offset into data at which the bitmap data starts
     * @param length Length of the bitmap data
     */
    public static Icon createWithData(byte[] data, int offset, int length) {
        if (data == null) {
            throw new IllegalArgumentException("Data must not be null.");
        }
        final Icon rep = new Icon(TYPE_DATA);
        rep.mObj1 = data;
        rep.mInt1 = length;
        rep.mInt2 = offset;
        return rep;
    }

    /**
     * Create an Icon pointing to an image file specified by URI.
     *
     * @param uri A uri referring to local content:// or file:// image data.
     */
    public static Icon createWithContentUri(String uri) {
        if (uri == null) {
            throw new IllegalArgumentException("Uri must not be null.");
        }
        final Icon rep = new Icon(TYPE_URI);
        rep.mString1 = uri;
        return rep;
    }

    /**
     * Create an Icon pointing to an image file specified by URI.
     *
     * @param uri A uri referring to local content:// or file:// image data.
     */
    public static Icon createWithContentUri(Uri uri) {
        if (uri == null) {
            throw new IllegalArgumentException("Uri must not be null.");
        }
        final Icon rep = new Icon(TYPE_URI);
        rep.mString1 = uri.toString();
        return rep;
    }

    /**
     * Store a color to use whenever this Icon is drawn.
     *
     * @param tint a color, as in {@link Drawable#setTint(int)}
     * @return this same object, for use in chained construction
     */
    public Icon setTint(@ColorInt int tint) {
        return setTintList(ColorStateList.valueOf(tint));
    }

    /**
     * Store a color to use whenever this Icon is drawn.
     *
     * @param tintList as in {@link Drawable#setTintList(ColorStateList)}, null to remove tint
     * @return this same object, for use in chained construction
     */
    public Icon setTintList(ColorStateList tintList) {
        mTintList = tintList;
        return this;
    }

    /**
     * Store a blending mode to use whenever this Icon is drawn.
     *
     * @param mode a blending mode, as in {@link Drawable#setTintMode(PorterDuff.Mode)}, may be null
     * @return this same object, for use in chained construction
     */
    public Icon setTintMode(PorterDuff.Mode mode) {
        mTintMode = mode;
        return this;
    }

    /** @hide */
    public boolean hasTint() {
        return (mTintList != null) || (mTintMode != DEFAULT_TINT_MODE);
    }

    /**
     * Create an Icon pointing to an image file specified by path.
     *
     * @param path A path to a file that contains compressed bitmap data of
     *           a type that {@link android.graphics.BitmapFactory} can decode.
     */
    public static Icon createWithFilePath(String path) {
        if (path == null) {
            throw new IllegalArgumentException("Path must not be null.");
        }
        final Icon rep = new Icon(TYPE_URI);
        rep.mString1 = path;
        return rep;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("Icon(typ=").append(typeToString(mType));
        switch (mType) {
            case TYPE_BITMAP:
                sb.append(" size=")
                        .append(getBitmap().getWidth())
                        .append("x")
                        .append(getBitmap().getHeight());
                break;
            case TYPE_RESOURCE:
                sb.append(" pkg=")
                        .append(getResPackage())
                        .append(" id=")
                        .append(String.format("0x%08x", getResId()));
                break;
            case TYPE_DATA:
                sb.append(" len=").append(getDataLength());
                if (getDataOffset() != 0) {
                    sb.append(" off=").append(getDataOffset());
                }
                break;
            case TYPE_URI:
                sb.append(" uri=").append(getUriString());
                break;
        }
        if (mTintList != null) {
            sb.append(" tint=");
            String sep = "";
            for (int c : mTintList.getColors()) {
                sb.append(String.format("%s0x%08x", sep, c));
                sep = "|";
            }
        }
        if (mTintMode != DEFAULT_TINT_MODE) sb.append(" mode=").append(mTintMode);
        sb.append(")");
        return sb.toString();
    }

    /**
     * Parcelable interface
     */
    public int describeContents() {
        return (mType == TYPE_BITMAP || mType == TYPE_DATA)
                ? Parcelable.CONTENTS_FILE_DESCRIPTOR : 0;
    }

    // ===== Parcelable interface ======

    private Icon(Parcel in) {
        this(in.readInt());
        switch (mType) {
            case TYPE_BITMAP:
                final Bitmap bits = Bitmap.CREATOR.createFromParcel(in);
                mObj1 = bits;
                break;
            case TYPE_RESOURCE:
                final String pkg = in.readString();
                final int resId = in.readInt();
                mString1 = pkg;
                mInt1 = resId;
                break;
            case TYPE_DATA:
                final int len = in.readInt();
                final byte[] a = in.readBlob();
                if (len != a.length) {
                    throw new RuntimeException("internal unparceling error: blob length ("
                            + a.length + ") != expected length (" + len + ")");
                }
                mInt1 = len;
                mObj1 = a;
                break;
            case TYPE_URI:
                final String uri = in.readString();
                mString1 = uri;
                break;
            default:
                throw new RuntimeException("invalid "
                        + this.getClass().getSimpleName() + " type in parcel: " + mType);
        }
        if (in.readInt() == 1) {
            mTintList = ColorStateList.CREATOR.createFromParcel(in);
        }
        mTintMode = PorterDuff.intToMode(in.readInt());
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(mType);
        switch (mType) {
            case TYPE_BITMAP:
                final Bitmap bits = getBitmap();
                getBitmap().writeToParcel(dest, flags);
                break;
            case TYPE_RESOURCE:
                dest.writeString(getResPackage());
                dest.writeInt(getResId());
                break;
            case TYPE_DATA:
                dest.writeInt(getDataLength());
                dest.writeBlob(getDataBytes(), getDataOffset(), getDataLength());
                break;
            case TYPE_URI:
                dest.writeString(getUriString());
                break;
        }
        if (mTintList == null) {
            dest.writeInt(0);
        } else {
            dest.writeInt(1);
            mTintList.writeToParcel(dest, flags);
        }
        dest.writeInt(PorterDuff.modeToInt(mTintMode));
    }

    public static final Parcelable.Creator<Icon> CREATOR
            = new Parcelable.Creator<Icon>() {
        public Icon createFromParcel(Parcel in) {
            return new Icon(in);
        }

        public Icon[] newArray(int size) {
            return new Icon[size];
        }
    };

    /**
     * Implement this interface to receive a callback when
     * {@link #loadDrawableAsync(Context, OnDrawableLoadedListener, Handler) loadDrawableAsync}
     * is finished and your Drawable is ready.
     */
    public interface OnDrawableLoadedListener {
        void onDrawableLoaded(Drawable d);
    }

    /**
     * Wrapper around loadDrawable that does its work on a pooled thread and then
     * fires back the given (targeted) Message.
     */
    private class LoadDrawableTask implements Runnable {
        final Context mContext;
        final Message mMessage;

        public LoadDrawableTask(Context context, final Handler handler,
                final OnDrawableLoadedListener listener) {
            mContext = context;
            mMessage = Message.obtain(handler, new Runnable() {
                    @Override
                    public void run() {
                        listener.onDrawableLoaded((Drawable) mMessage.obj);
                    }
                });
        }

        public LoadDrawableTask(Context context, Message message) {
            mContext = context;
            mMessage = message;
        }

        @Override
        public void run() {
            mMessage.obj = loadDrawable(mContext);
            mMessage.sendToTarget();
        }

        public void runAsync() {
            AsyncTask.THREAD_POOL_EXECUTOR.execute(this);
        }
    }
}


text:
/*global QUnit:false, module:false, test:false, asyncTest:false, expect:false*/
/*global start:false, stop:false ok:false, equal:false, notEqual:false, deepEqual:false*/
/*global notDeepEqual:false, strictEqual:false, notStrictEqual:false, raises:false*/
/*
  ======== A Handy Little QUnit Reference ========
  http://docs.jquery.com/QUnit

  Test methods:
    expect(numAssertions)
    stop(increment)
    start(decrement)
  Test assertions:
    ok(value, [message])
    equal(actual, expected, [message])
    notEqual(actual, expected, [message])
    deepEqual(actual, expected, [message])
    notDeepEqual(actual, expected, [message])
    strictEqual(actual, expected, [message])
    notStrictEqual(actual, expected, [message])
    raises(block, [expected], [message])
*/

module('Builder#requirejs');

test('exists', function() {
  expect(1);

  // Stop the test while we load jQuery.
  stop();

  // Load jQuery.
  require(['Builder'], function (Builder) {
    // Continue testing.
    start();

    // Assert Builder exists
    ok(Builder, 'Builder as defined by requirejs exists');
  });
});


text:
using Newtonsoft.Json;

namespace KenticoInspector.Reports.UserPasswordAnalysis.Models.Data.Results
{
    public class CmsUserResultWithPasswordFormat : CmsUserResult
    {
        [JsonProperty(Order = 1)]
        public new string UserPasswordFormat { get; set; }

        public CmsUserResultWithPasswordFormat(CmsUser user)
            : base(user)
        {
            UserPasswordFormat = user.UserPasswordFormat;
        }
    }
}