text:
hapi has an extensive and powerful plugin system that allows you to very easily break your application up into isolated pieces of business logic, and reusable utilities.

## Creating a plugin

Plugins are very simple to write. At their core they are an object with a `register` function that has the signature `function (server, options, next)`. That `register` function then has an `attributes` object attached to it to provide hapi with some additional information about the plugin, such as name and version.

A very simple plugin looks like:

```javascript
'use strict';

const myPlugin = {
    register: function (server, options, next) {
        next();
    }
};

myPlugin.register.attributes = {
    name: 'myPlugin',
    version: '1.0.0'
};
```

Or when written as an external module:

```javascript
'use strict';

exports.register = function (server, options, next) {
    next();
};

exports.register.attributes = {
    pkg: require('./package.json')
};
```

Note that in the first example, we set the `name` and `version` attributes specifically, however in the second we set a `pkg` parameter with the contents of package.json as its value. Either method is acceptable.

Additionally, the `attributes` object may contain the key `multiple` that when set to `true` tells hapi that it is safe to register your plugin more than once in the same server.

### The register method

As we've seen above, the `register` method accepts three parameters, `server`, `options`, and `next`.

The `options` parameter is simply whatever options the user passes to your plugin. No changes are made and the object is passed directly to your `register` method.

`next` is a method to be called when your plugin has completed whatever steps are necessary for it to be registered. This method accepts only one parameter, `err`, that should only be defined if an error occurred while registering your plugin.

The `server` object is a reference to the `server` your plugin is being loaded in.

#### `server.select()`

Servers can have connections added with a label assigned to them:

```javascript
const server = new Hapi.Server();
server.connection({ labels: ['api'] });
```

This label can then be used to apply plugins and other settings only to specific connections by using the `server.select()` method.

For example, to add a route only to connections with a label of `'api'`, you would use:

```javascript
const api = server.select('api');

api.route({
    method: 'GET',
    path: '/',
    handler: function (request, reply) {
        reply('api index');
    }
});
```

Multiple labels can be selected at the same time by passing an array of strings, this works as a logical OR statement. To accomplish a logical AND, you can chain calls to `server.select()` like so:

```javascript
// all servers with a label of backend OR api
const myServers = server.select(['backend', 'api']);

// servers with a label of api AND admin
const adminServers = server.select('api').select('admin');
```

The return value of `server.select()` is a server object that contains only the selected connections.

## Loading a plugin

Plugins can be loaded one at a time, or as a group in an array, by the `server.register()` method, for example:

```javascript
// load one plugin
server.register(require('myplugin'), (err) => {
    if (err) {
        console.error('Failed to load plugin:', err);
    }
});

// load multiple plugins
server.register([require('myplugin'), require('yourplugin')], (err) => {
    if (err) {
        console.error('Failed to load a plugin:', err);
    }
});
```

To pass options to your plugin, we instead create an object with `register` and `options` keys, such as:

```javascript
server.register({
    register: require('myplugin'),
    options: {
        message: 'hello'
    }
}, (err) => {

    if (err) {
        throw err;
    }
});
```

These objects can also be passed in an array:

```javascript
server.register([{
    register: require('plugin1'),
    options: {}
}, {
    register: require('plugin2'),
    options: {}
}], (err) => {

    if (err) {
        throw err;
    }
});
```

### Plugin options

You may also pass an optional parameter to `server.register()` before the callback. Documentation for this object can be found in the [API reference](/api#serverregisterplugins-options-callback).

The options object is used by hapi and is *not* passed to the plugin(s) being loaded. It allows you to pre-select servers based on one or more labels, as well as apply `vhost` or `prefix` modifiers to any routes that your plugins register.

For example, let's say we have a plugin that looks like this:

```javascript
'use strict';

exports.register = function (server, options, next) {

    server.route({
        method: 'GET',
        path: '/test',
        handler: function (request, reply) {
            reply('test passed');
        }
    });

    next();
};

exports.register.attributes = {
    pkg: require('./package.json')
};
```

Normally, when this plugin is loaded it will create a `GET` route at `/test`. This can be changed by using the `prefix` setting in the options, which will prepend a string to all routes created in the plugin:

```javascript
server.register({ register: require('myplugin') }, {
    routes: {
        prefix: '/plugins'
    }
}, (err) => {

    if (err) {
        throw err;
    }
});
```

Now when the plugin is loaded, because of the `prefix` option the `GET` route will be created at `/plugins/test`.

Similarly the `config.vhost` parameter will assign a default `vhost` configuration to any routes created by the plugins being loaded. More detail about the `vhost` configuration can be found in the [API reference](/api#route-options).

The `select` parameter works exactly the same way as `server.select()` does, in that you may pass one label or an array of labels for the plugin to be associated with.

```javascript
server.register({ register: require('myplugin') }, {
    select: ['webserver', 'admin']
}, (err) => {

    if (err) {
        throw err;
    }
});
```

This allows you to attach a plugin to specific connections in a server without having to change the code of the plugin.


text:
<?xml version="1.0" encoding="UTF-8"?>
<module rename-to='webclient'>
  <inherits name="org.waveprotocol.box.webclient.WebClient"/>

  <inherits name='com.google.gwt.user.theme.chrome.Chrome'/>

  <!-- Specification of permutation restrictions suitable for production.
       In general, this should support as many permutations as possible -->

  <!-- Stack emulation is too slow to use in production. -->
  <set-property name="compiler.emulatedStack" value="false"/>

  <!-- Specify the app entry point class.                         -->
  <entry-point class='org.waveprotocol.box.webclient.client.WebClient'/>

  <!-- Only build supported clients. -->
  <set-property name="user.agent" value="safari,gecko1_8,ie6,ie8"/>
  <set-property name="mobile.user.agent" value="not_mobile" />

  <!-- Turn off logging, because it's really slow. -->
  <set-property name="loglevel" value="none" />
</module>

redpajama_set_name: RedPajamaGithub


text:
/*globals describe,it,beforeEach,process */
'use strict';

var expect = require('chai').expect;
var Router = require('../../../lib/router');
var sinon = require('sinon');
var routesObject = {
    article: {
        path: '/:site/:category?/:subcategory?/:alias',
        method: 'get',
        page: 'viewArticle'
    },
    offnetwork_article: {
        path: '/',
        method: 'get',
        navigate: {
            params: {
                id: /^\w{4}\-\w{3}$/,
                foo: 'bar'
            }
        },
        page: 'viewArticle'
    },
    home: {
        path: '/',
        method: 'get',
        page: 'viewHomepage'
    },
    new_article: {
        path: '/new_article',
        method: 'post',
        page: 'createArticle'
    },
    custom_match_params: {
        path: '/posts/:id(\\d+)'
    },
    unamed_params: {
        path: '/:foo/(.*)',
        method: null
    },
    no_methods: {
        path: '/no_methods',
        method: null
    },
    multi_methods: {
        path: '/multi_methods',
        method: ['get', 'post']
    },
    all_methods: {
        path: '/all_methods'
    },
    case_insensitive: {
        path: '/case_insensitive',
        method: 'GET',
        page: 'viewCaseInsensitive'
    },
    array_path: {
        path: ['/array_path']
    },
    array_path_name_collision: {
        path: [
            '/array/path/with/collision/foo/:key',
            '/array/path/with/collision/bar/:key'
        ],
        method: 'GET',
        page: 'arrayPathNameCollision'
    },
    invalid_path: {
        path: 123
    },
    json_value: {
        path: '/path/with/some/json_value/:json'
    }
};
var routesArray = Object.keys(routesObject).map(function (routeName) {
    return Object.assign({}, routesObject[routeName], {
        name: routeName
    });
});
var encodingConsistencyPath = '/path/with/some/json_value/%7B%22keyword%22%3A%22foo%22%7D';

describe('Router', function () {
    [routesObject, routesArray].forEach(function (routes, key) {
        var text = ['routes object', 'routes array'];
        describe(text[key], function () {
            var router;
            beforeEach(function () {
                router = new Router(routes);
            });

            describe('#constructor', function () {
                it('should init correctly', function () {
                    expect(Object.keys(router._routes).length).to.equal(routesArray.length);

                    expect(router._routes.article.name).to.equal('article');
                    expect(router._routes.article.config.path).to.equal('/:site/:category?/:subcategory?/:alias');
                    expect(router._routes.article.config.method).to.equal('get');
                    expect(router._routes.article.config.page).to.equal('viewArticle');
                    expect(router._routes.article.config.navigate).to.equal(undefined);
                    expect(router._routes.article.keys.length).to.equal(4);
                    expect(router._routes.article.keys[0].name).to.equal('site');
                    expect(router._routes.article.keys[1].name).to.equal('category');
                    expect(router._routes.article.keys[2].name).to.equal('subcategory');
                    expect(router._routes.article.keys[3].name).to.equal('alias');
                    expect(router._routes.article.regexp).to.be.a('RegExp');

                    expect(router._routes.offnetwork_article.name).to.equal('offnetwork_article');
                    expect(router._routes.offnetwork_article.config.path).to.equal('/');
                    expect(router._routes.offnetwork_article.config.method).to.equal('get');
                    expect(router._routes.offnetwork_article.config.page).to.equal('viewArticle');
                    expect(router._routes.offnetwork_article.config.navigate.params).to.be.a('object');
                    expect(router._routes.offnetwork_article.config.navigate.params.id).to.be.a('RegExp');
                    expect(router._routes.offnetwork_article.keys.length).to.equal(0);
                    expect(router._routes.offnetwork_article.regexp).to.be.a('RegExp');

                    expect(router._routes.home.name).to.equal('home');
                    expect(router._routes.home.config.path).to.equal('/');
                    expect(router._routes.home.config.method).to.equal('get');
                    expect(router._routes.home.config.page).to.equal('viewHomepage');
                    expect(router._routes.home.keys.length).to.equal(0);
                    expect(router._routes.home.regexp).to.be.a('RegExp');

                    expect(router._routes.new_article.name).to.equal('new_article');
                    expect(router._routes.new_article.config.path).to.equal('/new_article');
                    expect(router._routes.new_article.config.method).to.equal('post');
                    expect(router._routes.new_article.config.page).to.equal('createArticle');
                    expect(router._routes.new_article.keys.length).to.equal(0);
                    expect(router._routes.new_article.regexp).to.be.a('RegExp');

                    expect(router._routes.case_insensitive.name).to.equal('case_insensitive');
                    expect(router._routes.case_insensitive.config.path).to.equal('/case_insensitive');
                    expect(router._routes.case_insensitive.config.method).to.equal('GET');
                    expect(router._routes.case_insensitive.config.page).to.equal('viewCaseInsensitive');
                    expect(router._routes.case_insensitive.keys.length).to.equal(0);
                    expect(router._routes.case_insensitive.regexp).to.be.a('RegExp');

                    expect(router._routes.array_path.name).to.equal('array_path');
                    expect(router._routes.array_path.config.path[0]).to.equal('/array_path');
                    expect(router._routes.array_path.keys.length).to.equal(0);
                    expect(router._routes.array_path.regexp).to.be.a('RegExp');

                    expect(router._routes.invalid_path.name).to.equal('invalid_path');
                    expect(router._routes.invalid_path.config.path).to.equal(123);
                    expect(router._routes.invalid_path.keys.length).to.equal(0);
                    expect(router._routes.invalid_path.regexp).to.be.a('RegExp');
                });
                it('should not freeze in production env', function () {
                    var origEnv = process.env.NODE_ENV;
                    process.env.NODE_ENV = 'production';
                    var notFrozen = new Router(routes);

                    expect(Object.keys(notFrozen._routes).length).to.equal(routesArray.length);
                    notFrozen._routes.foo = null;
                    expect(notFrozen._routes.foo).to.equal(null);
                    expect(Object.keys(notFrozen._routes).length).to.equal(routesArray.length + 1);

                    var homeRoute = notFrozen._routes.home;
                    expect(homeRoute.name).to.equal('home');
                    homeRoute.name = 'changed';
                    expect(homeRoute.name).to.equal('changed');
                    process.env.NODE_ENV = origEnv;
                });
                it('should freeze in non-production env', function () {
                    var origEnv = process.env.NODE_ENV;
                    process.env.NODE_ENV = 'development';
                    var frozen = new Router(routes);
                    var homeRoute = frozen._routes.home;
                    expect(Object.keys(frozen._routes).length).to.equal(routesArray.length);
                    expect(homeRoute.name).to.equal('home');
                    expect(homeRoute.config.path).to.equal('/');
                    expect(homeRoute.config.method).to.equal('get');
                    expect(homeRoute.config.page).to.equal('viewHomepage');
                    expect(homeRoute.keys.length).to.equal(0);
                    expect(homeRoute.regexp).to.be.a('RegExp');
                    expect(function () {
                        frozen._routes.foo = 'abc';
                    }).to['throw'](TypeError);
                    expect(function () {
                        homeRoute.name = 'unfreeze!';
                    }).to['throw'](TypeError);
                    expect(function () {
                        homeRoute.config.method = 'unfreeze!';
                    }).to['throw'](TypeError);
                    expect(function () {
                        homeRoute.config.page = 'unfreeze!';
                    }).to['throw'](TypeError);
                    expect(function () {
                        homeRoute.keys[0] = 'unfreeze!';
                    }).to['throw'](TypeError);
                    expect(function () {
                        homeRoute.config.regexp = null;
                    }).to['throw'](TypeError);
                    expect(Object.keys(frozen._routes).length).to.equal(routesArray.length);
                    expect(frozen._routes.foo).to.equal(undefined);
                    expect(homeRoute.keys.length).to.equal(0);
                    expect(homeRoute.name).to.equal('home');
                    expect(homeRoute.config.path).to.equal('/');
                    expect(homeRoute.config.method).to.equal('get');
                    expect(homeRoute.config.page).to.equal('viewHomepage');
                    expect(homeRoute.keys.length).to.equal(0);
                    expect(homeRoute.regexp).to.be.a('RegExp');
                    process.env.NODE_ENV = origEnv;
                });
            });
        });
    });

    describe('#getRoute', function () {
        var router;
        beforeEach(function () {
            router = new Router(routesArray);
        });
        it('existing route', function () {
            var route = router.getRoute('/finance/news/e-t-initially-horror-film-202700630.html', {method: 'get'});
            expect(route.name).to.equal('article');
            expect(route.params.site).to.equal('finance');
            expect(route.params.category).to.equal('news');
            expect(route.params.alias).to.equal('e-t-initially-horror-film-202700630.html');

            route = router.getRoute('/finance/news/e-t-initially-horror-film-202700630.html?query=true', {method: 'get'});
            expect(route.name).to.equal('article');
            expect(route.params.site).to.equal('finance');
            expect(route.params.category).to.equal('news');
            expect(route.params.alias).to.equal('e-t-initially-horror-film-202700630.html');

            route = router.getRoute('/finance/news/e-t-initially-horror-film-202700630.html?query=true#hasHashToo', {method: 'get'});
            expect(route.name).to.equal('article');
            expect(route.params.site).to.equal('finance');
            expect(route.params.category).to.equal('news');
            expect(route.params.alias).to.equal('e-t-initially-horror-film-202700630.html');

            route = router.getRoute('/finance/news/e-t-initially-horror-film-202700630.html#hasHash', {method: 'get'});
            expect(route.name).to.equal('article');
            expect(route.params.site).to.equal('finance');
            expect(route.params.category).to.equal('news');
            expect(route.params.alias).to.equal('e-t-initially-horror-film-202700630.html');

            route = router.getRoute('/sports/blogs/nfl-shutdown-corner/report-says-aaron-hernandez-having-trouble-paying-legal-bills-215349137.html', {method: 'get'});
            expect(route.name).to.equal('article');
            expect(route.params.site).to.equal('sports');
            expect(route.params.category).to.equal('blogs');
            expect(route.params.subcategory).to.equal('nfl-shutdown-corner');
            expect(route.params.alias).to.equal('report-says-aaron-hernandez-having-trouble-paying-legal-bills-215349137.html');

            route = router.getRoute('/new_article', {method: 'post'});
            expect(route.name).to.equal('new_article');

            route = router.getRoute('/new_article?foo=bar', {method: 'post'});
            expect(route.name).to.equal('new_article');
            expect(route.params).to.deep.equal({});
            expect(route.query).to.deep.equal({foo: 'bar'});
        });

        it('method should be case-insensitive and defaults to get', function () {
            var route = router.getRoute('/finance/news/e-t-initially-horror-film-202700630.html');
            expect(route.name).to.equal('article');
            expect(route.method).to.equal('GET');
            route = router.getRoute('/finance/news/e-t-initially-horror-film-202700630.html', {method: 'GET'});
            expect(route.name).to.equal('article');
            expect(route.method).to.equal('GET');
            route = router.getRoute('/new_article', {method: 'POST'});
            expect(route.method).to.equal('POST');
            expect(route.name).to.equal('new_article');
            route = router.getRoute('/case_insensitive', {method: 'get'});
            expect(route.name).to.equal('case_insensitive');
            expect(route.method).to.equal('GET');
        });

        it('non-existing route', function () {
            var route = router.getRoute('/finance/news/e-t-initially-horror-film-202700630.html', {method: 'post'});
            expect(route).to.equal(null);

            route = router.getRoute('/finance');
            expect(route).to.equal(null);

            route = router.getRoute('/new_article', 'delete');
            expect(route).to.equal(null);
        });
        it('array route with param name collision first', function () {
            var route = router.getRoute('/array/path/with/collision/foo/abc');
            expect(route.params.key).to.equal('abc');
        });
        it('array route with param name collision second', function () {
            var route = router.getRoute('/array/path/with/collision/bar/abc');
            expect(route.params.key).to.equal('abc');
        });
        it('route with json string in param with consistency', function () {
            var route = router.getRoute(encodingConsistencyPath);
            expect(route.params.json).to.equal('{"keyword":"foo"}');
        });

        it('should allow route to match multiple methods', function () {
            var route = 'multi_methods';
            expect(router.getRoute('/' + route).name).to.equal(route);
            expect(router.getRoute('/' + route, {method: 'post'}).name).to.equal(route);
            expect(router.getRoute('/' + route, {method: 'put'})).to.equal(null);
            expect(router.getRoute('/' + route, {method: 'delete'})).to.equal(null);
        });

        it('should allow route to match all methods', function () {
            var route = 'all_methods';
            expect(router.getRoute('/' + route).name).to.equal(route);
            expect(router.getRoute('/' + route, {method: 'post'}).name).to.equal(route);
            expect(router.getRoute('/' + route, {method: 'put'}).name).to.equal(route);
            expect(router.getRoute('/' + route, {method: 'delete'}).name).to.equal(route);
        });

        it('should allow route to match no methods', function () {
            var route = 'no_methods';
            expect(router.getRoute('/' + route)).to.equal(null);
            expect(router.getRoute('/' + route, {method: 'post'})).to.equal(null);
            expect(router.getRoute('/' + route, {method: 'put'})).to.equal(null);
            expect(router.getRoute('/' + route, {method: 'delete'})).to.equal(null);
        });
    });

    describe('#makePath', function () {
        var router;
        beforeEach(function () {
            router = new Router(routesArray);
        });
        it('existing route', function () {
            var path = router.makePath('article', {
                site: 'SITE',
                category: 'CATEGORY',
                subcategory: 'SUBCATEGORY',
                alias: 'ALIAS.html'
            });
            expect(path).to.equal('/SITE/CATEGORY/SUBCATEGORY/ALIAS.html');
        });
        it('handle optional params', function () {
            var path = router.makePath('article', {
                site: 'SITE',
                category: 'CATEGORY',
                alias: 'ALIAS.html'
            });
            expect(path).to.equal('/SITE/CATEGORY/ALIAS.html');
            path = router.makePath('article', {
                site: 'SITE',
                alias: 'ALIAS.html'
            });
            expect(path).to.equal('/SITE/ALIAS.html');
        });
        it('handle custom match params', function () {
            var path = router.makePath('custom_match_params', {
                id: '12345'
            });
            expect(path).to.equal('/posts/12345');
            path = router.makePath('custom_match_params', {
                id: '12345abc'
            });
            expect(path).to.equal(null);
        });
        it('handle unamed params', function () {
            var path = router.makePath('unamed_params', {
                foo: 'foo',
                0: 'bar'
            });
            expect(path).to.equal('/foo/bar');
        });
        it('handle query params', function () {
            var path = router.makePath('unamed_params', {
                foo: 'foo',
                0: 'bar'
            }, {
                foo: 'bar',
                baz: 'foo'
            });
            expect(path).to.equal('/foo/bar?baz=foo&foo=bar');
        });
        it('adds no question mark with empty query', function () {
            var path = router.makePath('unamed_params', {
                foo: 'foo',
                0: 'bar'
            }, {/* empty object */});
            expect(path).to.equal('/foo/bar');
        });
        it('non-existing route', function () {
            var path = router.makePath('article_does_not_exist', {
                site: 'SITE',
                category: 'CATEGORY',
                subcategory: 'SUBCATEGORY',
                alias: 'ALIAS.html'
            });
            expect(path).to.equal(null);
        });
        it('array route', function () {
            var path = router.makePath('array_path', {});
            expect(path).to.equal('/array_path');
        });
        it('invalid route', function () {
            var path = router.makePath('invalid_path', {});
            expect(path).to.equal(null);
        });
        it('path with some json value and consistency', function () {
            var path = router.makePath('json_value', {
                json: JSON.stringify({keyword: 'foo'})
            });
            expect(path).to.equal(encodingConsistencyPath);
        });
    });

    it('should throw if route name is not defined', function () {
        expect(function () {
            new Router([
                {
                    path: '/'
                }
            ]);
        }).to['throw'](Error);
    });

    it('should throw if there are routes with duplicate name', function () {
        expect(function () {
            new Router([
                {
                    name: 'home',
                    path: '/'
                },
                {
                    name: 'home',
                    path: '/home'
                }
            ]);
        }).to['throw'](Error);
    });

    it('should allow custom query string library', function () {
        var queryLib = {
            parse: sinon.spy(function (queryString) {
                return queryString.split('&').reduce(function (a, v) {
                    var split = v.split('=');
                    a[split[0]] = split[1] || null;
                    return a;
                }, {});
            }),
            stringify: sinon.spy(function (queryObject) {
                return Object.keys(queryObject).map(function (key) {
                    return key + '=' + queryObject[key];
                }).join('&');
            })
        };
        var router = new Router([
            {
                name: 'home',
                path: '/',
                method: 'get'
            }
        ], {
            queryLib: queryLib
        });
        var matched = router.getRoute('/?foo=bar&bar=baz');
        expect(queryLib.parse.called).to.equal(true);
        expect(matched.query).to.deep.equal({
            foo: 'bar',
            bar: 'baz'
        });
        var stringified = router.makePath('home', {}, {
            foo: 'bar',
            bar: 'baz'
        });
        expect(queryLib.stringify.called).to.equal(true);
        expect(stringified).to.equal('/?foo=bar&bar=baz');
    });
});

describe('Route', function () {
    it('match', function () {
        var router = new Router(routesObject);
        var homeRoute = router._routes.home;
        expect(homeRoute.match()).to.equal(null, 'empty path returns null');
    });
    it('should leave unset optional parameters as undefined', function(){
        var router = new Router(routesObject);
        var article = router._routes.article;
        var result = article.match('/site/alias');
        expect(result.route.category).to.be.undefined;
        expect(result.route.subcategory).to.be.undefined;
    });
});


text:
/* San Jose State University
 * CS 134 - Game Design and Programming
 * Instructor: Sun Tee Teoh
 * Student: Andrew Kalenda
 *
 * A* Algorithm Demo
 *
 * There is a minor bug where overwriting a start/goal tile with another
 * tile does not remove the start/goal information
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace AstarDemo
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        int HEIGHT = 16;
        int WIDTH = 16;
        Tile[,] tileAt;
        Brush currColor;
        Int32 currCost;
        Astar astar;
        Boolean pathNotSet;
        Int32 startX;
        Int32 startY;
        Int32 goalX;
        Int32 goalY;
        delegate void PaintFunction(Tile tile);
        PaintFunction extraStep;
        PaintFunction doNothing;
        PaintFunction changeStart;
        PaintFunction changeGoal;
        Astar.DataFeed paintAstar;
        LinkedList<Int32[]> path;

        // MAIN FUNCTION: set up the GUI
        public MainWindow()
        {
            InitializeComponent();

            // Set up the grid
            for (int x = 0; x < WIDTH; x++)
                bttnGrid.ColumnDefinitions.Add(new ColumnDefinition());
            for (int y = 0; y < HEIGHT; y++)
                bttnGrid.RowDefinitions.Add(new RowDefinition());

            // Fill it with buttons
            Thickness noBorder = new Thickness(0);
            tileAt = new Tile[HEIGHT, WIDTH];
            for (int x = 0; x < WIDTH; x++)
            {
                for (int y = 0; y < HEIGHT; y++)
                {
                    tileAt[x, y] = new Tile();
                    tileAt[x, y].x = x;
                    tileAt[x, y].y = y;
                    tileAt[x, y].BorderThickness = noBorder;
                    tileAt[x, y].Click += setTile; // hook the paint function below so it is invoked on click
                    bttnGrid.Children.Add(tileAt[x, y]);
                    Grid.SetColumn(tileAt[x, y], x);
                    Grid.SetRow(tileAt[x, y], y);
                }
            }

            // Initialize the pathfinding data
            reset();

            // DELEGATES
            // Set up some functional programming for the paint callbacks
            extraStep = doNothing = delegate(Tile tile) { };
            changeStart = delegate(Tile tile)
            {
                if (startX != -1)
                {
                    tileAt[startX, startY].Background = Brushes.White;
                    astar.updateTraversal(startX, startY, 1);
                }
                startX = tile.x;
                startY = tile.y;
            };
            changeGoal = delegate(Tile tile)
            {
                if (goalX != -1)
                {
                    tileAt[goalX, goalY].Background = Brushes.White;
                    astar.updateTraversal(goalX, goalY, 1);
                }
                goalX = tile.x;
                goalY = tile.y;
            };
            paintAstar = delegate(Int32 x, Int32 y, Char type, Int32 data, Char direction)
            {
                switch (type)
                {
                    case 'o':
                        if (tileAt[x, y].Background.Equals(Brushes.White))
                            tileAt[x, y].Background = Brushes.Beige;
                        if (tileAt[x, y].Background.Equals(Brushes.Blue))
                            tileAt[x, y].Background = Brushes.Teal;
                        tileAt[x, y].Content = direction + " " + data;
                        break;
                    case 'c':
                        if (tileAt[x, y].Background.Equals(Brushes.White))
                            tileAt[x, y].Background = Brushes.DarkGoldenrod;
                        if (tileAt[x, y].Background.Equals(Brushes.Blue))
                            tileAt[x, y].Background = Brushes.DarkOrange;
                        break;
                    default:
                        break;
                }
            };
        }

        // BUTTON FUNCTIONS: reset
        public void reset()
        {
            Int32[,] costFor = new Int32[WIDTH, HEIGHT];
            pathNotSet = true;
            startX = -1;
            startY = -1;
            goalX = -1;
            goalY = -1;

            for (int x = 0; x < WIDTH; x++)
            {
                for (int y = 0; y < HEIGHT; y++)
                {
                    costFor[x, y] = 1;
                    tileAt[x, y].Background = Brushes.White;
                    tileAt[x, y].Content = "";
                }
            }
            astar = new Astar(WIDTH, HEIGHT, costFor);
        }
        public void reset(Object bttn, EventArgs e)
        {
            reset();
        }

        // BUTTON FUNCTIONS: painting tiles
        public void setPaint_Free(Object bttn, EventArgs e)
        {
            currColor = Brushes.White;
            currCost = 1;
            extraStep = doNothing;
        }
        public void setPaint_Goal(Object bttn, EventArgs e)
        {
            currColor = Brushes.Red;
            currCost = 1;
            extraStep = changeGoal;
        }
        public void setPaint_Strt(Object bttn, EventArgs e)
        {
            currColor = Brushes.Green;
            currCost = 1;
            extraStep = changeStart;
        }
        public void setPaint_Wall(Object bttn, EventArgs e)
        {
            currColor = Brushes.DarkGray;
            currCost = Int32.MaxValue;
            extraStep = doNothing;
        }
        public void setPaint_Watr(Object bttn, EventArgs e)
        {
            currColor = Brushes.Blue;
            currCost = 8;
            extraStep = doNothing;
        }
        public void setTile(Object bttn, EventArgs e)
        {
            Tile tile = (Tile)bttn;
            tile.Background = currColor;
            tile.Content = "";
            astar.updateTraversal(tile.x, tile.y, currCost);
            extraStep(tile);
        }

        // PATHING FUNCTIONS
        public void setPath()
        {
            // Have the start and end points not been selected yet?
            if (startX == -1 || goalX == -1)
                return;

            astar.navFromTo(startX, startY, goalX, goalY, paintAstar);
            pathNotSet = false;
        }

        // BUTTON FUNCTIONS: stepping
        public void stepNext(Object bttn, EventArgs e)
        {
            if (pathNotSet)
            {
                setPath();
                return;
            }
            if ((path = astar.step()) != null)
                foreach (Int32[] pair in path)
                    tileAt[pair[0], pair[1]].Background = Brushes.Yellow;
        }
        public void stepFnsh(Object bttn, EventArgs e)
        {
            if (pathNotSet)
            {
                setPath();
                return;
            }
            while ((path = astar.step()) == null) ;
            foreach (Int32[] pair in path)
                tileAt[pair[0], pair[1]].Background = Brushes.Yellow;
        }

        // NESTED CONVENIENCE CLASS
        public class Tile : Button
        {
            public Int32 x;
            public Int32 y;
        }
    }
}


text:
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  {% feed_meta %}
  <title>{{ page.title }}</title>
  <link rel="stylesheet" type="text/css" href="/styles.css">
  <link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/css?family=Belgrano|Inconsolata">
  <link rel="apple-touch-icon-precomposed" sizes="144x144" href="/assets/apple-touch-icon-precomposed.png">
  <link rel="shortcut icon" href="/assets/favicon.ico">
  <script async src="https://www.googletagmanager.com/gtag/js?id=UA-402224-7"></script>
  <script>
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag('js', new Date());
    gtag('config', 'UA-402224-7');
  </script>
</head>


text:
require 'disco/generators'

if [nil, '-h', '--help'].include?(ARGV.first)
  Rails::Generators.help 'generate'
  exit
end

name = ARGV.shift
name = name.sub(/^disco:/, '')

root = defined?(ENGINE_ROOT) ? ENGINE_ROOT : Rails.root
Rails::Generators.invoke "disco:#{name}", ARGV, behavior: :invoke, destination_root: root


text:
<?php
namespace oasis\names\specification\ubl\schema\xsd\CommonBasicComponents_2;

/**
 * @xmlNamespace urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2
 * @xmlType SettlementDiscountPercentType
 * @xmlName SettlementDiscountPercent
 * @var oasis\names\specification\ubl\schema\xsd\CommonBasicComponents_2\SettlementDiscountPercent
 */
class SettlementDiscountPercent
	extends SettlementDiscountPercentType
	{

} // end class SettlementDiscountPercent


text:
        Setup
        PrimeNG is a rich set of open source native Angular UI components.

Download

PrimeNG is available at npm, if you have an existing application run the following command to download it to your project.

npm install primeng --save

Load Configuration

PrimeNG is distributed in commonjs format, a module manager of your choice is required and this guide provides a sample for SystemJS and Webpack.

Import

UI components are configured as modules, once PrimeNG is downloaded and configured, modules and apis can be imported from 'primeng/primeng' shorthand in your application code.

import {AccordionModule} from 'primeng/primeng';     //accordion and accordion tab
import {MenuItem} from 'primeng/primeng';            //api

Importing from primeng/primeng will load all other components as well, to only import a specific component pattern would result in a smaller bundle size.

//import {ComponentModule} from 'primeng/components/componentname/componentname';
//import {InterfaceName} from 'primeng/common/api';

import {AccordionModule} from 'primeng/components/accordion/accordion';
import {MenuItem} from 'primeng/components/common/api';

Dependencies

Majority of PrimeNG components (95%) are native and there are some exceptions having 3rd party dependencies. In addition, components require font-awesome for icons.

The css dependencies are as follows, note that you may change the theme with another one of your choice.

<link rel="stylesheet" type="text/css" href="/node_modules/primeng/resources/themes/omega/theme.css" />
<link rel="stylesheet" type="text/css" href="/node_modules/primeng/resources/primeng.min.css" />
<link rel="stylesheet" type="text/css" href="YOUR_PATH/font-awesome.min.css" />

Here is the list of components with 3rd party dependencies.

                    Component
                    Dependency

                    Schedule
                    FullCalendar and Moment.js

                    Editor
                    Quill Editor

                    GMap
                    Google Maps

                    Charts
                    Charts.js 2.1.x

                    Captcha
                    Google Recaptcha

Angular CLI Integration

Angular CLI is the official CLI tool for Angular. We strongly suggest using Angular CLI when starting an Angular project.

Dependencies

Add PrimeNG and FontAwesome as a dependency

"dependencies": {
  //...
  "primeng": "^2.0.3",
  "font-awesome": "^4.7.0"
},

Styles Configuration

Configure required styles at the styles section, example below uses the Omega theme.

"styles": [
  "../node_modules/primeng/resources/primeng.min.css",
  "../node_modules/primeng/resources/themes/omega/theme.css",
  "../node_modules/font-awesome/css/font-awesome.min.css",
  //...
],

That is all, you may now import PrimeNG components, for a working example visit the PrimeNG CLI QuickStart sample at GitHub.

Angular Seed Integration

Angular2 Seed is a modular starter project, there is an official entry at the project wiki
        describing how to use PrimeNG with seed.

QuickStart with System.js

The official quickstart example of Angular uses System.JS and we
    have extended it to add PrimeNG. Visit the PrimeNG-Quickstart at GitHub for an example.

QuickStart with Webpack

There is also a webpack version of the The official quickstart example of Angular and we
    have extended it to add PrimeNG. Visit the PrimeNG-Quickstart-Webpack at GitHub for an example.

External Articles

PrimeNG - UI Components for Angular 2 - Yakov Fain's Blog

Adding PrimeNG UI components to Angular CLI projects - Yakov Fain's Blog

PRIMENG - WEB COMPONENT FRAMEWORK BASED ON ANGULARJS 2 - DaVinci IT Blog

PrimeNG with CLI - Glen Smith

Hello World Angular 2+ Data Sample Using JavaScriptServices .Net Core and PrimeNg

An Angular 2 Tree With CRUD Functionality


text:
<?php
class PHPUnitStandard_Sniffs_Testing_NoReflectionSniff implements PHP_CodeSniffer_Sniff
{
    public function register()
    {
        return array(T_NEW);
    }

    public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
    {
        $tokens    = $phpcsFile->getTokens();
        $className = $phpcsFile->findNext(
                       T_WHITESPACE, ($stackPtr + 1), NULL, TRUE
                     );

        if ($tokens[$className]['code'] === T_STRING &&
            strpos($tokens[$className]['content'], 'Reflection') === 0) {
            $phpcsFile->addError(
              'Reflection API usage found',
              $stackPtr,
              'NotAllowed',
              array()
            );
        }
    }
}


text:
package org.topbraid.shacl.optimize;

import java.util.List;
import java.util.Map;

import org.apache.jena.graph.Graph;
import org.apache.jena.graph.Node;

/**
 * A Graph interface providing additional optimization features.
 *
 * @author Holger Knublauch
 */
public interface OptimizedMultiUnion {

	boolean getIncludesSHACL();

	boolean getIncludesSPIN();

	List<Node> getLabelProperties();

	void resetOptimizations();

	void tellContainedNamespaces(Map<String,List<Graph>> subjectNamespaces, Map<String,List<Graph>> objectNamespaces);
}


text:
package main

import (
	"github.com/sgoertzen/xchango"
	"github.com/stretchr/testify/assert"
	"google.golang.org/api/calendar/v3"
	"testing"
	"time"
)

func TestBuildDiffListsEmpty(t *testing.T) {
	apps := []xchango.Appointment{}
	events := calendar.Events{}

	actions, err := buildDiffLists(&apps, &events)
	assert.Nil(t, err)
	assert.Equal(t, 0, len(actions.toAdd))
	assert.Equal(t, 0, len(actions.toUpdate))
}

func TestBuildDiffListsAllNew(t *testing.T) {
	apps := []xchango.Appointment{
		xchango.Appointment{
			ItemId:   "Hello",
			Subject:  "sub",
			Location: "loc",
			Body:     "body",
		},
	}
	events := calendar.Events{}

	actions, err := buildDiffLists(&apps, &events)
	assert.Nil(t, err)
	assert.Equal(t, 1, len(actions.toAdd))
	assert.Equal(t, "sub", actions.toAdd[0].Summary)
	assert.Equal(t, "loc", actions.toAdd[0].Location)
	assert.Equal(t, "body", actions.toAdd[0].Description)
	assert.Equal(t, 0, len(actions.toUpdate))
	assert.Equal(t, 0, len(actions.toDelete))
}

func TestBuildDiffListsDelete(t *testing.T) {
	apps := []xchango.Appointment{}
	events := calendar.Events{
		Items: []*calendar.Event{
			&calendar.Event{
				Id: "45",
				ExtendedProperties: &calendar.EventExtendedProperties{
					Private: map[string]string{"ItemId": "45"},
				},
			},
		},
	}

	actions, err := buildDiffLists(&apps, &events)
	assert.Nil(t, err)
	assert.Equal(t, 1, len(actions.toDelete))
	assert.Equal(t, "45", actions.toDelete[0].Id)
	assert.Equal(t, 0, len(actions.toUpdate))
	assert.Equal(t, 0, len(actions.toAdd))
}

func TestBuildDiffListsLeaveExisting(t *testing.T) {
	apps := []xchango.Appointment{}
	events := calendar.Events{
		Items: []*calendar.Event{
			&calendar.Event{
				Id: "45",
				// Note: No extended properties on here.  Indicates not our event.
			},
		},
	}

	actions, err := buildDiffLists(&apps, &events)
	assert.Nil(t, err)
	assert.Equal(t, 0, len(actions.toDelete))
}

func TestPopulateEventEmpty(t *testing.T) {
	e := calendar.Event{}
	a := xchango.Appointment{
		Subject: "42",
		ItemId:  "uniqueId",
	}
	populateEvent(&e, &a)
	assert.Equal(t, "42", e.Summary)
	assert.Equal(t, "uniqueId", e.ExtendedProperties.Private["ItemId"])
}

func TestPopulateEventExisting(t *testing.T) {
	e := calendar.Event{
		Id:      "train",
		Summary: "blah",
	}
	a := xchango.Appointment{
		Subject: "42",
		ItemId:  "uniqueId",
	}
	changes := populateEvent(&e, &a)
	assert.Equal(t, true, changes)
	assert.Equal(t, "42", e.Summary)
	assert.Equal(t, "train", e.Id)
	assert.Equal(t, "uniqueId", e.ExtendedProperties.Private["ItemId"])
}

func TestPopulateEventExistingNoChanges(t *testing.T) {
	e := calendar.Event{
		Id:          "123",
		Summary:     "phone call",
		Description: "hello",
		Start:       &calendar.EventDateTime{DateTime: "2015-05-04T11:00:00-07:00"},
		End:         &calendar.EventDateTime{DateTime: "2015-05-04T12:00:00-07:00"},
	}
	tStart, _ := time.Parse(time.RFC3339, "2015-05-04T18:00:00Z")
	tEnd, _ := time.Parse(time.RFC3339, "2015-05-04T18:00:00Z")
	a := xchango.Appointment{
		Subject:       "phone call",
		ItemId:        "123",
		Start:         tStart,
		End:           tEnd,
		IsAllDayEvent: false,
		Body:          "hello",
	}
	changes := populateEvent(&e, &a)
	assert.False(t, changes)
}

func TestPopulateEventExistingStartChange(t *testing.T) {
	e := calendar.Event{
		Id:          "123",
		Summary:     "phone call",
		Description: "",
		Start:       &calendar.EventDateTime{DateTime: "2015-04-12T16:00:00Z"},
	}
	t1, _ := time.Parse(time.RFC3339, "2015-04-13T16:00:00Z")
	a := xchango.Appointment{
		Subject:       "phone call",
		ItemId:        "123",
		Start:         t1,
		IsAllDayEvent: false,
	}
	changes := populateEvent(&e, &a)
	assert.True(t, changes)
}

func TestPopulateEventExistingEndChange(t *testing.T) {
	e := calendar.Event{
		Id:          "123",
		Summary:     "phone call",
		Description: "",
		Start:       &calendar.EventDateTime{DateTime: "2015-04-13T16:00:00Z"},
		End:         &calendar.EventDateTime{DateTime: "2015-04-13T18:00:00Z"},
	}
	tStart, _ := time.Parse(time.RFC3339, "2015-04-13T16:00:00Z")
	tEnd, _ := time.Parse(time.RFC3339, "2015-04-13T17:00:00Z")
	a := xchango.Appointment{
		Subject:       "phone call",
		ItemId:        "123",
		Start:         tStart,
		End:           tEnd,
		IsAllDayEvent: false,
	}
	changes := populateEvent(&e, &a)

	// Google adjusts the end time between 5 and 15 minutes.  We need to ignore end time differences.
	assert.False(t, changes)
}

func TestPopulateEventExisitingAllDay(t *testing.T) {
	tStart, _ := time.Parse(time.RFC3339, "2015-04-13T16:00:00Z")
	tEnd, _ := time.Parse(time.RFC3339, "2015-04-13T16:00:00Z")
	a := xchango.Appointment{
		Subject:       "phone call",
		ItemId:        "123",
		Start:         tStart,
		End:           tEnd,
		IsAllDayEvent: true,
	}
	e := calendar.Event{
		Id:          "123",
		Summary:     "phone call",
		Description: "",
		Start:       &calendar.EventDateTime{Date: "2015-04-13"},
		End:         &calendar.EventDateTime{Date: "2015-04-14"},
	}
	changes := populateEvent(&e, &a)

	assert.False(t, changes)
}

func TestPopulateEventEmptyAllDay(t *testing.T) {
	tStart, _ := time.Parse(time.RFC3339, "2015-04-13T16:00:00Z")
	tEnd, _ := time.Parse(time.RFC3339, "2015-04-14T16:00:00Z")
	a := xchango.Appointment{
		Subject:       "phone call",
		ItemId:        "123",
		Start:         tStart,
		End:           tEnd,
		IsAllDayEvent: true,
	}
	e := calendar.Event{}
	changes := populateEvent(&e, &a)

	assert.True(t, changes)
	assert.Equal(t, a.Subject, e.Summary)
	assert.Equal(t, &calendar.EventDateTime{Date: "2015-04-13"}, e.Start)
	assert.Equal(t, &calendar.EventDateTime{Date: "2015-04-14"}, e.End)
	assert.Equal(t, a.ItemId, e.ExtendedProperties.Private["ItemId"])
}


text:
/*
0xor1   http://github.com/0xor1
*/
(function () {

    Sudoku.GameBoard3D = function (gameBoard) {

        var n, nSqrd, cSpace, sgSpace, cSize, gSGB;
        n = gameBoard.getGameSize();
        nSqrd = n * n;
        cSpace = Sudoku.GameBoard3D.cellSpacing;
        sgSpace = Sudoku.GameBoard3D.subGridSpacing;
        cSize = Sudoku.GameBoard3D.cellSize;
        gSGB = gameBoard.getSubGridBoundsContainingCell.bind(gameBoard);

        THREE.Object3D.call(this);

        this._gameBoard = gameBoard;

        this._cells = new Utils.MultiArray(nSqrd, nSqrd);

        this._selectedCell = null;

        for (var i = 0; i < nSqrd; i++) {
            for (var j = 0; j < nSqrd; j++) {

                this._cells[i][j] = new Sudoku.GameBoardCell3D(i, j, this._gameBoard.getValue(i, j));
                this.add(this._cells[i][j]);

                this._cells[i][j].position.x = (j * (cSize + cSpace) + gSGB(i, j).jSubGrid * sgSpace) - 0.5 * ((nSqrd - 1) * (cSize + cSpace) + (n - 1) * sgSpace);
                this._cells[i][j].position.y = -(i * (cSize + cSpace) + gSGB(i, j).iSubGrid * sgSpace) + 0.5 * ((nSqrd - 1) * (cSize + cSpace) + (n - 1) * sgSpace);
                this._cells[i][j].position.z = 0;

                this._cells[i][j].addEventListener("selected", cellSelected.bind(this));
                this._cells[i][j].addEventListener("deselected", cellDeselected.bind(this));
            }
        }

        this._cells[0][0].select();

        this._gameBoard.addEventListener('valueEntered', valueEntered.bind(this));

        this._gameBoard.addEventListener('batchValueEntered', batchValueEntered.bind(this));

        this._gameBoard.addEventListener('valueCleared', valueCleared.bind(this));

        this._gameBoard.addEventListener('batchValueCleared', batchValueCleared.bind(this));

        this._gameBoard.addEventListener('startingConfigurationSaved', startingConfigurationSaved.bind(this));

        this._gameBoard.addEventListener('startingConfigurationDiscarded', startingConfigurationDiscarded.bind(this));

        this._gameBoard.addEventListener("clash", clashRouter.bind(this));

        this._gameBoard.addEventListener("gameComplete", gameComplete.bind(this));

        this._keyPressRouter = keyPressRouter.bind(this);

        window.addEventListener("keydown", this._keyPressRouter, false);

    };

    Sudoku.GameBoard3D.cellSize = 300;

    Sudoku.GameBoard3D.cellSpacing = 20;

    Sudoku.GameBoard3D.subGridSpacing = 40;

    Sudoku.GameBoard3D.prototype = Object.create(THREE.Object3D.prototype);

    Sudoku.GameBoard3D.prototype.select = function(i, j){

        this._cells[i][j].select();

    }

    function valueEntered(event) {

        this._cells[event.i][event.j].valueEntered(event.value);

        return this;

    }

    function batchValueEntered(event) {

        event.batch.forEach(
            function (el, idx, arr) {
                valueEntered.call(this, el);
            },
            this
        );

        return this;

    }

    function valueCleared(event) {

        this._cells[event.i][event.j].valueCleared();

        return this;

    }

    function batchValueCleared(event) {

        event.batch.forEach(
            function (el, idx, arr) {
                valueCleared.call(this, el);
            },
            this
        );

        return this;

    }

    function startingConfigurationSaved(event) {

        var i
            , j
            , n = this._gameBoard.getGameSize()
            , nSqrd = n * n
            , startConf = event.startingConfiguration
            ;

        for (var i = 0, l = startConf.length; i < l; i++) {
            this._cells[startConf[i].i][startConf[i].j].setAsStartingCell();
        }

        i = j = 0;
        while (!this._cells[i][j].select().isSelected()) {
            j++;
            if (j === nSqrd) {
                j = 0;
                i++;
                if (i === nSqrd) {
                    return;
                }
            }
        }

        return this;

    }

    function startingConfigurationDiscarded(event) {

        var startConf = event.startingConfiguration;

        for (var k = 0, l = startConf.length; k < l; k++) {
            this._cells[startConf[k].i][startConf[k].j].unsetAsStartingCell();
        }

        return this;

    }

    function cellSelected(event) {

        if (this._selectedCell !== null) {

            this._selectedCell.deselect();

        }

        this._selectedCell = event.cell;

    }

    function cellDeselected(event) {

        this._selectedCell = null;

    }

    function clashRouter(event) {

        var k
            , l
            , kUpper
            , lUpper
            , n = this._gameBoard.getGameSize()
            , nSqrd = n * n
            , sgb = this._gameBoard.getSubGridBoundsContainingCell(event.i, event.j)
            ;

        if (event.subType === "row") {

            k = event.i;
            l = 0;
            kUpper = k + 1;
            lUpper = nSqrd;

        } else if (event.subType === "column") {

            k = 0;
            l = event.j;
            kUpper = nSqrd;
            lUpper = l + 1;

        } else if (event.subType === "subGrid") {

            k = sgb.iLower;
            l = sgb.jLower;
            kUpper = sgb.iUpper + 1;
            lUpper = sgb.jUpper + 1;

        }

        for (; k < kUpper; k++) {
            for (var tempL = l; tempL < lUpper; tempL++) {
                if (k === event.i && tempL === event.j) {
                    this._cells[k][tempL].clash("Primary");
                } else {
                    this._cells[k][tempL].clash("Secondary");
                }
            }
        }

    }

    function keyPressRouter(event) {

        var n = this._gameBoard.getGameSize()
            , nSqrd = n * n
            , dir
            , val
            , i
            , j
            ;

        if (this._selectedCell === null) {
            return;
        }

        if (event.keyCode >= 37 && event.keyCode <= 40) {
            if (event.keyCode === 37) {
                dir = 'left';
            }
            else if (event.keyCode === 38) {
                dir = 'up';
            }
            else if (event.keyCode === 39) {
                dir = 'right';
            }
            else if (event.keyCode === 40) {
                dir = 'down';
            }
            selectNextAvailableCellInDirection.call(this, dir);
            return;
        }

        val = Sudoku.getTextureIndexFromKeyCode(event.keyCode);
        if (val > 0) {
            this._gameBoard.enterValue(this._selectedCell.i, this._selectedCell.j, val);
        } else if (val === 0) {
            this._gameBoard.clearValue(this._selectedCell.i, this._selectedCell.j);
        }
    }

    function selectNextAvailableCellInDirection(dir) {

        var n = this._gameBoard.getGameSize()
            , nSqrd = n * n
            , idxs = {}
            , iterIdx
            , getIJ
            , firstCount = nSqrd
            , secondCount = nSqrd * nSqrd
            ;

        if (dir === "left" || dir === "right") {
            idxs.first = this._selectedCell.j;
            idxs.second = this._selectedCell.i;
            getIJ = function () {
                return {i:idxs.second, j:idxs.first};
            };
        } else {
            idxs.first = this._selectedCell.i;
            idxs.second = this._selectedCell.j;
            getIJ = function () {
                return {i:idxs.first, j:idxs.second};
            };
        }

        if (dir === "left" || dir === "up") {
            iterIdx = function (idx) {
                return (idx - 1 < 0) ? nSqrd - 1 : idx - 1;
            };
        } else {
            iterIdx = function (idx) {
                return (idx + 1 >= nSqrd) ? 0 : idx + 1;
            };
        }

        do {
            if (!--firstCount) {
                firstCount = nSqrd;
                idxs.second = iterIdx(idxs.second);
                if (!--secondCount) {
                    return;
                }
            }
            idxs.first = iterIdx(idxs.first);
        } while (!this._cells[getIJ().i][getIJ().j].select().isSelected())

    }

    function gameComplete() {

        var n = this._gameBoard.getGameSize()
            , nSqrd = n * n
            ;

        for (var i = 0; i < nSqrd; i++) {
            for (var j = 0; j < nSqrd; j++) {
                this._cells[i][j].gameComplete();
            }
        }

    }

})();


text:
- Класът представлява шаблонен динамичен масив.
- Има канонично представяне, оператор [], за да се държи подобно на масив и някои основни фунцкии за добавяне, изтриване и търсене на елементи.
- Вътрешният буфер се уголемява авоматично ако бъде запълнен.
- Има оператор за отпечатване в output stream.
- Класът разчита на това, че обектите, които съхранява имат канонично представяне.

### 1.1 Някои шаблонни фунцкии от по-висок ред за работа с вектори
- SortVector
    - Получава референция към вектор, comparator фунцкия и има опция да сортира наобратно. Мутира подадения вектор.
- filterVector
    - Получава референция към вектор и филтрираща фунцкия(предикат). НЕ мутира подадения вектор. Проверява предиката за всеки от елементите на вектора и връща НОВ вектор, съставен от елементите на подадения за които предиката е верен.
- mapVector
    - Получава референция към вектор и map фунцкия. Изпълнява функцията върху всеки от елементите на вектори и му присвоява получената стойност. Мутира подадения вектор.
- paramFilterVector
    - Доста подобна на filterVector, но предиката, който получава е двуместен, като първият му аргумент е от типа на елементите във вектора, а втория е произволен тип М. Фунцкията получава и стойност от тип М, която да подава на предиката като 2ри аргумент.

## 2. String
- Основната му идея е да бъде wrapper на буфер от char-ове. Предоставя някои удобни оператори за конкатенация и сравнение, както и оператор за достъп до елемент [].
- Класът има канонично представяне
- Има няколко конструктора, може да бъде конструиран от char*, int, double, Vector<char> или друг стринг.
- Има оператор = както са стрингове, така и за char*.
- Има оператори за четене и писане от поток, като този за четене използва Vector<char> за да може да прочете предварително неизвестно количество информация.

## 3. Movie
- Класът описва филм. Основните данни които съхранява са:
    + Име на филма:
    + Име на режисьора на филма
    + Година на премиерата
    + id за филма, което представлява стринг от името и годината
    + Рейтинг даден от потребителите
    + Дали е римейк на друг филм и евентуално id-то на другия филм
    + Вектор от стрингове с имената на актьорите, които участват в него
    + Жанр
- **Important:** Класът не се нуждае от канонично представяне, защото всичките му член данни ще бъдат добре обработени от default-но създадените оператор = и copy-конструктор.
- Класът има get методи за всичките си член данни
- Има оператори `==` и `!=`, които сравняват по id.
- Има фунцкия за записване във файлов поток.
- Има конструктор, който да извлича член данните от файлов поток и така да създава обекта.
- Има само 2 мутиращи фунцкии:
    + За добавяне на актьор в списъка с актьори
    + За добавяне на потребителски рейтинг
        * Филлмът пази само сумарният рейтинг от потребителите, а не всяка оценка по отделно.

### 3.1. Някои допълнителни фунцкии
- Има няколко compare фунцкии, които сравняват филми по различни член-данни на обектите
- Една map фунцкия, която само принтира обект от тип movie и го връща.
- Оператор за извеждане в поток
- Няколко двуместни предиката, които да се използват с paramFilterVector върху вектор от филми.

## 4. Date
- Класът описва дата с ден, месец и година.
- Конструкторът приема 3те аргумента - ден, месец, година и ги валидира.
    + Ако не са валидни, се вдига corrupted флаг и в датата се записва 1.1.1970
- Има get фунцкии за 3те данни и flag функция `isCorrupted`
- Оператори за вход и изход от поток

## 5. Role
- Енумерация
- Имплементиран е оператор за четене от поток, както и 2 фунцкии за четене и писане за файлов поток.

## 6. Review
- Класът описва потребителско ревю за даден филм.
- Има 3 член данни:
    + id на филма, за който се отнася
    + коментар на потребителя за филма
    + оценка на потребителя за филма
- има get методи за 3-те член данни
- има 2 булеви фунцкии:
    + `addComment`: приема стринг и го задава като коментар, ако такъв още не е даден
    + `addRating`: приема число и го задава като оценка, ако такава още не е дадена
    И двете фунцкии връщат истина при успех и лъжа в противен случай

## 7. MovieStaff
- Класът пази основна информация за участник във филм:
    + Име
    + Рождена дата
    + Вектор от стрингове, в който са записани id-тата на филмите, в които участва
    + Роля
- get методи за член данните
- булева фунцкия `is` която приема роля и проверява дали участникът има тази роля
- Фунцкия за записване във файлов поток
- Конструктор, който приема файлов поток и прочита данните за обекта от там
- Оператор << за отпечатване в поток
- Функция за добавяне на филм във вектора от филми

## 8. User
- Класът предоставя фунцкионалности за работа с потребители
- Пази информация за потребител:
    + потребителско име
    + парола
    + 2 флага за валидиране на името и паролата, които се вдигат автоматично след конструиране или използване на set-методите
    + Вектор от ревюта на филми
- get методи за името и паролата
- set методи за името и паролата
- Фунцкия, която проверява дали user-a е администраторът
- Фунцкия, която сравнява името и паролата на потребителя с подадени такива и връща истина ако и двете съвпадат и лъжа в противен случаи
- Фунцкия за добавяне на коментар за филм
- Фунцкия за добавяне на оценка за филм
        * Ако вече има коментар или оценка, фунцкиите връщат лъжа, тъй като един филм може да бъде коментиран/оценяван само по 1 път
- Фунцкия за записване на обекта във файлов поток
- Конструктор, който приема файлов поток и прочита данните за обекта от там
- Две валидиращи фунцкии, които връщат състоянието на флаговете за името и паролата.
- Булева фунцкия, която приема id на филм и връща истина ако потребителя е коментирал или е дал оценка за този филм
- Фунцкия която приема id на филм и връща оценката на потребителя за филма
- Фунцкия която приема id на филм и връща коментара на потребителя за филма
- Оператор << за отпечатване в поток

## 9. Dispatcher
- Класът, който представлява самата система
- В основният интерфейс на системата влизат няколко функции:
    + start - стартира системата като прочита информацията от файловете
    + shutdown - спира системата като записва информацията във файловете
        * 2-те фунцкии са синхронизирани с булев флаг и не могат да бъдат извикани в грешна последователност
    + registerUser - комуникира с потребителя, за да изпълни регистрация
    + login - комуникира с потребителя, за да го логне в ситемата
        * При 3 неуспешни опита връща false, при успех - true
    + logut
    + 3 булеви фунцкии за проверка на логнатия потребител - дали е администратор, дали има логнат потребител, дали няма логнат потребител
    + `addMovie` - комуникира с администарторът, за да добави филм към колекцията
    + `review` - комуникира с потребителя, за да добави коментар или рейтинг за филм
    + `sortMovies` - комуникира с потребителя и му показва сортираната колекция от филми според неговия избор
    + `searchRemakes` - търси и показва римейк филмите на избран филм
    + `searchReviews` търси и показва ревютата на избран филм
    + `filterMovies` - филтрира филмите според избран от потребителя филтър и въведена от него стойност. Предоставя фунцкионалност за търсене. Филтрите се наслагват и по този начин търсенето може да е по повече от един филтър.


text:
package com.stratio.ingestion.source.redis;

public class RedisConstants {
	public static final String CONF_HOST = "host";
    public static final String CONF_PORT = "port";
    public static final String CONF_CHANNELS = "subscribe";
    public static final String CONF_PCHANNELS = "psubscribe";
    public static final String CONF_CHARSET = "charset";

    public static final String CONF_TESTONBORROW = "testOnBorrow";
    public static final String CONF_MAXTOTAL = "maxTotal";
    public static final String CONF_MAXIDLE= "maxIdle";
    public static final String CONF_MINIDLE = "minIdle";
    public static final String CONF_MAXWAITINMILLIS = "maxWaitInMillis";
    public static final String CONF_TESTWHILEIDLE = "testWhileIdle";
    public static final String CONF_TESTONRETURN = "testOnReturn";
    public static final String CONF_MINEVICTABLEIDLETIMEINMILLIS = "minEvictableIdleTimeInMillis";
    public static final String CONF_TIMEBETWEETNEVICTIONRUNSMILLIS = "timeBetweenEvictionRunsMillis";
    public static final String CONF_NUMTESTSPEREVICTIONRUN = "numTestsPerEvictionRun";

    public static final String DEFAULT_HOST = "localhost";
    public static final Integer DEFAULT_PORT = 6379;
    public static final String DEFAULT_CHARSET = "utf-8";

    public static final Boolean DEFAULT_TESTONBORROW = true;
    public static final Integer DEFAULT_MAXTOTAL = 100;
    public static final Integer DEFAULT_MAXIDLE = 10;
    public static final Integer DEFAULT_MINIDLE = 2;
    public static final Integer DEFAULT_MAXWAITINMILLIS = 100;
    public static final Boolean DEFAULT_TESTWHILEIDLE = true;
    public static final Boolean DEFAULT_TESTONRETURN = true;
    public static final Integer DEFAULT_MINEVICTABLEIDLETIMEINMILLIS = 10000;
    public static final Integer DEFAULT_TIMEBETWEETNEVICTIONRUNSMILLIS = 5000;
    public static final Integer DEFAULT_NUMTESTSPEREVICTIONRUN = 10;

}


text:
After lots of discussion and testing, I'm happy to announce a significant
update to the Yesod scaffolded site. You can see some mailing list discussions
on this at:

* [Yesod 1.4 reminder](https://groups.google.com/d/msg/yesodweb/BhUq8wLrhgQ/0_rwAqvEGxEJ)
* [Proposed overhaul to the scaffolding](https://groups.google.com/d/msg/yesodweb/rpuXOKtUj_o/LrRNQJns6noJ)

The newest version of yesod-bin (and all versions going forward) will ship with
this newly minted scaffolding. There is no migration guide for existing sites;
scaffoldings aren't the kind of things to be easily migrated, and all existing
sites will continue to function due to lack of breaking API changes.
Nonetheless, if people are excited enough about these changes that they'd like
to integrate them into their existing sites, please start up a discussion on
the mailing list.

The primary motivation in this change is an overhaul to the settings system.
The new system is much more modular regarding environment variables, config
files, and hard-coded settings. It's also much simpler to determine where a
setting value comes from, and to configure things differently in different
environments. Since I've already described these changes in quite some detail,
I will instead point you to [the second mailing list thread linked
above](https://groups.google.com/d/msg/yesodweb/rpuXOKtUj_o/LrRNQJns6noJ).

To give an example of how this works, take a look at the following lines from
the new `settings.yml` file:

```
host:           "_env:HOST:*4" # any IPv4 host
port:           "_env:PORT:3000"
approot:        "_env:APPROOT:http://localhost:3000"
```

In the old scaffolding, both `PORT` and `APPROOT` were recognized environment
variable names, that would override whatever was defined in `settings.yml`.
However, that overriding occurred in a library (Yesod.Default.Config) and was
not obvious to users, which led to many bug reports/support questions.
Additionally, there was no way to override the host/interface binding via
environment variables. In the new system:

* It's obvious from reading the config file which settings can be overridden via environment variables, and what the names of those variables are.
* It's trivial to change the names, or disable environment variable overriding (e.g., replace the `approot` line with `approot: http://localhost:3000`).
* New arbitrary settings can be added at will, and easily use environment variables to override their values.

The other change is that we've replaced the ad-hoc `Import` prelude replacement
previously found in the scaffolding with ClassyPrelude.Yesod. For users not
interested in classy-prelude, it should be trivial to replace `import
ClassyPrelude.Yesod` with `import Prelude`, `import Yesod`, and whatever else
you want. Greg has also spent quite some time in the past week improving the
documentation for both classy-prelude and mono-traversable, which will help
things out considerably.

Besides that, I've done a bunch of minor maintenance on the scaffolding,
cleaning up import lists, adding some missing documentation, and so on.

Like any new release, it's certainly possible that there are some issues, so if
you notice any, please feel free to bring them up. Also, documentation fixes
are great as well. As always, please send any pull requests against [the
postgres branch of the yesod-scaffold
repo](https://github.com/yesodweb/yesod-scaffold/tree/postgres), from which we
automatically merge changes to all other versions of the scaffolding.


text:
package com.netflix.hystrix.contrib.javanica.test.common.error;

import com.netflix.hystrix.HystrixEventType;
import com.netflix.hystrix.HystrixRequestLog;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.test.common.BasicHystrixTest;
import com.netflix.hystrix.contrib.javanica.test.common.domain.User;
import com.netflix.hystrix.exception.HystrixRuntimeException;
import org.junit.Before;
import org.junit.Test;
import org.mockito.MockitoAnnotations;

import java.util.HashMap;
import java.util.Map;

import static com.netflix.hystrix.contrib.javanica.test.common.CommonUtils.getHystrixCommandByKey;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;

/**
 * Created by dmgcodevil
 */
public abstract class BasicErrorPropagationTest extends BasicHystrixTest {

    private static final String COMMAND_KEY = "getUserById";

    private static final Map<String, User> USERS;

    static {
        USERS = new HashMap<String, User>();
        USERS.put("1", new User("1", "user_1"));
        USERS.put("2", new User("2", "user_2"));
        USERS.put("3", new User("3", "user_3"));
    }

    private UserService userService;

    @MockitoAnnotations.Mock
    private FailoverService failoverService;

    protected abstract UserService createUserService();

    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
        userService = createUserService();
        userService.setFailoverService(failoverService);
    }

    @Test(expected = BadRequestException.class)
    public void testGetUserByBadId() throws NotFoundException {
        try {
            String badId = "";
            userService.getUserById(badId);
        } finally {
            assertEquals(1, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
            com.netflix.hystrix.HystrixInvokableInfo getUserCommand = getHystrixCommandByKey(COMMAND_KEY);
            // will not affect metrics
            assertFalse(getUserCommand.getExecutionEvents().contains(HystrixEventType.FAILURE));
            // and will not trigger fallback logic
            verify(failoverService, never()).getDefUser();
        }
    }

    @Test(expected = NotFoundException.class)
    public void testGetNonExistentUser() throws NotFoundException {
        try {
            userService.getUserById("4"); // user with id 4 doesn't exist
        } finally {
            assertEquals(1, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
            com.netflix.hystrix.HystrixInvokableInfo getUserCommand = getHystrixCommandByKey(COMMAND_KEY);
            // will not affect metrics
            assertFalse(getUserCommand.getExecutionEvents().contains(HystrixEventType.FAILURE));
            // and will not trigger fallback logic
            verify(failoverService, never()).getDefUser();
        }
    }

    @Test // don't expect any exceptions because fallback must be triggered
    public void testActivateUser() throws NotFoundException, ActivationException {
        try {
            userService.activateUser("1"); // this method always throws ActivationException
        } finally {
            assertEquals(1, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
            com.netflix.hystrix.HystrixInvokableInfo activateUserCommand = getHystrixCommandByKey("activateUser");
            // will not affect metrics
            assertTrue(activateUserCommand.getExecutionEvents().contains(HystrixEventType.FAILURE));
            assertTrue(activateUserCommand.getExecutionEvents().contains(HystrixEventType.FALLBACK_SUCCESS));
            // and will not trigger fallback logic
            verify(failoverService, atLeastOnce()).activate();
        }
    }

    @Test(expected = OperationException.class)
    public void testBlockUser() throws NotFoundException, ActivationException, OperationException {
        try {
            userService.blockUser("1"); // this method always throws ActivationException
        } finally {
            assertEquals(2, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
            com.netflix.hystrix.HystrixInvokableInfo activateUserCommand = getHystrixCommandByKey("blockUser");
            // will not affect metrics
            assertTrue(activateUserCommand.getExecutionEvents().contains(HystrixEventType.FAILURE));
            assertTrue(activateUserCommand.getExecutionEvents().contains(HystrixEventType.FALLBACK_FAILURE));
        }
    }

    @Test(expected = NotFoundException.class)
    public void testPropagateCauseException() throws NotFoundException {
        userService.deleteUser("");
    }

    public static class UserService {

        private FailoverService failoverService;

        public void setFailoverService(FailoverService failoverService) {
            this.failoverService = failoverService;
        }

        @HystrixCommand
        public Object deleteUser(String id) throws NotFoundException {
            throw new NotFoundException("");
        }

        @HystrixCommand(
                commandKey = COMMAND_KEY,
                ignoreExceptions = {
                        BadRequestException.class,
                        NotFoundException.class
                },
                fallbackMethod = "fallback")
        public User getUserById(String id) throws NotFoundException {
            validate(id);
            if (!USERS.containsKey(id)) {
                throw new NotFoundException("user with id: " + id + " not found");
            }
            return USERS.get(id);
        }

        @HystrixCommand(
                ignoreExceptions = {BadRequestException.class, NotFoundException.class},
                fallbackMethod = "activateFallback")
        public void activateUser(String id) throws NotFoundException, ActivationException {
            validate(id);
            if (!USERS.containsKey(id)) {
                throw new NotFoundException("user with id: " + id + " not found");
            }
            // always throw this exception
            throw new ActivationException("user cannot be activate");
        }

        @HystrixCommand(
                ignoreExceptions = {BadRequestException.class, NotFoundException.class},
                fallbackMethod = "blockUserFallback")
        public void blockUser(String id) throws NotFoundException, OperationException {
            validate(id);
            if (!USERS.containsKey(id)) {
                throw new NotFoundException("user with id: " + id + " not found");
            }
            // always throw this exception
            throw new OperationException("user cannot be blocked");
        }

        private User fallback(String id) {
            return failoverService.getDefUser();
        }

        private void activateFallback(String id) {
            failoverService.activate();
        }

        @HystrixCommand(ignoreExceptions = {RuntimeException.class})
        private void blockUserFallback(String id) {
            throw new RuntimeOperationException("blockUserFallback has failed");
        }

        private void validate(String val) throws BadRequestException {
            if (val == null || val.length() == 0) {
                throw new BadRequestException("parameter cannot be null ot empty");
            }
        }
    }

    private class FailoverService {
        public User getDefUser() {
            return new User("def", "def");
        }

        public void activate() {
        }
    }

    // exceptions
    private static class NotFoundException extends Exception {
        private NotFoundException(String message) {
            super(message);
        }
    }

    private static class BadRequestException extends RuntimeException {
        private BadRequestException(String message) {
            super(message);
        }
    }

    private static class ActivationException extends Exception {
        private ActivationException(String message) {
            super(message);
        }
    }

    private static class OperationException extends Throwable {
        private OperationException(String message) {
            super(message);
        }
    }

    private static class RuntimeOperationException extends RuntimeException {
        private RuntimeOperationException(String message) {
            super(message);
        }
    }

}


text:
<!DOCTYPE html>

    <title>Source and template binding</title>

    <link href="../../content/shared/styles/examples-offline.css" rel="stylesheet">
    <link href="../../../styles/kendo.common.min.css" rel="stylesheet">
    <link href="../../../styles/kendo.default.min.css" rel="stylesheet">

        Back

            Add a product

                    Name:<input type="text" placeholder="Enter name" data-bind="value: productName" class="name k-textbox"/>

                    Price:<input type="text" placeholder="Enter number" data-bind="value: productPrice" class="k-textbox" />

                    Units in stock:<input type="text" placeholder="Enter number" data-bind="value: productUnitsInStock" class="k-textbox" />

                    <button class="k-button" data-bind="click: addProduct">Add a new product</button>

                    Name
                    Price
                    Units
                    Delete

View source code:

<div id="example">
    <table>
        <thead>
            <tr>
                <th>Name</th>
                <th>Price</th>
                <th>Units</th>
                <th>Delete</th>
            </tr>
        </thead>
        <tbody data-template="row-template" data-bind="source: products"></tbody>
        <tfoot data-template="footer-template" data-bind="source: this"></tfoot>
    </table>

    <div>
        <span>Add a product</span>
        <ul>
            <li>
                <label>Name:<input type="text" placeholder="Enter name" data-bind="value: productName" /></label>
            </li>
            <li>
                <label>Price:<input type="number" placeholder="Enter number" data-bind="value: productPrice" /></label>
            </li>
            <li>
                <label>Units in stock:<input type="number" placeholder="Enter number" data-bind="value: productUnitsInStock" /></label>
            </li>
            <li>
                <button data-bind="click: addProduct">Add a new product</button>
            </li>
        </ul>
    </div>
</div>
<script id="row-template" type="text/x-kendo-template">
    <tr>
        <td data-bind="text: name">
        </td>
        <td>
            #: kendo.toString(get("price"), "C") #
        </td>
        <td data-bind="text: unitsInStock"></td>
        <td><button data-bind="click: deleteProduct">Delete</button></td>
    </tr>
</script>
<script id="footer-template" type="text/x-kendo-template">
    <tr>
        <td>
            Products count: #: total() #
        </td>
        <td>
            Total price: #: totalPrice() #
        </td>
        <td colspan="2">
            Units in stock: #: totalUnitsInStock() #
        </td>
    </tr>
</script>

View model source code:

var viewModel = kendo.observable({
    productName: "Product name",
    productPrice: 10,
    productUnitsInStock: 10,
    addProduct: function() {
        this.get("products").push({
            name: this.get("productName"),
            price: parseFloat(this.get("productPrice")),
            unitsInStock: parseFloat(this.get("productUnitsInStock"))
        });
    },
    deleteProduct: function(e) {
        // the current data item (product) is passed as the "data" field of the event argument
        var product = e.data;

        var products = this.get("products");

        var index = products.indexOf(product);

        // remove the product by using the splice method
        products.splice(index, 1);
    },
    total: function() {
        return this.get("products").length;
    },
    totalPrice: function() {
        var sum = 0;

        $.each(this.get("products"), function(index, product) {
            sum += product.price;
        });

        return sum;
    },
    totalUnitsInStock: function() {
        var sum = 0;

        $.each(this.get("products"), function(index, product) {
            sum += product.unitsInStock;
        });

        return sum;
    },
    products: [
        { name: "Hampton Sofa", price: 989.99, unitsInStock: 39 },
        { name: "Perry Sofa", price: 559.99, unitsInStock: 17 },
        { name: "Donovan Sofa", price: 719.99, unitsInStock: 29 },
        { name: "Markus Sofa", price: 839.99, unitsInStock: 3 }
    ]
});

kendo.bind($("#example"), viewModel);


text:
uv.PieGraph = function (graphdef, config) {
  var self = this;
  uv.Graph.call(self, graphdef, config).setDefaults().init();

  self.radius = Math.min(self.height(), self.width()) * 2 / 5;
  self.center = {
    x : self.width() / 2,
    y : self.height() / 2
  };

  self.category = graphdef.categories[0];

  var data = uv.util.getCategoryData(self.graphdef, [self.category]),
    arcfunc = d3.svg.arc().innerRadius(0).outerRadius(self.radius),
    layout = d3.layout.pie();

  self.chart.data(data);
  self.arcs = self.chart.selectAll('g.arc')
          .data(layout).enter()
          .append('g').classed(uv.constants.classes.arc + uv.util.formatClassName(self.category), true)
          .attr('class', function (d, i){
            return uv.util.getClassName(this, 'cge-' + self.labels[i]);
          })
          .attr('transform', 'translate(' + self.center.x + ',' + self.center.y + ')');

  self.arcs.append('path')
      .attr('d', arcfunc)
      .style('fill', function (d, i) { return uv.util.getColorBand(self.config, i); })
      .style('stroke', self.config.pie.strokecolor)
      .style('stroke-width', self.config.pie.strokewidth)
    .on('mouseover', uv.effects.pie.mouseover(self, self.center, arcfunc, self.config))
    .on('mouseout', uv.effects.pie.mouseout(self, self.center, self.config));

  self.arcs.append('text')
      .attr('transform', function (d) { return 'translate(' + arcfunc.centroid(d) + ')'; })
      .attr('dy', '.35em')
      .attr('text-anchor', 'middle')
      .style('fill', self.config.label.showlabel ? self.config.donut.fontfill : 'none')
      .style('font-family', self.config.pie.fontfamily)
      .style('font-size', self.config.pie.fontsize)
      .style('font-weight', self.config.pie.fontweight)
      .style('font-variant', self.config.pie.fontvariant)
      .text(function (d) { return uv.util.getLabelValue(self, d); });

  self.arcs.append('svg:title')
    .text(function (d, i) { return uv.util.getTooltipText(self, self.category, self.labels[i], d);});

};

uv.PieGraph.prototype = uv.util.inherits(uv.Graph);

uv.PieGraph.prototype.setDefaults = function () {
  var self = this;
  self.graphdef.stepup = false;
  self.config.legend.legendtype = 'labels';
  return this;
};


text:
package kieker.tools.slastic.metamodel.componentAssembly;

import kieker.tools.slastic.metamodel.core.FQNamedEntity;

import kieker.tools.slastic.metamodel.typeRepository.ComponentType;

import org.eclipse.emf.common.util.EList;

/**
 *
 * A representation of the model object 'Assembly Component'.
 *
 *
 *

 * The following features are supported:
 *

 *
{@link kieker.tools.slastic.metamodel.componentAssembly.AssemblyComponent#getComponentType Component Type}

 *
{@link kieker.tools.slastic.metamodel.componentAssembly.AssemblyComponent#getProvidingConnectors Providing Connectors}

 *
{@link kieker.tools.slastic.metamodel.componentAssembly.AssemblyComponent#getRequiringConnectors Requiring Connectors}

 *

 *

 *
 * @see kieker.tools.slastic.metamodel.componentAssembly.ComponentAssemblyPackage#getAssemblyComponent()
 * @model
 * @generated
 */
public interface AssemblyComponent extends FQNamedEntity {
	/**
	 * Returns the value of the 'Component Type' reference.
	 *
	 *

	 * If the meaning of the 'Component Type' reference isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Component Type' reference.
	 * @see #setComponentType(ComponentType)
	 * @see kieker.tools.slastic.metamodel.componentAssembly.ComponentAssemblyPackage#getAssemblyComponent_ComponentType()
	 * @model required="true" ordered="false"
	 * @generated
	 */
	ComponentType getComponentType();

	/**
	 * Sets the value of the '{@link kieker.tools.slastic.metamodel.componentAssembly.AssemblyComponent#getComponentType Component Type}' reference.
	 *
	 *
	 * @param value the new value of the 'Component Type' reference.
	 * @see #getComponentType()
	 * @generated
	 */
	void setComponentType(ComponentType value);

	/**
	 * Returns the value of the 'Providing Connectors' reference list.
	 * The list contents are of type {@link kieker.tools.slastic.metamodel.componentAssembly.AssemblyComponentConnector}.
	 * It is bidirectional and its opposite is '{@link kieker.tools.slastic.metamodel.componentAssembly.AssemblyComponentConnector#getRequiringComponent Requiring Component}'.
	 *
	 *

	 * If the meaning of the 'Providing Connectors' reference list isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Providing Connectors' reference list.
	 * @see kieker.tools.slastic.metamodel.componentAssembly.ComponentAssemblyPackage#getAssemblyComponent_ProvidingConnectors()
	 * @see kieker.tools.slastic.metamodel.componentAssembly.AssemblyComponentConnector#getRequiringComponent
	 * @model opposite="requiringComponent" ordered="false"
	 * @generated
	 */
	EList<AssemblyComponentConnector> getProvidingConnectors();

	/**
	 * Returns the value of the 'Requiring Connectors' reference list.
	 * The list contents are of type {@link kieker.tools.slastic.metamodel.componentAssembly.AssemblyComponentConnector}.
	 * It is bidirectional and its opposite is '{@link kieker.tools.slastic.metamodel.componentAssembly.AssemblyComponentConnector#getProvidingComponent Providing Component}'.
	 *
	 *

	 * If the meaning of the 'Requiring Connectors' reference list isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Requiring Connectors' reference list.
	 * @see kieker.tools.slastic.metamodel.componentAssembly.ComponentAssemblyPackage#getAssemblyComponent_RequiringConnectors()
	 * @see kieker.tools.slastic.metamodel.componentAssembly.AssemblyComponentConnector#getProvidingComponent
	 * @model opposite="providingComponent" ordered="false"
	 * @generated
	 */
	EList<AssemblyComponentConnector> getRequiringConnectors();

} // AssemblyComponent


text:
var app = angular.module('app', ['ngRoute']);

//Create our 404 handler
app.config(['$routeProvider', function ($routeProvider) {
  $routeProvider.otherwise({
    controller: 'Error404Ctrl',
    controllerAs: 'vm',
    templateUrl: 'errors/404/error-404.html'
  });
}]);


text:
module BeachApiCore
  class Role < ApplicationRecord
    has_many :assignments, inverse_of: :role, dependent: :destroy

    validates :name, presence: true, uniqueness: true

    acts_as_downcasable_on :name
    acts_as_strippable_on :name

    %i(admin developer user editor scientist).each do |basic_role|
      define_method "#{basic_role}?" do
        name == basic_role.to_s
      end
    end

    class << self
      %i(admin developer user editor scientist).each do |basic_role|
        define_method basic_role do
          find_by(name: basic_role)
        end
      end
    end
  end
end


text:
<?php
/**
 * 单例
 */

namespace LanguageStatement\DesignModel\Singleton;

class Singleton
{
    public static $instance=null;
    //java 多线程下的单例
    //public static $instance=new Singleton();

    private function __construct()
    {

    }

    public static function getInstance(){
        if(self::$instance===null){
            self::$instance=new Singleton();
            //java 多线程下的单例
//            synchronized (Singleton.class) {
//                if (instance == null) {
//                    instance = new Singleton();
//                }
//            }
        }
        return self::$instance;
    }

    //动态资源
    public $asset;
    public function setAsset($param){$this->asset=$param;}
    public function getAsset(){return $this->asset;}
}