text:
<?php
namespace Aura\Cli;

class ContextTest extends \PHPUnit_Framework_TestCase
{
    protected function newContext(array $globals = array())
    {
        $factory = new CliFactory;
        return $factory->newContext($globals);
    }

    public function test__get()
    {
        $context = $this->newContext(array(
            '_ENV' => array(
                'foo' => 'bar',
                'baz' => 'dib',
            ),
            '_SERVER' => array(
                'zim' => 'gir',
                'irk' => 'doom',
            ),
            'argv' => array(
                'a',
                '-b',
                '--cee',
            ),
        ));

        // get a server value
        $expect = 'gir';
        $actual = $context->server->get('zim', 'default');
        $this->assertSame($expect, $actual);

        // get an alternative server value
        $expect = 'default';
        $actual = $context->server->get('no-such-key', 'default');
        $this->assertSame($expect, $actual);

        // get an env key
        $expect = 'bar';
        $actual = $context->env->get('foo', 'default');
        $this->assertSame($expect, $actual);

        // get an alternative env key
        $expect = 'default';
        $actual = $context->env->get('no-such-key', 'default');
        $this->assertSame($expect, $actual);

        // get from putenv()
        putenv('PUTFOO=foo');
        $expect = 'foo';
        $actual = $context->env->get('PUTFOO');
        $this->assertSame($expect, $actual);
        $this->assertNull($context->env->get('PUTBAR'));

        // get all of one
        $expect = array(
                'a',
                '-b',
                '--cee',
        );
        $actual = $context->argv->get();
        $this->assertSame($expect, $actual);
    }

    public function testGetopt()
    {
        $context = $this->newContext(array(
            'argv' => array(
                'foo',
                'bar',
                '-f',
            )
        ));

        $getopt = $context->getopt(array('f:'));
        $this->assertInstanceOf('Aura\Cli\Context\Getopt', $getopt);

        $actual = $getopt->get();
        $expect = array(
            0 => 'foo',
            1 => 'bar',
        );

        $this->assertTrue($getopt->hasErrors());
        $errors = $getopt->getErrors();
        $actual = $errors[0];
        $expect = 'Aura\Cli\Exception\OptionParamRequired';
        $this->assertInstanceOf($expect, $actual);
        $expect = "The option '-f' requires a parameter.";
        $this->assertSame($expect, $actual->getMessage());
    }

    /**
     * Test that when using a getopt alias that whichever order you use
     * them in the result is the same
     */
    public function testGetoptAlias()
    {
        $context = $this->newContext(array(
            'argv' => array(
                '-f',
            )
        ));

        $getopt = $context->getopt(array('f,foo'));
        $this->assertInstanceOf('Aura\Cli\Context\Getopt', $getopt);

        $this->assertTrue($getopt->get('-f'));
        $this->assertTrue($getopt->get('--foo'));

        $getopt = $context->getopt(array('foo,f'));
        $this->assertInstanceOf('Aura\Cli\Context\Getopt', $getopt);

        $this->assertTrue($getopt->get('-f'));
        $this->assertTrue($getopt->get('--foo'));

        $context = $this->newContext(array(
            'argv' => array(
                '-foo',
            )
        ));

        $getopt = $context->getopt(array('f,foo'));
        $this->assertInstanceOf('Aura\Cli\Context\Getopt', $getopt);

        $this->assertTrue($getopt->get('-f'));
        $this->assertTrue($getopt->get('--foo'));

        $getopt = $context->getopt(array('foo,f'));
        $this->assertInstanceOf('Aura\Cli\Context\Getopt', $getopt);

        $this->assertTrue($getopt->get('-f'));
        $this->assertTrue($getopt->get('--foo'));
    }

    public function testGithubIssue32()
    {
        $context = $this->newContext();
        $getopt  = $context->getopt(array('f:'));
        $actual = $context->getopt_factory->getGetoptParser()->getOptions();
        $expect = array(
            '-f' => (object) array(
                'name' => '-f',
                'alias' => null,
                'multi' => false,
                'param' => 'required',
                'descr' => null,
            ),
        );
        $this->assertEquals($expect, $actual);
    }
}


text:
<?php

namespace FOS\UserBundle\Model;

use FOS\UserBundle\Util\CanonicalFieldsUpdater;
use FOS\UserBundle\Util\PasswordUpdaterInterface;

/**
 * Abstract User Manager implementation which can be used as base class for your
 * concrete manager.
 *
 * @author Johannes M. Schmitt <schmittjoh@gmail.com>
 */
abstract class UserManager implements UserManagerInterface
{
    private $passwordUpdater;
    private $canonicalFieldsUpdater;

    public function __construct(PasswordUpdaterInterface $passwordUpdater, CanonicalFieldsUpdater $canonicalFieldsUpdater)
    {
        $this->passwordUpdater = $passwordUpdater;
        $this->canonicalFieldsUpdater = $canonicalFieldsUpdater;
    }

    /**
     * {@inheritdoc}
     */
    public function createUser()
    {
        $class = $this->getClass();
        $user = new $class();

        return $user;
    }

    /**
     * {@inheritdoc}
     */
    public function findUserByEmail($email)
    {
        return $this->findUserBy(array('emailCanonical' => $this->canonicalFieldsUpdater->canonicalizeEmail($email)));
    }

    /**
     * {@inheritdoc}
     */
    public function findUserByUsername($username)
    {
        return $this->findUserBy(array('usernameCanonical' => $this->canonicalFieldsUpdater->canonicalizeUsername($username)));
    }

    /**
     * {@inheritdoc}
     */
    public function findUserByUsernameOrEmail($usernameOrEmail)
    {
        if (preg_match('/^.+\@\S+\.\S+$/', $usernameOrEmail)) {
            return $this->findUserByEmail($usernameOrEmail);
        }

        return $this->findUserByUsername($usernameOrEmail);
    }

    /**
     * {@inheritdoc}
     */
    public function findUserByConfirmationToken($token)
    {
        return $this->findUserBy(array('confirmationToken' => $token));
    }

    /**
     * {@inheritdoc}
     */
    public function updateCanonicalFields(UserInterface $user)
    {
        $this->canonicalFieldsUpdater->updateCanonicalFields($user);
    }

    /**
     * {@inheritdoc}
     */
    public function updatePassword(UserInterface $user)
    {
        $this->passwordUpdater->hashPassword($user);
    }

    /**
     * @return PasswordUpdaterInterface
     */
    protected function getPasswordUpdater()
    {
        return $this->passwordUpdater;
    }

    /**
     * @return CanonicalFieldsUpdater
     */
    protected function getCanonicalFieldsUpdater()
    {
        return $this->canonicalFieldsUpdater;
    }
}

redpajama_set_name: RedPajamaGithub


text:
//
//  NewsCommentTableViewController.m
//  CNBlogs
//
//  Created by 李远超 on 15/9/2.
//  Copyright (c) 2015年 liyc. All rights reserved.
//

#import "NewsCommentTableViewController.h"
#import "CommentTableViewCell.h"
#import "NewsModel.h"
#import "CommentModel.h"

@interface NewsCommentTableViewController ()

@property (nonatomic, strong) CommentTableViewCell *prototypeCell;

@end

@implementation NewsCommentTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.tableView registerNib:[UINib nibWithNibName:@"CommentTableViewCell" bundle:nil] forCellReuseIdentifier:@"CommentTableViewCell"];

    self.prototypeCell = [[NSBundle mainBundle] loadNibNamed:@"CommentTableViewCell" owner:self options:nil].firstObject;

    [self.tableView.header beginRefreshing];
}

- (void)requestDataWithSuccess:(PageTableRequestDataSuccessBlock)success failure:(PageTableRequestDataFailureBlock)failure {
    [ProtocolUtil getNewsCommentListWithID:self.newsModel.identifier pageIndex:@(self.pageIndex) pageCount:@(PageCount) success:^(id data, id identifier) {
        success(data);
    } failure:^(RKObjectRequestOperation *operation, NSError *error) {
        failure(error);
    }];
}

#pragma mark - Table view data source

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CommentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CommentTableViewCell" forIndexPath:indexPath];
    CommentModel *model = self.dataArray[indexPath.row];
    [cell setupCellWithCommentModel:model];
    return cell;
}

#pragma mark - Table view delegate

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 100;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CommentModel *model = self.dataArray[indexPath.row];
    return [self.prototypeCell cellHeightForCommentModel:model tableWidth:CGRectGetWidth(tableView.frame)];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


text:
module TeamFun
  require File.join( File.dirname(__FILE__), *%w{team_fun form_builder})
  require File.join( File.dirname(__FILE__), *%w{team_fun helpers})
end


text:
/**
 *     This code was auto-generated by a Codezu.
 *
 *     Changes to this file may cause incorrect behavior and will be lost if
 *     the code is regenerated.
 */
package com.mozu.api.contracts.appdev;

import org.joda.time.DateTime;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.joda.time.DateTime;

/**
 *	Mozu.AppDev.Contracts.ApplicationTransaction ApiType DOCUMENT_HERE
 */
@JsonIgnoreProperties(ignoreUnknown = true)
public class ApplicationTransaction implements Serializable
{
	// Default Serial Version UID
	private static final long serialVersionUID = 1L;

	/**
	 * Mozu.AppDev.Contracts.ApplicationTransaction applicationEntitlementId ApiTypeMember DOCUMENT_HERE
	 */
	protected Integer applicationEntitlementId;

	public Integer getApplicationEntitlementId() {
		return this.applicationEntitlementId;
	}

	public void setApplicationEntitlementId(Integer applicationEntitlementId) {
		this.applicationEntitlementId = applicationEntitlementId;
	}

	/**
	 * Mozu.AppDev.Contracts.ApplicationTransaction applicationId ApiTypeMember DOCUMENT_HERE
	 */
	protected Integer applicationId;

	public Integer getApplicationId() {
		return this.applicationId;
	}

	public void setApplicationId(Integer applicationId) {
		this.applicationId = applicationId;
	}

	/**
	 * Mozu.AppDev.Contracts.ApplicationTransaction applicationTransactionId ApiTypeMember DOCUMENT_HERE
	 */
	protected Integer applicationTransactionId;

	public Integer getApplicationTransactionId() {
		return this.applicationTransactionId;
	}

	public void setApplicationTransactionId(Integer applicationTransactionId) {
		this.applicationTransactionId = applicationTransactionId;
	}

	/**
	 * The three character ISO currency code for the monetary amount. For example, USD is used for US Dollars.
	 */
	protected String isoCurrencyCode;

	public String getIsoCurrencyCode() {
		return this.isoCurrencyCode;
	}

	public void setIsoCurrencyCode(String isoCurrencyCode) {
		this.isoCurrencyCode = isoCurrencyCode;
	}

	/**
	 * Language used for the entity. Currently, only "en-US" is supported.
	 */
	protected Integer localeCode;

	public Integer getLocaleCode() {
		return this.localeCode;
	}

	public void setLocaleCode(Integer localeCode) {
		this.localeCode = localeCode;
	}

	/**
	 * Mozu.AppDev.Contracts.ApplicationTransaction orderNumber ApiTypeMember DOCUMENT_HERE
	 */
	protected String orderNumber;

	public String getOrderNumber() {
		return this.orderNumber;
	}

	public void setOrderNumber(String orderNumber) {
		this.orderNumber = orderNumber;
	}

	/**
	 * Unique identifier for the site. This ID is used at all levels of a store, catalog, and tenant to associate objects to a site.
	 */
	protected Integer siteId;

	public Integer getSiteId() {
		return this.siteId;
	}

	public void setSiteId(Integer siteId) {
		this.siteId = siteId;
	}

	/**
	 * Unique identifier of the Mozu tenant.
	 */
	protected Integer tenantId;

	public Integer getTenantId() {
		return this.tenantId;
	}

	public void setTenantId(Integer tenantId) {
		this.tenantId = tenantId;
	}

	/**
	 * Mozu.AppDev.Contracts.ApplicationTransaction transactionDate ApiTypeMember DOCUMENT_HERE
	 */
	protected DateTime transactionDate;

	public DateTime getTransactionDate() {
		return this.transactionDate;
	}

	public void setTransactionDate(DateTime transactionDate) {
		this.transactionDate = transactionDate;
	}

	/**
	 * Mozu.AppDev.Contracts.ApplicationTransaction transactionPrice ApiTypeMember DOCUMENT_HERE
	 */
	protected Double transactionPrice;

	public Double getTransactionPrice() {
		return this.transactionPrice;
	}

	public void setTransactionPrice(Double transactionPrice) {
		this.transactionPrice = transactionPrice;
	}

	/**
	 * Mozu.AppDev.Contracts.ApplicationTransaction transactionTax ApiTypeMember DOCUMENT_HERE
	 */
	protected Double transactionTax;

	public Double getTransactionTax() {
		return this.transactionTax;
	}

	public void setTransactionTax(Double transactionTax) {
		this.transactionTax = transactionTax;
	}

	/**
	 * Mozu.AppDev.Contracts.ApplicationTransaction transactionTotal ApiTypeMember DOCUMENT_HERE
	 */
	protected Double transactionTotal;

	public Double getTransactionTotal() {
		return this.transactionTotal;
	}

	public void setTransactionTotal(Double transactionTotal) {
		this.transactionTotal = transactionTotal;
	}

}


text:
import cgi
import cgitb
cgitb.enable()

import os, sys
sys.path.extend(('../../','../../dispatch','../../langdet'))
from db2zmq_cleartext import DB_get_full_article
import pprint

import psycopg2, psycopg2.extras
psycopg2.extensions.register_type(psycopg2.extensions.UNICODE)

def htmlStr(x):
	if type(x)==unicode:
		x = x.encode('utf8','replace')
	else:
		x = str(x)

	assert type(x)==str
	if x.startswith('http://') and len(x)<300:
		return '%s' % (x.replace('&','&').replace('<','<').replace('"','"'), x)
	else:
		return x.replace('&','&').replace('<','<').replace('\n','
')

def resultTableToHtml(rows, columns=None, ignore_columns=[]):
	"""
	HTML display of DB results. If `columns` is omitted, it's autodetected
	`rows` should be a list of dicts.
	"""
	if not rows:
		return '(No rows)'

	columns = columns or sorted(rows[0].keys())
	columns = [c for c in columns if c not in ignore_columns]

	ret = '

' + ''.join('%s	' % c for c in columns) + '
'
	for row in rows:
		ret += '
' + ''.join('%s	' % htmlStr(row[c]) for c in columns) + '
'
	ret += '

\n'
	return ret

def articleDetail(articleHandle):
	# connect to DB
	conn = psycopg2.connect(database='news', host='maximus', user='mitjat', password='XXX_GITHUB_XXX')
	cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
	cur.execute("SET bytea_output TO 'escape'")
	res = ''

	# identify the article
	if articleHandle.isdigit():
		articleId = int(articleHandle)
	else:
		cur.execute("SELECT fa_id FROM feed_article_urls WHERE url_hash(%s)=url_hash(url) and %s=url LIMIT 1", (articleHandle,articleHandle))
		if cur.rowcount:
			articleId = cur.fetchone()[0]
		else:
			return 'URL not in the DB'
	res += '
Article %s
' % articleId

	# fetch what db2zmq sees
	zmq_data = DB_get_full_article(cur, articleId)
	res += '\n\n
zmq
' + '
'+pprint.pformat(zmq_data)+'
'

	# fetch raw results
	cur.execute("SELECT * FROM feed_article_meta WHERE id=%s", (articleId,))
	res += '\n\n
feed_article_meta
' + resultTableToHtml(cur.fetchall())

	cur.execute("SELECT * FROM feed_article WHERE id=%s", (articleId,))
	rows = cur.fetchall()
	res += '\n\n
feed_article
' + resultTableToHtml(rows)
	feedId = rows[0]['feedid']
	siteId = rows[0]['feedsiteid']

	cur.execute("SELECT * FROM feed WHERE id=%s", (feedId,))
	res += '\n\n
feed
' + resultTableToHtml(cur.fetchall())

	cur.execute("SELECT * FROM site WHERE id=%s", (siteId,))
	res += '\n\n
site
' + resultTableToHtml(cur.fetchall())

	cur.execute("SELECT * FROM processed_article WHERE feed_articleid=%s", (articleId,))
	rows = cur.fetchall()
	res += '\n\n
processed_article
' + resultTableToHtml(rows, ignore_columns=['content'])
	for (i,row) in enumerate(rows):
		res += 'content (row %d)
%s
' % (i, row['content'].encode('utf8','replace').replace('&','&').replace('<','<'))

	cur.execute("""SELECT story_id, ARRAY_AGG('
'||m.id||' - '||COALESCE(m.title,'(no title)')) AS story_articles FROM feed_article_googles g JOIN feed_article_meta m ON (g.feed_articleid=m.id) WHERE story_id=(SELECT story_id FROM feed_article_googles WHERE feed_articleid=%s) GROUP BY story_id;""", (articleId,))
	res += '\n\n
Google clusters/stories
'
	for row in cur:
		res += 'Story '+str(row['story_id'])+'
'+'\n'.join(row['story_articles'])+'
'

	cur.execute("SELECT * FROM article WHERE feed_articleid=%s", (articleId,))
	rows = cur.fetchall()
	res += '\n\n
article
' + resultTableToHtml(rows, ignore_columns=['content'])
	for (i,row) in enumerate(rows):
		res += 'content (row %d)
%r
' % (i, str(row['content']).replace('&','&').replace('<','<'))

	return res

header = """
<!DOCTYPE html>

<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>

"""

footer = """

"""

if __name__=='__main__':
	# parse request
	form = cgi.FieldStorage()
	articleHandle = form.getvalue('id')

	# print response
	print 'Content-type: text/html\n\n'

	print 'New query: ID or URL'
	print '<form target="" method="GET"><input name="id"><input type="submit"></form>'

	if articleHandle:
		print header + articleDetail(articleHandle) + footer
	else:
		print 'Gimme an id'


text:
require('babel/register');
module.exports = require('./main');

if (require.main === module) {
	module.exports();
}


text:
Template.Sea.onCreated(function () {
    var self = this;
    self.autorun(function () {
        self.subscribe('spp');
    });
});

Template.Sea.helpers({
    getSpp: function () {
        return Spp.find({appearDate: {$lt: new Date()}, disappearDate: {$gt: new Date()}});
    }
});


text:
/* STM32L476G-Eval board configuration */

#ifndef __CROS_EC_BOARD_H
#define __CROS_EC_BOARD_H

#ifdef CTS_MODULE
/* CTS tests are small. We can use smaller size to expedite flash time. */
#undef CONFIG_FLASH_SIZE_BYTES
#define CONFIG_FLASH_SIZE_BYTES 0x00040000 /* 256k */
#endif

/* Optional features */
#undef CONFIG_WATCHDOG_HELP
#undef CONFIG_LID_SWITCH

/* Console is on LPUART (PG7/8). Undef it to use USART1 (PB6/7). */
#define STM32L476G_EVAL_USE_LPUART_CONSOLE
#undef CONFIG_UART_CONSOLE

#ifdef STM32L476G_EVAL_USE_LPUART_CONSOLE
#define CONFIG_UART_CONSOLE 9
#define CONFIG_UART_TX_DMA_CH STM32_DMAC_CH14
#define CONFIG_UART_TX_DMA_PH 4
#else
#define CONFIG_UART_CONSOLE 1
#define CONFIG_UART_TX_DMA_CH STM32_DMAC_USART1_TX
#define CONFIG_UART_TX_DMA_PH 2
#endif

/* Optional features */

#ifdef CTS_MODULE_I2C
#define CONFIG_I2C
#define CONFIG_I2C_PERIPHERAL
#define CONFIG_HOSTCMD_I2C_SLAVE_ADDR 0x3c
#define I2C_PORT_EC STM32_I2C2_PORT
#endif

/*
 * Allow dangerous commands all the time, since we don't have a write protect
 * switch.
 */
#define CONFIG_SYSTEM_UNLOCKED

#ifndef __ASSEMBLER__

#undef CONFIG_FLASH_CROS
#undef CONFIG_FLASH_PHYSICAL

/* Timer selection */
#define TIM_CLOCK32 5

/* External clock speeds (8 MHz) */
#define STM32_HSE_CLOCK 8000000

/* PLL configuration. Freq = STM32_HSE_CLOCK * n/m/r */
#undef STM32_PLLM
#define STM32_PLLM 1
#undef STM32_PLLN
#define STM32_PLLN 10
#undef STM32_PLLR
#define STM32_PLLR 2

#include "gpio_signal.h"

#endif /* !__ASSEMBLER__ */
#endif /* __CROS_EC_BOARD_H */


text:
"""dj4 URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Add an import:  from blog import urls as blog_urls
    2. Add a URL to urlpatterns:  url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from learn import views as learn_views
from calc import views as calc_views

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^$', learn_views.index, name='home'),
    url(r'^add/$', learn_views.add, name='add'),

#    url(r'^add/', calc_views.add, name='add'),
#    url(r'^add3/', learn_views.add, name='add3'),
#    url(r'^home/', learn_views.home, name='home'),
#    url(r'^add2/(\d+)/(\d+)/$', calc_views.add2, name='add2'),
]


text:
title: Angular 2 Tutorial
name: Angular 2
alias:
  - angular2
  - angularjs
language:
  - Javascript
framework:
  - Angular 2
image: /media/platforms/angular.png
tags:
  - quickstart
snippets:
  dependencies: client-platforms/angular2/dependencies
  install: client-platforms/angular2/install
  observable: client-platforms/angular2/observable
  request: client-platforms/angular2/request
  router: client-platforms/angular2/router
  setup: client-platforms/angular2/setup
  system_map: client-platforms/angular2/system-map
  use: client-platforms/angular2/use
alias:
  - angular
---

## Angular 2 Tutorial

<%= include('../_includes/_package', {
  pkgRepo: 'auth0-angular2',
  pkgBranch: 'master',
  pkgPath: null,
  pkgFilePath: null,
  pkgType: 'js' + account.clientParam
}) %>

**If you have an existing application, follow the steps below.**

${include('./\_callback')}

### 1. Add the Auth0 Scripts and Install angular2-jwt

Install **angular2-jwt** with **npm**.

${snippet(meta.snippets.install)}

Add **Lock** in your `index.html` file and set the viewport.

${snippet(meta.snippets.dependencies)}

### 2. Set Up SystemJS Configuration to Map angular2-jwt

If you're using SystemJS, set up `System.config` to map **angular-jwt** so that it can be imported.

${snippet(meta.snippets.system_map)}

### 2.1 Using Webpack

**If you are using Webpack, please see the [auth0-angular2 Webpack example](https://github.com/auth0/auth0-angular2/tree/master/webpack) for configuration.**

### 3. Import Dependencies

To set up a simple component, you'll need some standard Angular 2 imports, as well as the `AuthHttp` class and `tokenNotExpired` function from **angular2-jwt**.

${snippet(meta.snippets.setup)}

### 4. Implement Login and Logout

To implement login, create a new `Auth0Lock` instance in your component. In this example, login is implemented in the app's root component, but it could also be placed in a child component.

${snippet(meta.snippets.use)}

${browser}

In the `login` method, call `lock.show` to display the login widget. On a successful login, you can save the user's profile object (as a string) and token in local storage.

To log the user out, simply remove the profile and token from local storage.

You can use the `tokenNotExpired` function in the `loggedIn` method to conditionally show and hide the **Login** and **Logout** buttons.

__Note:__ There are multiple ways of implementing a login. The example above displays the Login Widget. However you may implement your own login UI by changing the line `<script src="//cdn.auth0.com/js/lock-7.5.min.js"></script>` to `<script src="//cdn.auth0.com/w2/auth0-6.7.js"></script>`.

### 5. Make an Authenticated HTTP Request

The `AuthHttp` class is used to make authenticated HTTP requests. `AuthHttp` uses Angular 2's **Http** class but includes the `Authorization` header for you on requests.

${snippet(meta.snippets.request)}

Inject the `AuthHttp` class as `authHttp`. This example uses the `get` method to make an authenticated `GET` request. `AuthHttp` supports all HTTP verbs, so you can just as easily do `POST`, `PUT`, and `DELETE` requests. You can provide an object as the second argument to the call if you want to include a body.

### 6. Limit Certain Routes to Authenticated Users

Although data from the API will be protected and require a valid JWT to access, users that aren't authenticated will be able to get to any route by default. You can use the `@CanActivate` life-cycle hook from Angular 2's router to limit navigation on certain routes to only those with a non-expired JWT.

${snippet(meta.snippets.router)}

Use the `tokenNotExpired` function within the `@CanActivate` life-cycle hook to determine if the user can navigate to the private route. If the token isn't expired, the function will return `true` and navigation will be permitted.

### 7. All done!

You have completed the implementation of Login and Signup with Auth0 and Angular 2.

### Optional: Use JWT as an Observable

The `AuthHttp` class sets a property, `tokenStream`, as an observable stream from the user's JWT. This stream can be used with other streams and can be combined to make authenticated requests. This can be used as an alternative to the explicit methods in the `AuthHttp` class.

${snippet(meta.snippets.observable)}


text:
package aQute.bnd.compatibility;

import java.io.IOException;
import java.util.EnumSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

public class Scope {
	final Map<String,Scope>	children	= new LinkedHashMap<>();

	// class: slashed name
	// field: name ":" typed
	// constructor: ":(" typed* ")" typed
	// method: name ":(" typed* ")" typed
	final String			name;

	Access					access;
	Kind					kind;
	Scope					enclosing;
	Scope					declaring;
	GenericParameter		typeVars[];
	Map<String,String[]>	name2bounds;

	// class: super
	// field: type
	// constructor: void
	// method: return
	GenericType				base;

	// class: interfaces
	// constructor: args
	// method: args
	GenericType[]			parameters;

	// constructor: exceptions
	// method: exceptions
	GenericType[]			exceptions;

	// class: super interfaces*
	// field: type
	// constructor: void arguments*
	// method: return arguments*

	public Scope(Access access, Kind kind, String name) {
		this.access = access;
		this.kind = kind;
		this.name = name;
	}

	Scope getScope(String name) {
		Scope s = children.get(name);
		if (s != null)
			return s;

		s = new Scope(Access.UNKNOWN, Kind.UNKNOWN, name);
		children.put(name, s);
		s.declaring = this;
		return s;
	}

	public void setParameterTypes(GenericType[] convert) {
		this.parameters = convert;
	}

	public void setExceptionTypes(GenericType[] convert) {
		this.exceptions = convert;
	}

	public void setBase(GenericType typeSignature) {
		base = typeSignature;
	}

	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();

		if (typeVars != null && typeVars.length != 0) {
			sb.append("<");
			for (GenericParameter v : typeVars) {
				sb.append(v);
			}
			sb.append(">");
		}
		sb.append(access.toString());
		sb.append(" ");
		sb.append(kind.toString());
		sb.append(" ");
		sb.append(name);
		return sb.toString();
	}

	public void report(Appendable a, int indent) throws IOException {
		for (int i = 0; i < indent; i++)
			a.append("  ");
		a.append(toString());
		a.append("\n");
		for (Scope s : children.values())
			s.report(a, indent + 1);
	}

	public void add(Scope m) {
		children.put(m.name, m);

	}

	public void setDeclaring(Scope declaring) {
		this.declaring = declaring;
	}

	public void setAccess(Access access) {
		this.access = access;
	}

	public void setEnclosing(Scope enclosing) {
		this.enclosing = enclosing;
		if (this.enclosing != null) {
			this.enclosing.add(this);
		}
	}

	public boolean isTop() {
		return enclosing == null;
	}

	public void setKind(Kind kind) {
		this.kind = kind;
	}

	static public String classIdentity(String name2) {
		return name2.replace('.', '/');
	}

	static public String methodIdentity(String name, String descriptor) {
		return name + ":" + descriptor;
	}

	static public String constructorIdentity(String descriptor) {
		return ":" + descriptor;
	}

	static public String fieldIdentity(String name, String descriptor) {
		return name + ":" + descriptor;
	}

	public void cleanRoot() {
		children.entrySet().removeIf(entry -> !entry.getValue().isTop());
	}

	public void prune(EnumSet<Access> level) {
		Iterator<Map.Entry<String,Scope>> i = children.entrySet().iterator();
		while (i.hasNext()) {
			Map.Entry<String,Scope> entry = i.next();
			if (!level.contains(entry.getValue().access))
				i.remove();
			else
				entry.getValue().prune(level);
		}
	}

	public void setGenericParameter(GenericParameter[] typeVars) {
		this.typeVars = typeVars;
	}

}


text:
ONE_LOCATION = ENV["ONE_LOCATION"]

if !ONE_LOCATION
    RUBY_LIB_LOCATION = "/usr/lib/one/ruby"
    MAD_LOCATION      = "/usr/lib/one/mads"
    ETC_LOCATION      = "/etc/one/"
else
    RUBY_LIB_LOCATION = ONE_LOCATION + "/lib/ruby"
    MAD_LOCATION      = ONE_LOCATION + "/lib/mads"
    ETC_LOCATION      = ONE_LOCATION + "/etc/"
end

$: << RUBY_LIB_LOCATION
$: << MAD_LOCATION

require "VirtualMachineDriver"
require 'one_vnm'
require 'one_tm'
require 'getoptlong'
require 'ssh_stream'
require 'rexml/document'

require 'pp'

class VmmAction
    # List of xpaths required by the VNM driver actions
    XPATH_LIST = %w(
        ID DEPLOY_ID
        TEMPLATE/NIC
        TEMPLATE/SECURITY_GROUP_RULE
        HISTORY_RECORDS/HISTORY/HOSTNAME
    )

    attr_reader :data

    # Initialize a VmmAction object
    # @param[OpenNebula::ExecDriver] Driver to be used for the actions
    # @param[String] Id of the VM
    # @param[String] name of the actions as described in the VMM protocol
    # @param[xml_data] data sent from OpenNebula core
    def initialize(driver, id, action, xml_data)
        # Initialize object with xml data
        @vmm = driver
        @id  = id

        @main_action = action
        @xml_data    = @vmm.decode(xml_data)

        @data = Hash.new

        get_data(:host)
        get_data(:net_drv)
        get_data(:deploy_id)
        get_data(:checkpoint_file)

        get_data(:local_dfile, :LOCAL_DEPLOYMENT_FILE)
        get_data(:remote_dfile, :REMOTE_DEPLOYMENT_FILE)

        # For migration
        get_data(:dest_host, :MIGR_HOST)
        get_data(:dest_driver, :MIGR_NET_DRV)

        # For disk hotplugging
        get_data(:disk_target_path)
        get_data(:tm_command)

        # VM template
        vm_template = @xml_data.elements['VM'].to_s
        @data[:vm]  = Base64.encode64(vm_template).delete("\n")

        # VM data for VNM
        vm_template_xml = REXML::Document.new(vm_template).root
        vm_vnm_xml = REXML::Document.new('<VM></VM>').root

        XPATH_LIST.each do |xpath|
            elements = vm_template_xml.elements.each(xpath) do |element|
                add_element_to_path(vm_vnm_xml, element, xpath)
            end
        end

        # Initialize streams and vnm
        @ssh_src = @vmm.get_ssh_stream(action, @data[:host], @id)
        @vnm_src = VirtualNetworkDriver.new(@data[:net_drv],
                            :local_actions  => @vmm.options[:local_actions],
                            :message        => vm_vnm_xml.to_s,
                            :ssh_stream     => @ssh_src)

        if @data[:dest_host] and !@data[:dest_host].empty?
            @ssh_dst = @vmm.get_ssh_stream(action, @data[:dest_host], @id)
            @vnm_dst = VirtualNetworkDriver.new(@data[:dest_driver],
                            :local_actions  => @vmm.options[:local_actions],
                            :message        => vm_vnm_xml.to_s,
                            :ssh_stream     => @ssh_dst)
        end

        @tm = TransferManagerDriver.new(nil)
    end

    #Execute a set of steps defined with
    #  - :driver :vmm or :vnm to execute the step
    #  - :action for the step
    #  - :parameters command line paremeters for the action
    #  - :destination use next host
    #  - :fail_action steps to be executed if steps fail
    #  - :stdin for the action
    #  @param [Array] of steps
    def run(steps, info_on_success = nil)
        result = execute_steps(steps)

        @ssh_src.close if @ssh_src
        @ssh_dst.close if @ssh_dst

        #Prepare the info for the OpenNebula core
        if DriverExecHelper.failed?(result)
            info = @data[:failed_info]
        else
            info = @data["#{@main_action.to_s}_info".to_sym]
        end

        @vmm.send_message(VirtualMachineDriver::ACTION[@main_action],
                          result, @id, info)
    end

    private

    DRIVER_NAMES = {
        :vmm => "virtualization driver",
        :vnm => "network driver",
        :tm => "transfer manager driver"
    }

    # Executes a set of steps. If one step fails any recover action is performed
    # and the step execution breaks.
    # @param [Array] array of steps to be executed
    # @return [String, Hash] "SUCCESS/FAILURE" for the step set, and
    # information associated to each step (by :<action>_info). In case of
    # failure information is also in [:failed_info]
    def execute_steps(steps)
        result = DriverExecHelper.const_get(:RESULT)[:failure]

        steps.each do |step|
            # Execute Step
            case step[:driver]
            when :vmm
                if step[:destination]
                    host = @data[:dest_host]
                    ssh  = @ssh_dst
                else
                    host = @data[:host]
                    ssh  = @ssh_src
                end

                result, info = @vmm.do_action(get_parameters(step[:parameters]),
                                              @id,
                                              host,
                                              step[:action],
                                              :ssh_stream => ssh,
                                              :respond => false,
                                              :stdin => step[:stdin])
            when :vnm
                if step[:destination]
                    vnm = @vnm_dst
                else
                    vnm = @vnm_src
                end

                result, info = vnm.do_action(@id, step[:action],
                            :parameters => get_parameters(step[:parameters]))
            when :tm
                result, info = @tm.do_transfer_action(@id, step[:parameters])

            else
                result = DriverExecHelper.const_get(:RESULT)[:failure]
                info   = "No driver in #{step[:action]}"
            end

            # Save the step info
            @data["#{step[:action]}_info".to_sym] = info.strip

            # Roll back steps, store failed info and break steps
            if DriverExecHelper.failed?(result)
                execute_steps(step[:fail_actions]) if step[:fail_actions]
                @data[:failed_info] = info

                @vmm.log(@id,
                         "Failed to execute #{DRIVER_NAMES[step[:driver]]} " \
                         "operation: #{step[:action]}.")

                if step[:no_fail]
                    result = DriverExecHelper::RESULT[:success]
                else
                    break
                end
            else
                @vmm.log(@id,
                         "Successfully execute #{DRIVER_NAMES[step[:driver]]} " \
                         "operation: #{step[:action]}.")
            end
        end

        return result
    end

    # Prepare the parameters for the action step generating a blank separated
    # list of command arguments
    # @param [Hash] an action step
    def get_parameters(step_params)
        parameters = step_params || []

        parameters.map do |param|
            if Symbol===param
               "\'#{@data[param].to_s}\'"
            else
               "\'#{param}\'"
            end
        end.join(' ')
    end

    # Extracts data from the XML argument of the VMM action
    # @param [Symbol] corresponding to a XML element
    # @param [String] an xpath for the XML element
    # @return [String] the element value
    def get_data(name, xml_path=nil)
        if xml_path
            path=xml_path.to_s
        else
            path=name.to_s.upcase
        end

        if (elem = @xml_data.elements[path])
            @data[name]=elem.text
        end
    end

    # Adds a REXML node to a specific xpath
    #
    # @param [REXML::Element] xml document to add to
    # @param [REXML::Element] element to add
    # @param [String] path where the element is inserted in the xml document
    # @return [REXML::Element]
    def add_element_to_path(xml, element, path)
        root = xml
        path.split('/')[0..-2].each do |path_element|
            xml = xml.add_element(path_element) if path_element
        end
        xml.add_element(element)
        root
    end
end

# The main class for the Sh driver
class ExecDriver < VirtualMachineDriver
    attr_reader :options

    # Initializes the VMM driver
    # @param [String] hypervisor name identifies the plugin
    # @param [OpenNebulaDriver::options]
    def initialize(hypervisor, options={})
        @options={
            :threaded => true
        }.merge!(options)

        if options[:shell]
            @shell=options[:shell]
        else
            @shell='bash'
        end

        super("vmm/#{hypervisor}", @options)

        @hypervisor  = hypervisor
    end

    # Creates an SshStream to execute commands on the target host
    # @param[String] the hostname of the host
    # @param[String] id of the VM to log messages
    # @return [SshStreamCommand]
    def get_ssh_stream(aname, host, id)
        SshStreamCommand.new(host,
                            @remote_scripts_base_path,
                            log_method(id), nil, @shell)
    end

    #---------------------------------------------------------------------------
    #  Virtual Machine Manager Protocol Actions
    #---------------------------------------------------------------------------
    #
    # DEPLOY action, sends the deployment file to remote host
    #
    def deploy(id, drv_message)
        action = VmmAction.new(self, id, :deploy, drv_message)

        # ----------------------------------------------------------------------
        #  Initialization of deployment data
        # ----------------------------------------------------------------------
        local_dfile=action.data[:local_dfile]

        if !local_dfile || File.zero?(local_dfile)
            send_message(ACTION[:deploy],RESULT[:failure],id,
                "Cannot open deployment file #{local_dfile}")
            return
        end

        domain = File.read(local_dfile)

        if action_is_local?(:deploy)
            dfile = action.data[:local_dfile]
        else
            dfile = action.data[:remote_dfile]
        end

        # ----------------------------------------------------------------------
        #  Deployment Steps
        # ----------------------------------------------------------------------

        steps=[
            # Execute pre-boot networking setup
            {
                :driver   => :vnm,
                :action   => :pre
            },
            # Boot the Virtual Machine
            {
                :driver       => :vmm,
                :action       => :deploy,
                :parameters   => [dfile, :host],
                :stdin        => domain,
            },
            # Execute post-boot networking setup
            {
                :driver       => :vnm,
                :action       => :post,
                :parameters   => [:deploy_info],
                :fail_actions => [
                    {
                        :driver     => :vmm,
                        :action     => :cancel,
                        :parameters => [:deploy_info, :host]
                    }
                ]
            }
        ]

        action.run(steps)
    end

    #
    # SHUTDOWN action, graceful shutdown and network clean up
    #
    def shutdown(id, drv_message)

        action = VmmAction.new(self, id, :shutdown, drv_message)

        steps=[
            # Shutdown the Virtual Machine
            {
                :driver     => :vmm,
                :action     => :shutdown,
                :parameters => [:deploy_id, :host]
            },
            # Execute networking clean up operations
            {
                :driver   => :vnm,
                :action   => :clean
            }
        ]

        action.run(steps)
    end

    #
    # CANCEL action, destroys a VM and network clean up
    #
    def cancel(id, drv_message)
        action = VmmAction.new(self, id, :cancel, drv_message)

        steps=[
            # Cancel the Virtual Machine
            {
                :driver     => :vmm,
                :action     => :cancel,
                :parameters => [:deploy_id, :host]
            },
            # Execute networking clean up operations
            {
                :driver   => :vnm,
                :action   => :clean
            }
        ]

        action.run(steps)
    end

    #
    # SAVE action, stops the VM and saves its state, network is cleaned up
    #
    def save(id, drv_message)
        action = VmmAction.new(self, id, :save, drv_message)

        steps=[
            # Save the Virtual Machine state
            {
                :driver     => :vmm,
                :action     => :save,
                :parameters => [:deploy_id, :checkpoint_file, :host]
            },
            # Execute networking clean up operations
            {
                :driver   => :vnm,
                :action   => :clean
            }
        ]

        action.run(steps)
    end

    #
    # RESTORE action, restore a VM from a previous state, and restores network
    #
    def restore(id, drv_message)
        action=VmmAction.new(self, id, :restore, drv_message)

        steps=[
            # Execute pre-boot networking setup
            {
                :driver     => :vnm,
                :action     => :pre
            },
            # Restore the Virtual Machine from checkpoint
            {
                :driver     => :vmm,
                :action     => :restore,
                :parameters => [:checkpoint_file, :host, :deploy_id]
            },
            # Execute post-boot networking setup
            {
                :driver       => :vnm,
                :action       => :post,
                :parameters   => [:deploy_id],
                :fail_actions => [
                    {
                        :driver     => :vmm,
                        :action     => :cancel,
                        :parameters => [:deploy_id, :host]
                    }
                ],
            }
        ]

        action.run(steps)
    end

    #
    # MIGRATE (live) action, migrates a VM to another host creating network
    #
    def migrate(id, drv_message)
        action = VmmAction.new(self, id, :migrate, drv_message)
        pre    = "PRE"
        post   = "POST"
        failed = "FAIL"

        pre  << action.data[:tm_command] << " " << action.data[:vm]
        post << action.data[:tm_command] << " " << action.data[:vm]
        failed << action.data[:tm_command] << " " << action.data[:vm]

        steps=[
            # Execute a pre-migrate TM setup
            {
                :driver     => :tm,
                :action     => :tm_premigrate,
                :parameters => pre.split
            },
            # Execute pre-boot networking setup on migrating host
            {
                :driver      => :vnm,
                :action      => :pre,
                :destination => true
            },
            # Migrate the Virtual Machine
            {
                :driver     => :vmm,
                :action     => :migrate,
                :parameters => [:deploy_id, :dest_host, :host],
                :fail_actions => [
                    {
                        :driver     => :tm,
                        :action     => :tm_failmigrate,
                        :parameters => failed.split,
                        :no_fail    => true
                    }
                ]
            },
            # Execute networking clean up operations
            # NOTE: VM is now in the new host. If we fail from now on, oned will
            # assume that the VM is in the previous host but it is in fact
            # migrated. Log errors will be shown in vm.log
            {
                :driver       => :vnm,
                :action       => :clean,
                :no_fail      => true
            },
            # Execute post-boot networking setup on migrating host
            {
                :driver       => :vnm,
                :action       => :post,
                :parameters   => [:deploy_id],
                :destination  => :true,
                :no_fail      => true
            },
            {
                :driver     => :tm,
                :action     => :tm_postmigrate,
                :parameters => post.split,
                :no_fail    => true
            },
        ]

        action.run(steps)
    end

    #
    # POLL action, gets information of a VM
    #
    def poll(id, drv_message)
        data      = decode(drv_message)
        host      = data.elements['HOST'].text
        deploy_id = data.elements['DEPLOY_ID'].text

        do_action("#{deploy_id} #{host}", id, host, ACTION[:poll])
    end

    #
    # REBOOT action, reboots a running VM
    #
    def reboot(id, drv_message)
        data      = decode(drv_message)
        host      = data.elements['HOST'].text
        deploy_id = data.elements['DEPLOY_ID'].text

        do_action("#{deploy_id} #{host}", id, host, ACTION[:reboot])
    end

    #
    # RESET action, resets a running VM
    #
    def reset(id, drv_message)
        data      = decode(drv_message)
        host      = data.elements['HOST'].text
        deploy_id = data.elements['DEPLOY_ID'].text

        do_action("#{deploy_id} #{host}", id, host, ACTION[:reset])
    end

    #
    # ATTACHDISK action, attaches a disk to a running VM
    #
    def attach_disk(id, drv_message)
        action   = ACTION[:attach_disk]
        xml_data = decode(drv_message)

        tm_command = ensure_xpath(xml_data, id, action, 'TM_COMMAND') || return
        tm_rollback= xml_data.elements['TM_COMMAND_ROLLBACK'].text.strip

        target_xpath = "VM/TEMPLATE/DISK[ATTACH='YES']/TARGET"
        target     = ensure_xpath(xml_data, id, action, target_xpath) || return

        target_index = target.downcase[-1..-1].unpack('c').first - 97

        action = VmmAction.new(self, id, :attach_disk, drv_message)

        # Bug #1355, argument character limitation in ESX
        # Message not used in vmware anyway
        if @hypervisor == "vmware"
            drv_message = "drv_message"
        end

        steps = [
            # Perform a PROLOG on the disk
            {
                :driver     => :tm,
                :action     => :tm_attach,
                :parameters => tm_command.split
            },
            # Run the attach vmm script
            {
                :driver       => :vmm,
                :action       => :attach_disk,
                :parameters   => [
                        :deploy_id,
                        :disk_target_path,
                        target,
                        target_index,
                        drv_message
                ],
                :fail_actions => [
                    {
                        :driver     => :tm,
                        :action     => :tm_detach,
                        :parameters => tm_rollback.split
                    }
                ]
            }
        ]

        action.run(steps)
    end

    #
    # DETACHDISK action, attaches a disk to a running VM
    #
    def detach_disk(id, drv_message)
        action   = ACTION[:detach_disk]
        xml_data = decode(drv_message)

        tm_command = ensure_xpath(xml_data, id, action, 'TM_COMMAND') || return

        target_xpath = "VM/TEMPLATE/DISK[ATTACH='YES']/TARGET"
        target     = ensure_xpath(xml_data, id, action, target_xpath) || return

        target_index = target.downcase[-1..-1].unpack('c').first - 97

        action = VmmAction.new(self, id, :detach_disk, drv_message)

        steps = [
            # Run the detach vmm script
            {
                :driver       => :vmm,
                :action       => :detach_disk,
                :parameters   => [
                        :deploy_id,
                        :disk_target_path,
                        target,
                        target_index
                ]
            },
            # Perform an EPILOG on the disk
            {
                :driver     => :tm,
                :action     => :tm_detach,
                :parameters => tm_command.split
            }
        ]

        action.run(steps)
    end

    #
    # SNAPSHOTCREATE action, creates a new system snapshot
    #
    def snapshot_create(id, drv_message)
        xml_data = decode(drv_message)

        host      = xml_data.elements['HOST'].text
        deploy_id = xml_data.elements['DEPLOY_ID'].text

        snap_id_xpath = "VM/TEMPLATE/SNAPSHOT[ACTIVE='YES']/SNAPSHOT_ID"
        snap_id       = xml_data.elements[snap_id_xpath].text.to_i

        do_action("#{deploy_id} #{snap_id}",
                    id,
                    host,
                    ACTION[:snapshot_create],
                    :script_name => "snapshot_create")
    end

    #
    # SNAPSHOTREVERT action, reverts to a system snapshot
    #
    def snapshot_revert(id, drv_message)
        xml_data = decode(drv_message)

        host      = xml_data.elements['HOST'].text
        deploy_id = xml_data.elements['DEPLOY_ID'].text

        snap_id_xpath = "VM/TEMPLATE/SNAPSHOT[ACTIVE='YES']/HYPERVISOR_ID"
        snapshot_name = xml_data.elements[snap_id_xpath].text

        do_action("#{deploy_id} #{snapshot_name}",
                    id,
                    host,
                    ACTION[:snapshot_revert],
                    :script_name => "snapshot_revert")
    end

    #
    # SNAPSHOTDELETE action, deletes a system snapshot
    #
    def snapshot_delete(id, drv_message)
        xml_data = decode(drv_message)

        host      = xml_data.elements['HOST'].text
        deploy_id = xml_data.elements['DEPLOY_ID'].text

        snap_id_xpath = "VM/TEMPLATE/SNAPSHOT[ACTIVE='YES']/HYPERVISOR_ID"
        snapshot_name = xml_data.elements[snap_id_xpath].text

        do_action("#{deploy_id} #{snapshot_name}",
                    id,
                    host,
                    ACTION[:snapshot_delete],
                    :script_name => "snapshot_delete")
    end

    #
    # CLEANUP action, frees resources allocated in a host: VM and disk images
    #
    def cleanup(id, drv_message)
        xml_data = decode(drv_message)

        tm_command = xml_data.elements['TM_COMMAND'].text
        mhost      = xml_data.elements['MIGR_HOST'].text
        deploy_id  = xml_data.elements['DEPLOY_ID'].text

        action = VmmAction.new(self, id, :cleanup, drv_message)
        steps  = Array.new

        # Cancel the VM at host (only if we have a valid deploy-id)
        if deploy_id && !deploy_id.empty?
            steps <<
            {
                :driver     => :vmm,
                :action     => :cancel,
                :parameters => [:deploy_id, :host],
                :no_fail    => true
            }
            steps <<
            {
                :driver  => :vnm,
                :action  => :clean,
                :no_fail => true
            }
        end

        # Cancel the VM at the previous host (in case of migration)
        if mhost && !mhost.empty?
            steps <<
            {
                :driver      => :vmm,
                :action      => :cancel,
                :parameters  => [:deploy_id, :dest_host],
                :destination => true,
                :no_fail     => true
            }
            steps <<
            {
                :driver  => :vnm,
                :action  => :clean,
                :destination => true,
                :no_fail => true
            }
        end

        # Cleans VM disk images and directory
        tm_command.each_line { |tc|
            tc.strip!

            steps <<
            {
                :driver     => :tm,
                :action     => :tm_delete,
                :parameters => tc.split,
                :no_fail    => true
            } if !tc.empty?
        } if tm_command

        action.run(steps)
    end

    #
    #  ATTACHNIC action to attach a new nic interface
    #
    def attach_nic(id, drv_message)
        xml_data = decode(drv_message)

        begin
            source = xml_data.elements["VM/TEMPLATE/NIC[ATTACH='YES']/BRIDGE"]
            mac    = xml_data.elements["VM/TEMPLATE/NIC[ATTACH='YES']/MAC"]

            source = source.text.strip
            mac    = mac.text.strip
        rescue
            send_message(action, RESULT[:failure], id,
                "Error in #{ACTION[:attach_nic]}, BRIDGE and MAC needed in NIC")
            return
        end

        model = xml_data.elements["VM/TEMPLATE/NIC[ATTACH='YES']/MODEL"]

        model = model.text if !model.nil?
        model = model.strip if !model.nil?
        model = "-" if model.nil?

        net_drv = xml_data.elements["NET_DRV"]

        net_drv = net_drv.text if !net_drv.nil?
        net_drv = net_drv.strip if !net_drv.nil?
        net_drv = "-" if net_drv.nil?

        action = VmmAction.new(self, id, :attach_nic, drv_message)

        steps=[
            # Execute pre-attach networking setup
            {
                :driver   => :vnm,
                :action   => :pre
            },
            # Attach the new NIC
            {
                :driver     => :vmm,
                :action     => :attach_nic,
                :parameters => [:deploy_id, mac, source, model, net_drv]
            },
            # Execute post-boot networking setup
            {
                :driver       => :vnm,
                :action       => :post,
                :parameters   => [:deploy_id],
                :fail_actions => [
                    {
                        :driver     => :vmm,
                        :action     => :detach_nic,
                        :parameters => [:deploy_id, mac]
                    }
                ]
            }
        ]

        action.run(steps)
    end

    #
    #  DETACHNIC action to detach a nic interface
    #
    def detach_nic(id, drv_message)
        xml_data = decode(drv_message)

        begin
            mac = xml_data.elements["VM/TEMPLATE/NIC[ATTACH='YES']/MAC"]
            mac = mac.text.strip
        rescue
            send_message(action, RESULT[:failure], id,
                "Error in #{ACTION[:detach_nic]}, MAC needed in NIC")
            return
        end

        action = VmmAction.new(self, id, :detach_nic, drv_message)

        steps=[
            # Detach the NIC
            {
                :driver     => :vmm,
                :action     => :detach_nic,
                :parameters => [:deploy_id, mac]
            },
            # Clean networking setup
            {
                :driver       => :vnm,
                :action       => :clean
            }
        ]

        action.run(steps)
    end

    #
    # DISKSNAPSHOTCREATE action, takes a snapshot of a disk
    #
    def disk_snapshot_create(id, drv_message)
        action   = ACTION[:disk_snapshot_create]
        xml_data = decode(drv_message)

        tm_command = ensure_xpath(xml_data, id, action, 'TM_COMMAND') || return
        tm_rollback= xml_data.elements['TM_COMMAND_ROLLBACK'].text.strip

        target_xpath = "VM/TEMPLATE/DISK[DISK_SNAPSHOT_ACTIVE='YES']/TARGET"
        target       = ensure_xpath(xml_data, id, action, target_xpath) ||return

        target_index = target.downcase[-1..-1].unpack('c').first - 97

        if @options[:detach_snap]
          disk   = xml_data.elements[target_xpath].parent
          attach = REXML::Element.new('ATTACH')

          attach.add_text('YES')
          disk.add(attach)

          drv_message = Base64.encode64(xml_data.to_s)
        end

        action = VmmAction.new(self, id, :disk_snapshot_create, drv_message)

        vmm_driver_path = 'VM/HISTORY_RECORDS/HISTORY/VMMMAD'
        tm_driver_path = "VM/TEMPLATE/DISK[DISK_SNAPSHOT_ACTIVE='YES']/TM_MAD"

        vmm_driver = ensure_xpath(xml_data, id, action, vmm_driver_path) ||
            return
        tm_driver = ensure_xpath(xml_data, id, action, tm_driver_path) ||
            return

        # live_snapshots option is an array of VM and TM pairs
        # For example "kvm-qcow2". If found then only TM action is called.
        # Extra actions (suspend or attach) will be skipped
        live_snapshot = @options[:live_snapshots].include? "#{vmm_driver}-#{tm_driver}"

        if @options[:detach_snap]
          pre_action = :detach_disk
          pre_params = [:deploy_id, :disk_target_path, target, target_index]

          post_action = :attach_disk
          post_params = [:deploy_id, :disk_target_path, target, target_index,
                         drv_message]
        else
          pre_action = :save
          pre_params = [:deploy_id, :checkpoint_file, :host]

          post_action = :restore
          post_params = [:checkpoint_file, :host, :deploy_id]
        end

        steps = []

        if !live_snapshot
            # Save VM state / detach the disk
            steps << {
                :driver     => :vmm,
                :action     => pre_action,
                :parameters => pre_params
            }
        end

        # Do the snapshot
        steps << {
            :driver     => :tm,
            :action     => :tm_snap_create,
            :parameters => tm_command.split,
            :no_fail    => true
        }

        if !live_snapshot
            # Restore VM / attach the disk
            steps << {
                :driver     => :vmm,
                :action     => post_action,
                :parameters => post_params,
                :fail_actions => [
                    {
                        :driver     => :tm,
                        :action     => :tm_snap_delete,
                        :parameters => tm_rollback.split
                    }
                ]
            }
        end

        action.run(steps)
    end

    #
    # DISKSNAPSHOTREVERT action, takes a snapshot of a disk
    #
    def disk_snapshot_revert(id, drv_message)
        action   = ACTION[:disk_snapshot_revert]
        xml_data = decode(drv_message)

        tm_command = ensure_xpath(xml_data, id, action, 'TM_COMMAND') || return

        target_xpath = "VM/TEMPLATE/DISK[DISK_SNAPSHOT_ACTIVE='YES']/TARGET"
        target       = ensure_xpath(xml_data, id, action, target_xpath) ||return

        target_index = target.downcase[-1..-1].unpack('c').first - 97

        if @options[:detach_snap]
            disk   = xml_data.elements[target_xpath].parent
            attach = REXML::Element.new('ATTACH')

            attach.add_text('YES')
            disk.add(attach)

            drv_message = Base64.encode64(xml_data.to_s)
        end

        action = VmmAction.new(self, id, :disk_snapshot_revert, drv_message)

        if @options[:detach_snap]
          pre_action = :detach_disk
          pre_params = [:deploy_id, :disk_target_path, target, target_index]

          post_action = :attach_disk
          post_params = [:deploy_id, :disk_target_path, target, target_index,
                         drv_message]
        else
          pre_action = :save
          pre_params = [:deploy_id, :checkpoint_file, :host]

          post_action = :restore
          post_params = [:checkpoint_file, :host, :deploy_id]
        end

        steps = [
            # Save VM state / detach the disk
            {
                :driver     => :vmm,
                :action     => pre_action,
                :parameters => pre_params
            },
            # Do the snapshot
            {
                :driver     => :tm,
                :action     => :tm_snap_revert,
                :parameters => tm_command.split,
                :no_fail    => true,
            },
            # Restore VM / attach the disk
            {
                :driver     => :vmm,
                :action     => post_action,
                :parameters => post_params
            }
        ]

        action.run(steps)
    end
private

    def ensure_xpath(xml_data, id, action, xpath)
        begin
            value = xml_data.elements[xpath].text.strip
            raise if value.empty?
            value
        rescue
            send_message(action, RESULT[:failure], id,
                "Cannot perform #{action}, expecting #{xpath}")
            nil
        end
    end

end

################################################################################
#
# Virtual Machine Manager Execution Driver - Main Program
#
################################################################################

opts = GetoptLong.new(
    [ '--retries',        '-r', GetoptLong::OPTIONAL_ARGUMENT ],
    [ '--threads',        '-t', GetoptLong::OPTIONAL_ARGUMENT ],
    [ '--local',          '-l', GetoptLong::REQUIRED_ARGUMENT ],
    [ '--shell',          '-s', GetoptLong::REQUIRED_ARGUMENT ],
    [ '--parallel',       '-p', GetoptLong::NO_ARGUMENT ],
    [ '--detach-snap',    '-d', GetoptLong::NO_ARGUMENT ],
    [ '--live-snapshots', '-i', GetoptLong::REQUIRED_ARGUMENT ]
)

hypervisor    = ''
retries       = 0
threads       = 15
shell         = 'bash'
local_actions = {}
single_host   = true
detach_snap   = false
live_snapshots= ['kvm-qcow2']

begin
    opts.each do |opt, arg|
        case opt
            when '--retries'
                retries   = arg.to_i
            when '--threads'
                threads   = arg.to_i
            when '--local'
                local_actions=OpenNebulaDriver.parse_actions_list(arg)
            when '--shell'
                shell   = arg
            when '--parallel'
                single_host = false
            when '--detach-snap'
                detach_snap = true
            when '--live-snapshots'
                live_snapshots = arg.split(',')
        end
    end
rescue Exception => e
    exit(-1)
end

if ARGV.length >= 1
    hypervisor = ARGV.shift
else
    exit(-1)
end

exec_driver = ExecDriver.new(hypervisor,
                :concurrency => threads,
                :retries => retries,
                :local_actions => local_actions,
                :shell => shell,
                :single_host => single_host,
                :detach_snap => detach_snap,
                :live_snapshots => live_snapshots)

exec_driver.start_driver


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <title>123rf Search Demo</title>

        <link rel="stylesheet" href="styles.css"/>

Search

Browse

                        Enter a search term to find a motive if your choice: <input type="text" value="">
                        <button>Search</button>

                            Chose a media type:
                            <select class="mediaType">
                                <option selected value="all">any</option>
                                <option value="0">photography</option>
                                <option value="1">illustration</option>
                            </select>

                        You can also browse through a variety of preselected topcis: <select class="primary"></select>
                        <select class="secondary"></select>
                        <select class="tertiary"></select>

                Chose a color:

×

            <button class="previous">back</button>
            Page  of
            <button class="next">next</button>


text:
package org.visualtrading.model;

import org.visualtrading.xml.XMLObj;

import java.util.Dictionary;
import java.util.Enumeration;

public interface NewModel extends XMLObj, Cloneable {

// -------------------------- OTHER METHODS --------------------------

    public void clear();

    public boolean containsKey(Object key);

    public void copyFrom(Object source);

    public void copyTo(Object destination);

    public Enumeration elements();

    public Object get(Object key);

    public Object getId();

    public Dictionary getMap();

    public boolean isEmpty();

    public Object[] keySorted();

    public Enumeration keys();

    public Object put(Object key, Object value);

    public Object remove(Object key);

    public void setId(Object key);

    public int size();
}


text:
// <copyright file="MeasureReadHealthStatusBenchmark.cs" company="App Metrics Contributors">
// Copyright (c) App Metrics Contributors. All rights reserved.
// </copyright>

using System.Diagnostics;
using BenchmarkDotNet.Attributes;

namespace App.Metrics.Health.Benchmarks.BenchmarkDotNetBenchmarks
{
    public class MeasureReadHealthStatusBenchmark : DefaultBenchmarkBase
    {
        [Benchmark]
        public void ReadHealth()
        {
            var result = FixtureWithHealth.HealthCheckRunner.ReadAsync().GetAwaiter().GetResult();
            Debug.WriteLine("Health status: " + result.Status);
        }
    }
}


text:
@interface AFLineChartYAxis : UIView

@property (strong, nonatomic) NSMutableArray *aggregateData;
@property (nonatomic) CGFloat bodyPadding;
@property (strong, nonatomic) UIFont *font;
@property (nonatomic) CGFloat lineWidth;
@property (strong, nonatomic) NumberToString numberFormatter;

- (CGFloat)expectedWidth;

@end


text:
package myInterface;

import java.util.List;

/**
 * Created by GameSoftItalia on 07/12/2016.
 */
public interface StatisticaInterface {

    public List getListaTemi();
    public List getListaPunteggi();
    public void setListaTemi(List<String> listaTemi);
    public void setListaPunteggi(List<Integer> listaPunteggi);
    public String toString();
    public boolean equals(Object obj);
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Uses of Class org.apache.commons.lang3.builder.ReflectionToStringBuilder (Apache Commons Lang 3.3 API)</title>
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
org.apache.commons.lang3.builder.ReflectionToStringBuilder

Packages that use ReflectionToStringBuilder

Package
Description

org.apache.commons.lang3.builder

Assists in creating consistent equals(Object), toString(), hashCode(), and compareTo(Object) methods.

Uses of ReflectionToStringBuilder in org.apache.commons.lang3.builder

Methods in org.apache.commons.lang3.builder that return ReflectionToStringBuilder

Modifier and Type
Method and Description

ReflectionToStringBuilder
ReflectionToStringBuilder.reflectionAppendArray(Object array)

 Append to the toString an Object array.

ReflectionToStringBuilder
ReflectionToStringBuilder.setExcludeFieldNames(String... excludeFieldNamesParam)

Sets the field names to exclude.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2001–2014 The Apache Software Foundation. All rights reserved.


text:
import { moduleForModel, test } from 'ember-qunit';

moduleForModel('payment-reconciliation-detail', 'Unit | Model | PaymentReconciliation_Detail', {
  needs: [
    'model:meta',
    'model:narrative',
    'model:resource',
    'model:extension',
    'model:codeable-concept',
    'model:reference',
    'model:money'
  ]
});

test('it exists', function(assert) {
  const model = this.subject();
  assert.ok(!!model);
});


text:
@interface CMHRegistrationData : NSObject

@property (nonatomic, nonnull,  readonly) NSString *email;
@property (nonatomic, nonnull,  readonly) NSString *password;
@property (nonatomic, nullable, readonly) NSString *gender;
@property (nonatomic, nullable, readonly) NSDate   *birthdate;
@property (nonatomic, nullable, readonly) NSString *givenName;
@property (nonatomic, nullable, readonly) NSString *familyName;

- (_Nonnull instancetype)initWithEmail:(NSString *_Nonnull)email
                              password:(NSString *_Nonnull)password
                                gender:(NSString *_Nullable)gender
                             birthdate:(NSDate *_Nullable)birthdate
                             givenName:(NSString *_Nullable)givenName
                            familyName:(NSString *_Nullable)familyName;

+ (_Nullable instancetype)registrationDataFromResult:(ORKCollectionResult *_Nullable)result;

@end


text:
package org.jboss.resteasy.spi;

import org.jboss.resteasy.core.ResourceMethodInvoker;

import javax.ws.rs.container.AsyncResponse;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.ext.WriterInterceptor;
import java.lang.annotation.Annotation;

/**
 * @author Bill Burke
 * @version $Revision: 1 $
 */
public interface ResteasyAsynchronousResponse extends AsyncResponse
{
   /**
     * Callback by the initial http request thread.  It is used to help simulate suspend/resume asynchronous semantics
     * in containers that do not support asychronous HTTP. This method is a no-op in environments that support async HTTP.
     */
    public void initialRequestThreadFinished();

    ContainerResponseFilter[] getResponseFilters();

    void setResponseFilters(ContainerResponseFilter[] responseFilters);

    WriterInterceptor[] getWriterInterceptors();

    void setWriterInterceptors(WriterInterceptor[] writerInterceptors);

    Annotation[] getAnnotations();

    void setAnnotations(Annotation[] annotations);

    ResourceMethodInvoker getMethod();

    void setMethod(ResourceMethodInvoker method);

}


text:
"""
Re-process an archived version of the CAL-ACCESS data.
"""
import os
import logging
from datetime import datetime
import shutil
import zipfile
from hurry.filesize import size
from clint.textui import progress
from django.utils.timezone import now
from django.core.management import call_command
from django.core.management.base import CommandError
from calaccess_raw.management.commands import CalAccessCommand
from calaccess_raw.models.tracking import RawDataVersion
from calaccess_raw import get_data_directory, get_model_list
logger = logging.getLogger(__name__)

class Command(CalAccessCommand):
    """
    Re-process an archived version of the CAL-ACCESS data.
    """
    help = "Re-process an archived version of the CAL-ACCESS data."

    def add_arguments(self, parser):
        """
        Adds custom arguments specific to this command.
        """
        super(Command, self).add_arguments(parser)
        parser.add_argument(
            'release-date',
            help="Date that the version was released (format: YYYY-MM-DD)"
        )
        parser.add_argument(
            "--skip-clean",
            action="store_false",
            dest="clean",
            default=True,
            help="Skip cleaning up the raw data files"
        )
        parser.add_argument(
            "--skip-load",
            action="store_false",
            dest="load",
            default=True,
            help="Skip loading up the raw data files"
        )
        parser.add_argument(
            "--keep-files",
            action="store_true",
            dest="keep_files",
            default=False,
            help="Keep zip, unzipped, TSV and CSV files"
        )
        parser.add_argument(
            "-a",
            "--app-name",
            dest="app_name",
            default="calaccess_raw",
            help="Name of Django app with models into which data will "
                 "be imported (if other not calaccess_raw)"
        )

    def handle(self, *args, **options):
        """
        Make it happen.
        """
        super(Command, self).handle(*args, **options)

        # set / compute any attributes that multiple class methods need
        self.release_date = datetime.strptime(
            options['release-date'],
            '%Y-%m-%d'
        ).date()
        self.app_name = options["app_name"]
        self.keep_files = options["keep_files"]
        self.cleaning = options['clean']
        self.loading = options['load']
        self.data_dir = get_download_directory()

        os.path.exists(self.data_dir) or os.makedirs(self.data_dir)

        self.zip_path = os.path.join(self.data_dir, 'calaccess.zip')
        self.tsv_dir = os.path.join(self.data_dir, "tsv/")
        self.csv_dir = os.path.join(self.data_dir, "csv/")

        os.path.exists(self.csv_dir) or os.makedirs(self.csv_dir)

        try:
            version = self.raw_data_versions.get(
                release_datetime__year=self.release_date.year,
                release_datetime__month=self.release_date.month,
                release_datetime__day=self.release_date.day,
            )
        except RawDataVersion.DoesNotExist:
            raise CommandError(
                "No release from {0} in archive.".format(self.release_date)
            )

        last_started_reprocess = self.get_last_log()

        self.resume_mode = False

        if last_started_reprocess:
            if last_started_reprocess.finish_datetime:
                if last_started_reprocess.version == version:
                    if len(last_started_reprocess.called) > 0:
                        self.log('Resuming previous re-processing job.')
                        self.resume_mode = True

        if self.resume_mode:
            self.log_record = last_started_reprocess
        else:
            # create a new log record
            self.log_record = self.command_logs.create(
                version=version,
                command=self,
                called_by=self.get_caller_log()
            )

        if self.verbosity:
            self.header("Copying archived zip file to data directory")

        if not self.resume_mode:
            # copy the zip file to the data directory
            with open(self.zip_path, 'w') as local_zip:
                version.zip_file_archive.open()
                local_zip.write(version.zip_file_archive.read())
                version.zip_file_archive.close()

            self.unzip()
            self.prep()

            if self.verbosity:
                self.duration()

        # execute the other steps that haven't been skipped
        if options['clean']:
            self.clean()
            if self.verbosity:
                self.duration()

        if options['load']:
            self.load()
            if self.verbosity:
                self.duration()

        self.log_record.finish_datetime = now()
        self.log_record.save()

        if self.verbosity:
            self.success("Done!")
        logger.info("Done!")

    def unzip(self):
        """
        Unzip the snapshot file.
        """
        if self.verbosity:
            self.log(" Unzipping archive")

        with zipfile.ZipFile(self.zip_path) as zf:
            for member in zf.infolist():
                words = member.filename.split('/')
                path = self.data_dir
                for word in words[:-1]:
                    drive, word = os.path.splitdrive(word)
                    head, word = os.path.split(word)
                    if word in (os.curdir, os.pardir, ''):
                        continue
                    path = os.path.join(path, word)
                zf.extract(member, path)

    def prep(self):
        """
        Rearrange the unzipped files and get rid of the stuff we don't want.
        """
        if self.verbosity:
            self.log(" Prepping unzipped data")

        # Move the deep down directory we want out
        shutil.move(
            os.path.join(
                self.data_dir,
                'CalAccess/DATA/CalAccess/DATA/'
            ),
            self.data_dir
        )
        # Clear out target if it exists
        if os.path.exists(self.tsv_dir):
            shutil.rmtree(self.tsv_dir)

        # Rename it to the target
        shutil.move(
            os.path.join(self.data_dir, "DATA/"),
            self.tsv_dir,
        )

    def clean(self):
        """
        Clean up the raw data files from the state so they are ready to get loaded into the database.
        """
        if self.verbosity:
            self.header("Cleaning data files")

        tsv_list = os.listdir(self.tsv_dir)

        if self.resume_mode:
            # get finished clean command logs of last update
            prev_cleaned = [
                x.file_name + '.TSV'
                for x in self.log_record.called.filter(
                    command='cleancalaccessrawfile',
                    finish_datetime__isnull=False
                )
            ]
            self.log("{} files already cleaned.".format(len(prev_cleaned)))
            # remove these from tsv_list
            tsv_list = [x for x in tsv_list if x not in prev_cleaned]

        # Loop through all the files in the source directory
        if self.verbosity:
            tsv_list = progress.bar(tsv_list)
        for name in tsv_list:
            call_command(
                "cleancalaccessrawfile",
                name,
                verbosity=self.verbosity,
                keep_files=self.keep_files,
            )

    def load(self):
        """
        Loads the cleaned up csv files into the database.
        """
        if self.verbosity:
            self.header("Loading data files")

        model_list = [
            x for x in get_model_list() if os.path.exists(x.objects.get_csv_path())
        ]

        if self.resume_mode:
            # get finished load command logs of last update
            prev_loaded = [
                x.file_name
                for x in self.log_record.called.filter(
                    command='loadcalaccessrawfile',
                    finish_datetime__isnull=False
                )
            ]
            self.log("{} models already loaded.".format(len(prev_loaded)))
            # remove these from model_list
            model_list = [x for x in model_list if x._meta.db_table not in prev_loaded]

        if self.verbosity:
            model_list = progress.bar(model_list)
        for model in model_list:
            call_command(
                "loadcalaccessrawfile",
                model.__name__,
                verbosity=self.verbosity,
                keep_files=self.keep_files,
                app_name=self.app_name,
            )


text:
package io.seata.console.config;

import io.seata.console.filter.JwtAuthenticationTokenFilter;
import io.seata.console.security.CustomUserDetailsServiceImpl;
import io.seata.console.security.JwtAuthenticationEntryPoint;
import io.seata.console.utils.JwtTokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.BeanIds;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * Spring security config
 *
 * @author jameslcj
 */
@Configuration(proxyBeanMethods = false)
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * The constant AUTHORIZATION_HEADER.
     */
    public static final String AUTHORIZATION_HEADER = "Authorization";

    /**
     * The constant AUTHORIZATION_TOKEN.
     */
    public static final String AUTHORIZATION_TOKEN = "access_token";

    /**
     * The constant SECURITY_IGNORE_URLS_SPILT_CHAR.
     */
    public static final String SECURITY_IGNORE_URLS_SPILT_CHAR = ",";

    /**
     * The constant TOKEN_PREFIX.
     */
    public static final String TOKEN_PREFIX = "Bearer ";

    @Autowired
    private CustomUserDetailsServiceImpl userDetailsService;

    @Autowired
    private JwtAuthenticationEntryPoint unauthorizedHandler;

    @Autowired
    private JwtTokenUtils tokenProvider;

    @Autowired
    private Environment env;

    @Bean(name = BeanIds.AUTHENTICATION_MANAGER)
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Override
    public void configure(WebSecurity web) {
        String ignoreURLs = env.getProperty("seata.security.ignore.urls", "/**");
        for (String ignoreURL : ignoreURLs.trim().split(SECURITY_IGNORE_URLS_SPILT_CHAR)) {
            web.ignoring().antMatchers(ignoreURL.trim());
        }
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().authenticated().and()
            // custom token authorize exception handler
            .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
            // since we use jwt, session is not necessary
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
            // since we use jwt, csrf is not necessary
            .csrf().disable();
        http.addFilterBefore(new JwtAuthenticationTokenFilter(tokenProvider),
            UsernamePasswordAuthenticationFilter.class);

        // disable cache
        http.headers().cacheControl();
    }

    /**
     * Password encoder password encoder.
     *
     * @return the password encoder
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

}


text:
import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';

moduleForComponent('spark-action-info', 'Integration | Component | spark action info', {
  integration: true
});

test('it renders', function(assert) {
  // Set any properties with this.set('myProperty', 'value');
  // Handle any actions with this.on('myAction', function(val) { ... });"

  this.render(hbs`{{spark-action-info}}`);

  assert.equal(this.$().text().trim(), '');

  // Template block usage:"
  this.render(hbs`
    {{#spark-action-info}}
      template block text
    {{/spark-action-info}}
  `);

  assert.equal(this.$().text().trim(), 'template block text');
});


text:
namespace MobileDevice
{
    using System;
    using System.Collections.Generic;

    public class GSMCallHistoryTest
    {
        //public static void Main()
        //{
        //    // Comment the Main() in GSMTest.cs and uncomment this to test
        //    GSM mobilePhone = new GSM("dsds", "dsds");

        //    Call currentCall = new Call(DateTime.Now, "0899587433", 284);
        //    mobilePhone.AddCalls(currentCall);

        //    currentCall = new Call(DateTime.Now.AddMinutes(788), "0899410033", 100);
        //    mobilePhone.AddCalls(currentCall);

        //    currentCall = new Call(DateTime.Now.AddDays(14), "0877410033", 1440);
        //    mobilePhone.AddCalls(currentCall);

        //    foreach (var item in mobilePhone.CallHistory)
        //    {
        //        Console.WriteLine("Date: {0}\nNumber: {1}\nDuration: {2}\n", item.TimeOfCall, item.PhoneNumber, item.Duration);
        //    }

        //    Console.WriteLine("Price of calls: {0:C2}", mobilePhone.CalculateCallsPrice());

        //    long maxCallDuration = long.MinValue;
        //    Call longestCall = new Call(DateTime.Now, "0000000000", 0);

        //    foreach (var item in mobilePhone.CallHistory)
        //    {
        //        if (item.Duration > maxCallDuration)
        //        {
        //            maxCallDuration = item.Duration;
        //            longestCall = item;
        //        }
        //    }

        //    mobilePhone.DeleteCalls(longestCall);
        //    Console.WriteLine("The price without the longest call: {0:C2}", mobilePhone.CalculateCallsPrice());

        //    mobilePhone.ClearCalls();

        //    Console.WriteLine("\nCheck for calls:");

        //    if (mobilePhone.CallHistory.Count == 0)
        //    {
        //        Console.WriteLine("No calls found");
        //    }
        //}
    }
}


text:
package com.scwang.smartrefresh.header.flyrefresh;

import android.content.Context;
import android.util.AttributeSet;

import com.scwang.smartrefresh.layout.internal.pathview.PathsView;
import com.scwang.smartrefresh.layout.util.DensityUtil;

/**
 * 纸飞机视图
 * Created by SCWANG on 2017/6/6.
 */

public class FlyView extends PathsView {

    public FlyView(Context context) {
        super(context);
        this.initView(context, null, 0);
    }

    public FlyView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.initView(context, attrs, 0);
    }

    public FlyView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.initView(context, attrs, defStyleAttr);
    }

    private void initView(Context context, AttributeSet attrs, int defStyleAttr) {
        parserColors(0xffffffff);
        parserPaths("M2.01,21L23,12 2.01,3 2,10l15,2 -15,2z");
        setMinimumWidth(DensityUtil.dp2px(25));
        setMinimumHeight(DensityUtil.dp2px(25));
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(resolveSize(getSuggestedMinimumWidth(), widthMeasureSpec),
                resolveSize(getSuggestedMinimumHeight(), heightMeasureSpec));
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".activity.CrashTestActivity">

    <Button
        android:id="@+id/btn_crash_test1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="测试1"/>
    <Button
        android:id="@+id/btn_crash_test2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="测试2"/>
    <Button
        android:id="@+id/btn_crash_test3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="测试3"/>
    <Button
        android:id="@+id/btn_crash_test4"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="测试4"/>
    <Button
        android:id="@+id/btn_crash_test5"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="测试5"/>
    <Button
        android:id="@+id/btn_crash_test6"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="测试6"/>
    <Button
        android:id="@+id/btn_crash_test7"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="测试7"/>
    <Button
        android:id="@+id/btn_crash_test8"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="测试8"/>

</LinearLayout>


text:
from .queries import GranuleQuery, CollectionQuery

__all__ = ["GranuleQuery", "CollectionQuery"]


text:
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Csla;
using MyVote.BusinessObjects.Attributes;
using MyVote.BusinessObjects.Contracts;
using MyVote.BusinessObjects.Core;

namespace MyVote.BusinessObjects
{
	[System.Serializable]
	internal sealed class PollSubmissionCommand
		: CommandBaseScopeCore<PollSubmissionCommand>, IPollSubmissionCommand
	{

        [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")]
        [RunLocal]
        private void DataPortal_Create() { }

#if !NETFX_CORE && !MOBILE
        protected override void DataPortal_Execute()
		{
			var submissionExists = (from s in this.Entities.MVPollSubmissions
											where (s.UserID == this.UserID &&
											s.PollID == this.PollID)
											select s.PollSubmissionID).Any();

			if (!submissionExists)
			{
				this.Submission = this.Factory.Create(
					new PollSubmissionCriteria(this.PollID, this.UserID));
			}
		}
#endif

		public static PropertyInfo<int> PollIDProperty =
			PollSubmissionCommand.RegisterProperty<int>(_ => _.PollID);
		public int PollID
		{
			get { return this.ReadProperty(PollSubmissionCommand.PollIDProperty); }
			set { this.LoadProperty(PollSubmissionCommand.PollIDProperty, value); }
		}

		public static PropertyInfo<int> UserIDProperty =
			PollSubmissionCommand.RegisterProperty<int>(_ => _.UserID);
		public int UserID
		{
			get { return this.ReadProperty(PollSubmissionCommand.UserIDProperty); }
			set { this.LoadProperty(PollSubmissionCommand.UserIDProperty, value); }
		}

		public static PropertyInfo<IPollSubmission> SubmissionProperty =
			PollSubmissionCommand.RegisterProperty<IPollSubmission>(_ => _.Submission);
		public IPollSubmission Submission
		{
			get { return this.ReadProperty(PollSubmissionCommand.SubmissionProperty); }
			private set { this.LoadProperty(PollSubmissionCommand.SubmissionProperty, value); }
		}

#if !NETFX_CORE && !MOBILE
        [NonSerialized]
		private IObjectFactory<IPollSubmission> factory;
		[Dependency]
		public IObjectFactory<IPollSubmission> Factory
		{
			get { return this.factory; }
			set { this.factory = value; }
		}
#endif
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--*************************************************************************
Filename        :   build.xml
Project         :   proj4js
Document Type   :   XML
Purpose         :   build file for ant tool

Author     Date            Description
M.Adair    17-Dec-2001     initial version copied from mapbuilder

$Id: build.xml 2955 2007-07-09 12:12:27Z steven $
***************************************************************************--><!--
-->
<!-- A "project" describes a set of targets that may be requested
     when Ant is executed.  The "default" attribute defines the
     target which is executed if no specific target is requested,
     and the "basedir" attribute defines the current working directory
     from which Ant executes the requested task.  This is normally
     set to the current working directory.
-->
  <project basedir=".." default="dist" name="proj4js">

<!-- ===================== Property Definitions =========================== -->
<!--
  Each of the following properties are used in the build script.
  Values for these properties are set by the first place they are
  defined, from the following list:

  * Definitions on the "ant" command line (ant -Dfoo=bar compile).

  * Definitions from a "build.properties" file in the top level
    source directory of this application.

  * Definitions from a "build.properties" file in the developer's
    home directory.

  * Default definitions in this build.xml file.

  You will note below that property values can be composed based on the
  contents of previously defined properties.  This is a powerful technique
  that helps you minimize the number of changes required when your development
  environment is modified.  Note that property composition is allowed within
  "build.properties" files as well as in the "build.xml" script.
-->
  <property file="build.properties"/>
  <property file="${user.home}/build.properties"/>
  <property file="default.properties"/>

<!-- ==================== File and Directory Names ======================== -->
<!--

  These properties generally define file and directory names (or paths) that
  affect where the build process stores its outputs.

  app.name             Base name of this application, used to
                       construct filenames and directories.
                       Defaults to "myapp".

  app.path             Context path to which this application should be
                       deployed (defaults to "/" plus the value of the
                       "app.name" property).

  app.version          Version number of this iteration of the application.

  build.home           The directory into which the "prepare" and
                       "compile" targets will generate their output.
                       Defaults to "build".

  dist.home            The name of the base directory in which
                       distribution files are created.
                       Defaults to "dist".
-->

  <property environment="env"/>
  <property name="app.name" value="proj4js"/>
  <property name="app.path" value="/${app.name}"/>
  <property name="app.version" value="1.1.0"/>
  <property name="build.home" value="${basedir}/tempBuild"/>
  <property name="dist.home" value="${basedir}/dist"/>
  <property name="docs.home" value="${build.home}/docs"/>

<!-- ==================== Prepare Target ================================== -->
<!--
  The "prepare" target is used to create the "build" destination directory,
  and copy the static contents of your web application to it.  If you need
  to copy static files from external dependencies, you can customize the
  contents of this task.

  Normally, this task is executed indirectly when needed.

-->

  <target name="prepare">
    <!-- Create build directories as needed -->
    <mkdir dir="${build.home}"/>
    <!-- Copy static content of the mapbuilder project  -->
    <copy todir="${build.home}">
      <fileset dir="${basedir}" excludes="tools/*.pyc "
          includes="index.html
                    lib/proj4js.js,
                    lib/proj4js-combined.js
                    lib/proj4js-compressed.js
                    lib/defs/**
                    lib/projCode/**
                    lib/util/**
                    build/**
                    demo/**
                    test/**
                    tools/**"
      />
    </copy>
  </target>

<!-- ==================== Clean Target ==================================== -->
<!--

  The "clean" target deletes any previous "build" and "dist" directory,
  so that you can be ensured the application can be built from scratch.

-->

  <target description="Delete old build and dist directories" name="clean">
    <delete dir="${build.home}"/>
    <delete dir="${dist.home}"/>
  </target>

<!-- ==================== Documentation =================================== -->

  <target description="Create documentation" name="docs" depends="prepare">

    <mkdir dir="${build.home}/docs"/>
    <mkdir dir="${build.home}/docs/NaturalDocs"/>

    <echo message="Generating documentation"/>
    <exec executable="cmd" os="Windows XP" dir="${build.home}">
        <arg line="/c perl C:\Progra~1\NaturalDocs\NaturalDocs -i ./lib -o html ./docs/NaturalDocs -p ./docs/NaturalDocs -r"/>
    </exec>
  </target>

<!-- ==================== Dist Target ===================================== -->
<!--
  The "dist" target creates the zip file distribution for the Apache/PHP
  environment.
-->
  <target name="dist" description="Create binary distribution" depends="clean,prepare,docs">

    <mkdir dir="${dist.home}"/>

    <!-- Create application zip file -->
    <zip destfile="${dist.home}/${app.name}-${app.version}.zip" update="true">
      <zipfileset dir="${build.home}" prefix="proj4js"/>
    </zip>

  </target>

</project>