text:
/**
 * Module dependencies.
 */

var Lexer = require('./lexer')
  , nodes = require('./nodes')
  , utils = require('./utils')
  , filters = require('./filters')
  , path = require('path')
  , extname = path.extname;

/**
 * Initialize `Parser` with the given input `str` and `filename`.
 *
 * @param {String} str
 * @param {String} filename
 * @param {Object} options
 * @api public
 */

var Parser = exports = module.exports = function Parser(str, filename, options){
  this.input = str;
  this.lexer = new Lexer(str, options);
  this.filename = filename;
  this.blocks = {};
  this.mixins = {};
  this.options = options;
  this.contexts = [this];
};

/**
 * Tags that may not contain tags.
 */

var textOnly = exports.textOnly = ['script', 'style'];

/**
 * Parser prototype.
 */

Parser.prototype = {

  /**
   * Push `parser` onto the context stack,
   * or pop and return a `Parser`.
   */

  context: function(parser){
    if (parser) {
      this.contexts.push(parser);
    } else {
      return this.contexts.pop();
    }
  },

  /**
   * Return the next token object.
   *
   * @return {Object}
   * @api private
   */

  advance: function(){
    return this.lexer.advance();
  },

  /**
   * Skip `n` tokens.
   *
   * @param {Number} n
   * @api private
   */

  skip: function(n){
    while (n--) this.advance();
  },

  /**
   * Single token lookahead.
   *
   * @return {Object}
   * @api private
   */

  peek: function() {
    return this.lookahead(1);
  },

  /**
   * Return lexer lineno.
   *
   * @return {Number}
   * @api private
   */

  line: function() {
    return this.lexer.lineno;
  },

  /**
   * `n` token lookahead.
   *
   * @param {Number} n
   * @return {Object}
   * @api private
   */

  lookahead: function(n){
    return this.lexer.lookahead(n);
  },

  /**
   * Parse input returning a string of js for evaluation.
   *
   * @return {String}
   * @api public
   */

  parse: function(){
    var block = new nodes.Block, parser;
    block.line = this.line();

    while ('eos' != this.peek().type) {
      if ('newline' == this.peek().type) {
        this.advance();
      } else {
        block.push(this.parseExpr());
      }
    }

    if (parser = this.extending) {
      this.context(parser);
      var ast = parser.parse();
      this.context();

      // hoist mixins
      for (var name in this.mixins)
        ast.unshift(this.mixins[name]);
      return ast;
    }

    return block;
  },

  /**
   * Expect the given type, or throw an exception.
   *
   * @param {String} type
   * @api private
   */

  expect: function(type){
    if (this.peek().type === type) {
      return this.advance();
    } else {
      throw new Error('expected "' + type + '", but got "' + this.peek().type + '"');
    }
  },

  /**
   * Accept the given `type`.
   *
   * @param {String} type
   * @api private
   */

  accept: function(type){
    if (this.peek().type === type) {
      return this.advance();
    }
  },

  /**
   *   tag
   * | doctype
   * | mixin
   * | include
   * | filter
   * | comment
   * | text
   * | each
   * | code
   * | yield
   * | id
   * | class
   * | interpolation
   */

  parseExpr: function(){
    switch (this.peek().type) {
      case 'tag':
        return this.parseTag();
      case 'mixin':
        return this.parseMixin();
      case 'block':
        return this.parseBlock();
      case 'case':
        return this.parseCase();
      case 'when':
        return this.parseWhen();
      case 'default':
        return this.parseDefault();
      case 'extends':
        return this.parseExtends();
      case 'include':
        return this.parseInclude();
      case 'doctype':
        return this.parseDoctype();
      case 'filter':
        return this.parseFilter();
      case 'comment':
        return this.parseComment();
      case 'text':
        return this.parseText();
      case 'each':
        return this.parseEach();
      case 'code':
        return this.parseCode();
      case 'call':
        return this.parseCall();
      case 'interpolation':
        return this.parseInterpolation();
      case 'yield':
        this.advance();
        var block = new nodes.Block;
        block.yield = true;
        return block;
      case 'id':
      case 'class':
        var tok = this.advance();
        this.lexer.defer(this.lexer.tok('tag', 'div'));
        this.lexer.defer(tok);
        return this.parseExpr();
      default:
        throw new Error('unexpected token "' + this.peek().type + '"');
    }
  },

  /**
   * Text
   */

  parseText: function(){
    var tok = this.expect('text');
    var node = new nodes.Text(tok.val);
    node.line = this.line();
    return node;
  },

  /**
   *   ':' expr
   * | block
   */

  parseBlockExpansion: function(){
    if (':' == this.peek().type) {
      this.advance();
      return new nodes.Block(this.parseExpr());
    } else {
      return this.block();
    }
  },

  /**
   * case
   */

  parseCase: function(){
    var val = this.expect('case').val;
    var node = new nodes.Case(val);
    node.line = this.line();
    node.block = this.block();
    return node;
  },

  /**
   * when
   */

  parseWhen: function(){
    var val = this.expect('when').val
    return new nodes.Case.When(val, this.parseBlockExpansion());
  },

  /**
   * default
   */

  parseDefault: function(){
    this.expect('default');
    return new nodes.Case.When('default', this.parseBlockExpansion());
  },

  /**
   * code
   */

  parseCode: function(){
    var tok = this.expect('code');
    var node = new nodes.Code(tok.val, tok.buffer, tok.escape);
    var block;
    var i = 1;
    node.line = this.line();
    while (this.lookahead(i) && 'newline' == this.lookahead(i).type) ++i;
    block = 'indent' == this.lookahead(i).type;
    if (block) {
      this.skip(i-1);
      node.block = this.block();
    }
    return node;
  },

  /**
   * comment
   */

  parseComment: function(){
    var tok = this.expect('comment');
    var node;

    if ('indent' == this.peek().type) {
      node = new nodes.BlockComment(tok.val, this.block(), tok.buffer);
    } else {
      node = new nodes.Comment(tok.val, tok.buffer);
    }

    node.line = this.line();
    return node;
  },

  /**
   * doctype
   */

  parseDoctype: function(){
    var tok = this.expect('doctype');
    var node = new nodes.Doctype(tok.val);
    node.line = this.line();
    return node;
  },

  /**
   * filter attrs? text-block
   */

  parseFilter: function(){
    var tok = this.expect('filter');
    var attrs = this.accept('attrs');
    var block;

    if ('indent' == this.peek().type) {
      this.lexer.pipeless = true;
      block = this.parseTextBlock();
      this.lexer.pipeless = false;
    } else block = new nodes.Block;

    var node = new nodes.Filter(tok.val, block, attrs && attrs.attrs);
    node.line = this.line();
    return node;
  },

  /**
   * each block
   */

  parseEach: function(){
    var tok = this.expect('each');
    var node = new nodes.Each(tok.code, tok.val, tok.key);
    node.line = this.line();
    node.block = this.block();
    if (this.peek().type == 'code' && this.peek().val == 'else') {
      this.advance();
      node.alternative = this.block();
    }
    return node;
  },

  /**
   * Resolves a path relative to the template for use in
   * includes and extends
   *
   * @param {String}  path
   * @param {String}  purpose  Used in error messages.
   * @return {String}
   * @api private
   */

  resolvePath: function (path, purpose) {
    var p = require('path');
    var dirname = p.dirname;
    var basename = p.basename;
    var join = p.join;

    if (path[0] !== '/' && !this.filename)
      throw new Error('the "filename" option is required to use "' + purpose + '" with "relative" paths');

    if (path[0] === '/' && !this.options.basedir)
      throw new Error('the "basedir" option is required to use "' + purpose + '" with "absolute" paths');

    path = join(path[0] === '/' ? this.options.basedir : dirname(this.filename), path);

    if (basename(path).indexOf('.') === -1) path += '.jade';

    return path;
  },

  /**
   * 'extends' name
   */

  parseExtends: function(){
    var fs = require('fs');

    var path = this.resolvePath(this.expect('extends').val.trim(), 'extends');
    if ('.jade' != path.substr(-5)) path += '.jade';

    var str = fs.readFileSync(path, 'utf8');
    var parser = new Parser(str, path, this.options);

    parser.blocks = this.blocks;
    parser.contexts = this.contexts;
    this.extending = parser;

    // TODO: null node
    return new nodes.Literal('');
  },

  /**
   * 'block' name block
   */

  parseBlock: function(){
    var block = this.expect('block');
    var mode = block.mode;
    var name = block.val.trim();

    block = 'indent' == this.peek().type
      ? this.block()
      : new nodes.Block(new nodes.Literal(''));

    var prev = this.blocks[name] || {prepended: [], appended: []}
    if (prev.mode === 'replace') return this.blocks[name] = prev;

    var allNodes = prev.prepended.concat(block.nodes).concat(prev.appended);

    switch (mode) {
      case 'append':
        prev.appended = prev.parser === this ?
                        prev.appended.concat(block.nodes) :
                        block.nodes.concat(prev.appended);
        break;
      case 'prepend':
        prev.prepended = prev.parser === this ?
                         block.nodes.concat(prev.prepended) :
                         prev.prepended.concat(block.nodes);
        break;
    }
    block.nodes = allNodes;
    block.appended = prev.appended;
    block.prepended = prev.prepended;
    block.mode = mode;
    block.parser = this;

    return this.blocks[name] = block;
  },

  /**
   * include block?
   */

  parseInclude: function(){
    var fs = require('fs');

    var path = this.resolvePath(this.expect('include').val.trim(), 'include');

    // non-jade
    if ('.jade' != path.substr(-5)) {
      var str = fs.readFileSync(path, 'utf8').replace(/\r/g, '');
      var ext = extname(path).slice(1);
      if (filters.exists(ext)) str = filters(ext, str, { filename: path });
      return new nodes.Literal(str);
    }

    var str = fs.readFileSync(path, 'utf8');
    var parser = new Parser(str, path, this.options);
    parser.blocks = utils.merge({}, this.blocks);

    parser.mixins = this.mixins;

    this.context(parser);
    var ast = parser.parse();
    this.context();
    ast.filename = path;

    if ('indent' == this.peek().type) {
      ast.includeBlock().push(this.block());
    }

    return ast;
  },

  /**
   * call ident block
   */

  parseCall: function(){
    var tok = this.expect('call');
    var name = tok.val;
    var args = tok.args;
    var mixin = new nodes.Mixin(name, args, new nodes.Block, true);

    this.tag(mixin);
    if (mixin.code) {
      mixin.block.push(mixin.code);
      mixin.code = null;
    }
    if (mixin.block.isEmpty()) mixin.block = null;
    return mixin;
  },

  /**
   * mixin block
   */

  parseMixin: function(){
    var tok = this.expect('mixin');
    var name = tok.val;
    var args = tok.args;
    var mixin;

    // definition
    if ('indent' == this.peek().type) {
      mixin = new nodes.Mixin(name, args, this.block(), false);
      this.mixins[name] = mixin;
      return mixin;
    // call
    } else {
      return new nodes.Mixin(name, args, null, true);
    }
  },

  /**
   * indent (text | newline)* outdent
   */

  parseTextBlock: function(){
    var block = new nodes.Block;
    block.line = this.line();
    var spaces = this.expect('indent').val;
    if (null == this._spaces) this._spaces = spaces;
    var indent = Array(spaces - this._spaces + 1).join(' ');
    while ('outdent' != this.peek().type) {
      switch (this.peek().type) {
        case 'newline':
          this.advance();
          break;
        case 'indent':
          this.parseTextBlock().nodes.forEach(function(node){
            block.push(node);
          });
          break;
        default:
          var text = new nodes.Text(indent + this.advance().val);
          text.line = this.line();
          block.push(text);
      }
    }

    if (spaces == this._spaces) this._spaces = null;
    this.expect('outdent');
    return block;
  },

  /**
   * indent expr* outdent
   */

  block: function(){
    var block = new nodes.Block;
    block.line = this.line();
    this.expect('indent');
    while ('outdent' != this.peek().type) {
      if ('newline' == this.peek().type) {
        this.advance();
      } else {
        block.push(this.parseExpr());
      }
    }
    this.expect('outdent');
    return block;
  },

  /**
   * interpolation (attrs | class | id)* (text | code | ':')? newline* block?
   */

  parseInterpolation: function(){
    var tok = this.advance();
    var tag = new nodes.Tag(tok.val);
    tag.buffer = true;
    return this.tag(tag);
  },

  /**
   * tag (attrs | class | id)* (text | code | ':')? newline* block?
   */

  parseTag: function(){
    // ast-filter look-ahead
    var i = 2;
    if ('attrs' == this.lookahead(i).type) ++i;

    var tok = this.advance();
    var tag = new nodes.Tag(tok.val);

    tag.selfClosing = tok.selfClosing;

    return this.tag(tag);
  },

  /**
   * Parse tag.
   */

  tag: function(tag){
    var dot;

    tag.line = this.line();

    var seenAttrs = false;
    // (attrs | class | id)*
    out:
      while (true) {
        switch (this.peek().type) {
          case 'id':
          case 'class':
            var tok = this.advance();
            tag.setAttribute(tok.type, "'" + tok.val + "'");
            continue;
          case 'attrs':
            if (seenAttrs) {
              console.warn('You should not have jade tags with multiple attributes.');
            }
            seenAttrs = true;
            var tok = this.advance()
              , obj = tok.attrs
              , escaped = tok.escaped
              , names = Object.keys(obj);

            if (tok.selfClosing) tag.selfClosing = true;

            for (var i = 0, len = names.length; i < len; ++i) {
              var name = names[i]
                , val = obj[name];
              tag.setAttribute(name, val, escaped[name]);
            }
            continue;
          default:
            break out;
        }
      }

    // check immediate '.'
    if ('.' == this.peek().val) {
      dot = tag.textOnly = true;
      this.advance();
    }

    // (text | code | ':')?
    switch (this.peek().type) {
      case 'text':
        tag.block.push(this.parseText());
        break;
      case 'code':
        tag.code = this.parseCode();
        break;
      case ':':
        this.advance();
        tag.block = new nodes.Block;
        tag.block.push(this.parseExpr());
        break;
      case 'newline':
      case 'indent':
      case 'outdent':
      case 'eos':
        break;
      default:
        throw new Error('Unexpected token `' + this.peek().type + '` expected `text`, `code`, `:`, `newline` or `eos`')
    }

    // newline*
    while ('newline' == this.peek().type) this.advance();

    tag.textOnly = tag.textOnly || ~textOnly.indexOf(tag.name);

    // script special-case
    if ('script' == tag.name) {
      var type = tag.getAttribute('type');
      if (!dot && type && 'text/javascript' != type.replace(/^['"]|['"]$/g, '')) {
        tag.textOnly = false;
      }
    }

    // block?
    if ('indent' == this.peek().type) {
      if (tag.textOnly) {
        if (!dot) {
          console.warn(this.filename + ', line ' + this.peek().line + ':')
          console.warn('Implicit textOnly for `script` and `style` is deprecated.  Use `script.` or `style.` instead.');
        }
        this.lexer.pipeless = true;
        tag.block = this.parseTextBlock();
        this.lexer.pipeless = false;
      } else {
        var block = this.block();
        if (tag.block) {
          for (var i = 0, len = block.nodes.length; i < len; ++i) {
            tag.block.push(block.nodes[i]);
          }
        } else {
          tag.block = block;
        }
      }
    }

    return tag;
  }
};


text:
using System;
using System.Collections.Generic;
using Fleck;
using PropOhGate.Send;

namespace PropOhGate.WebSockets.Send
{
    public class WebSocketSender : ISender
    {
        private readonly object _lockObject = new object();

        public WebSocketSender(IWebSocketConnection connection, string repositoryHash)
        {
            RepositoryHash = repositoryHash;
            Connection = connection;
        }

        public string RepositoryHash
        {
            get;
            private set;
        }

        public IWebSocketConnection Connection
        {
            get;
            private set;
        }

        public IDisposable Subscription
        {
            get;
            set;
        }

        public void Update(IList<byte[]> data)
        {
            lock (_lockObject)
            {
                foreach (var d in data)
                {
                    if (Connection.IsAvailable)
                    {
                        Connection.Send(d);
                    }
                }
            }
        }

        public void Update(byte[] data)
        {
            lock (_lockObject)
            {
                if (Connection.IsAvailable)
                {
                    Connection.Send(data);
                }
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
Auto-Scaling Layouts for Android.

        Android studio users import release/AutoScalingLayout.aar .

        Eclipse users import release/AutoScalingLayout.jar, and copy attr.xml into value folder.

------------

Replace the Layout:
============
All we need is to replace the root layouts required auto-scaling, the child layouts will also achieve auto-scaling.

Original layout  | AutoScalingLayout
------------- | -------------
RelativeLayout  | ASRelativeLayout
LinearLayout  | ASLinearLayout
FrameLayout  | ASFrameLayout

For now the three layouts above are supported.

Add the attribute:
============

designWidth and designHeight are the screen sizes you are using when you are designing the GUI in the xml editor. For instance, I use Nexus 4 as my design device (I treat all the devices as Nexus 4), so the generic screen size converting to dp is 384dp and 575dp (exclude the statebar and the actionbar).

autoScaleEnable use to enable/disable scaling.

autoScaleType can be "fitInside", "fitWidth" and "fitHeight"

```
<me.dreamheart.autoscalinglayout.ASRelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:custom="http://schemas.android.com/apk/res-auto"
    custom:designWidth="384dp"
    custom:designHeight="575dp"
    custom:autoScaleEnable="true"
    custom:autoScaleType="fitInside"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".LoginActivity"
    android:background="@drawable/login_bg"
    >
```

```
    xmlns:custom="http://schemas.android.com/apk/res-auto"
    custom:designWidth="384dp"
    custom:designHeight="575dp"
    custom:autoScaleEnable="true"
    custom:autoScaleType="fitInside"
```

1. designWidth and designHeight are very import. If you assign wrong values, you would not see the expected layouts.
2. The unit used in the xml GUI editor should keep constant. For example, if you use dp for designWidth and designHeight, all the unit of the child views has to be dp, even the font size can not be sp, so as px, pt. If you just want to copy the pixel values given by GUI, just use px for all components.
3. When applying AutoScalingLayout, the screen will keep the aspect ratio of designWidth and designHeight, so don't worry about turning square layouts into rectangle unexpectedly.


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Demo 03 - Module</title>
  <link rel="stylesheet" href="/bower_components/bootstrap/dist/css/bootstrap.min.css" media="all">
  <link rel="stylesheet" href="/bower_components/bootstrap/dist/css/bootstrap-theme.min.css" media="all">
  <link rel="stylesheet" href="/bower_components/highlightjs/styles/monokai.css" media="all">

Routing Exemple

app.js

var myApp = angular.module('myApp', ['ngRoute']);

myApp.config(['$routeProvider', function($routeProvider) {
  $routeProvider
    .when('/', {
      templateUrl: '/demos/routing/pages/home.html',
    })
    .when('/page2', {
      templateUrl: '/demos/routing/pages/page2.html'
    })
    .when('/the_end', {
      templateUrl: '/demos/routing/pages/the_end.html'
    });
}]);

index.html

<div ng-view></div>


text:
WinRM-config Cookbook
=====================
[![Cookbook Version][cookbook_version]][cookbook]
[![Build Status][build_status]][build_status]
[![License][license]][license]

Configure WinRM service and client.

Requirements
------------
This cookbook requires Chef 12.1+ and the windows cookbook v2.10.

### Platforms
This cookbook only supports the following platforms:

* Windows Server 2008 (R1, R2)
* Windows Server 2012 (R1, R2)

Usage
-----

Place an explicit dependency on this cookbook (using depends in the cookbook's metadata.rb)
from any cookbook where you would like to use the winrm-config-specific resources/providers
that ship with this cookbook.

```ruby
depends 'winrm-config'
```

Then include the recipes you want, or use one the LWRP provided.
The default recipe, should setup a working WinRM environment.

Resources
---------------------

## listener

### Actions
Action    | Description
----------|-------------------------------------------------
configure | Create or update the specified WinRM listener
delete    | Delete the specified WinRM listener if it exists

### Properties
Property               | Description                                              | Type                    | Default
-----------------------|----------------------------------------------------------|-------------------------|---------
name                   | Name of the resource                                     | String                  |
address                | Address on which the service is configured to listen     | String                  | `*`
certificate_thumbprint | Thumbprint of the certificate to use with HTTPS transport| String                  | ``
enabled                | Whether the current listener should be enabled or not    | TrueClass, FalseClass   | `true`
hostname               | Hostname of the server where the listener is configured  | String                  | ``
port                   | Port on which the service is configured to listen        | Fixnum                  | `5985`
transport              | Transport used over the with WS-Management protocol      | Symbol
:HTTP,:HTTPS | `:HTTP`
url_prefix             | URL prefix on which to accept HTTP or HTTPS requests     | String                  | `wsman`

## service_certmapping
This provider allows to configure or delete a WinRM user <-> certificate mapping.

**NOTE:** The user password cannot contain a double quote `"`, due to the usage of `winrm.vbs` (see [#8][quote_issue])

### Actions
Action    | Description
----------|------------------------------------------------------------
configure | Create or update the specified WinRM certificate mapping
delete    | Delete the specified WinRM certificate mapping if it exists

### Properties
Property  | Description                                               | Type                  | Default
----------|-----------------------------------------------------------|-----------------------|---------
name      | Name of the resource                                      | String                |
enabled   | Whether the current certificate mapping is enabled or not | TrueClass, FalseClass | `true`
issuer    | Thumbprint of the issuer of theclient certificate         | String                |
password  | Password of the local user for processing the request     | String                |
subject   | Subject field of the client certificate                   | String                | `*`
uri       | The URI or URI prefix for which this mapping applies      | String                | `*`
username  | Local username for processing the request                 | String                |

Recipes
-------

## winrm-config::client
Configures all WinRM client settings via registry keys, then performs a restart of the WinRM windows service.

### Attributes
WinRM client settings are configurable via `node['winrm_config']['client']` attributes, which follows the [msdn documentation][client_config].

Attribute        | Description                                               | Type                  | Default
-----------------|-----------------------------------------------------------|-----------------------|---------
AllowUnencrypted | Allow unencrypted communication with WinRM service        | TrueClass, FalseClass | `false`
Basic            | Allow the client to use `Basic authentication`            | TrueClass, FalseClass | `true`
Certificate      | Allow the client tu use `certificate authentication`      | TrueClass, FalseClass | `true`
CredSSP          | Allow the client tu use `CredSSP authentication`          | TrueClass, FalseClass | `false`
Digest           | Allow the client to use `Digest authentication`           | TrueClass, FalseClass | `true`
Kerberos         | Allow the client to use `Kerberos authentication`         | TrueClass, FalseClass | `true`
Negotiate        | Allow the client to use `Negotiate authentication`        | TrueClass, FalseClass | `true`
NetworkDelayms   | Time in milliseconds to accomodate to the network delay   | String                | `5000`
TrustedHosts     | List of trusted remote computer                           | String                | ``
URLPrefix        | URL prefix on which to accept HTTP or HTTPS requests      | String                | `wsman`

Default ports used for either HTTP or HTTPs can be configured via `node['winrm_config']['client']['DefaultPorts']`

Attribute | Description                                               | Type   | Default
----------|-----------------------------------------------------------|--------|---------
HTTP      | The ports used by the client for HTTP                     | Fixnum | `5985`
HTTPS     | The ports used by the client for HTTPS                    | Fixnum | `5986`

## winrm-config::default
A convenience recipe that include the following recipes to enable a default WinRM working service:

* `winrm-config::windows_service`
* `winrm-config::protocol`
* `winrm-config::client`
* `winrm-config::listeners`
* `winrm-config::service`
* `winrm-config::winrs`

## winrm-config::listeners
A convenience recipe to defines WinRM listeners via registry keys, then
performs a restart of the WinRM windows service.

### Attributes
You can define multiples listener via the `node['winrm_config']['listeners']`
hash, following the [msdn documentation][listener_config] for each entry.

Attribute             | Description                                              | Type                    | Default
----------------------|----------------------------------------------------------|-------------------------|---------
Address               | Address on which the service is configured to listen     | String                  | `*`
CertificateThumbprint | Thumbprint of the certificate to use with HTTPS transport| String                  | ``
Enabled               | Whether the current listener should be enabled or not    | TrueClass, FalseClass   | `true`
Hostname              | Hostname of the server where the listener is configured  | String                  | ``
Port                  | Port on which the service is configured to listen        | Fixnum                  | `5985`
Transport             | Transport used over the with WS-Management protocol      | Symbol
:HTTP,:HTTPS | `:HTTP`
URLPrefix             | URL prefix on which to accept HTTP or HTTPS requests     | String                  | `wsman`

## winrm-config::protocol
Configures WinRM protocol settings via registry key, then preforms a restart
of the WinRM windows service.

### Attributes
WinRM protocol settings attributes are accessible via `node['winrm_config']['protocol']`,
following the [msdn documentation][protocol_config].

Attribute         | Description                                              | Type   | Default
------------------|----------------------------------------------------------|--------|---------
MaxEnvelopeSizekb | The maximum SOAP data in kilobytes                       | Fixnum | `150`
MaxTimeoutms      | The maximum request time-out in milliseconds             | Fixnum | `60 000`
MaxBatchItems     | The maximum number of elements composing a Pull response | Fixnum | `32 000`

## winrm-config::service
Configures all WinRM service settings via registry keys, then performs a
restart of the WinRM windows service.

### Attributes
WinRM service settings are configurable via `node['winrm_config']['service']`
attributes, which follows the [msdn documentation][service_config].

Attribute                        | Description                                                              | Type                  | Default
---------------------------------|--------------------------------------------------------------------------|-----------------------|---------
AllowUnencrypted                 | Allow unencrypted communication with clients                             | TrueClass, FalseClass | `false`
Basic                            | Allow the service to use `Basic authentication`                          | TrueClass, FalseClass | `true`
Certificate                      | Allow the service tu use `certificate authentication`                    | TrueClass, FalseClass | `true`
CredSSP                          | Allow the service tu use `CredSSP authentication`                        | TrueClass, FalseClass | `false`
Kerberos                         | Allow the service to use `Kerberos authentication`                       | TrueClass, FalseClass | `true`
Negotiate                        | Allow the service to use `Negotiate authentication`                      | TrueClass, FalseClass | `true`
CbtHardeningLevel                | Policy for channel-binding token requirements in authentication requests | String                | `Relaxed`
EnableCompatibilityHttpListener  | Whether to enable additional compatibility HTTP listener on port 80      | TrueClass, FalseClass | `false`
EnableCompatibilityHttpsListener | Whether to enable additional compatibility HTTPS listener on port 443    | TrueClass, FalseClass | `false`
EnumerationTimeoutms             | Maximum time in milliseconds to accomodate to the network delay          | String                | `5000`
IPv4Filter                       | Filter IPV4 addresses that listeners can use                             | String                | ``
IPv6Filter                       | Filter IPV6 addresses that listeners can use                             | String                | ``
MaxConcurrentOperationsPerUser   | Maximum number of concurrent operations per user                         | String                | `5000`
MaxConnections                   | Maximum number of active requests to process simultaneously              | String                | `5000`
MaxPacketRetrievalTimeSeconds    | Maximum time in seconds to retrieve a packet                             | String                | `5000`
RootSDDL                         | The security descriptor that controls remote access to the listener      | String                | `O:NSG:BAD:P(A;;GA;;;BA)(A;;GR;;;ER)S:P(AU;FA;GA;;;WD)(AU;SA;GWGX;;;WD)`

## winrm-config::windows_service
A simple recipe to enable and start the WinRM Windows service.

## winrm-config::winrs
Configures the WinRS settings via registry keys, then performs a restart of
the WinRM windows service.

### Attributes
WinRS settings are configurable via `node['winrm_config']['winrs']`

Attribute              | Description                                              | Type                  | Default
-----------------------|----------------------------------------------------------|-----------------------|----------
AllowRemoteShellAccess | Allows access to remote shells                           | TrueClass, FalseClass | `true`
IdleTimeout            | Maximum time in milliseconds to keep an idle shell open  | Fixnum                | `180 000`
MaxConcurrentUsers     | Maximum number of users who can concurrently open a shell| Fixnum                | `5`
MaxMemoryPerShellMB    | Maximum amount of memory in megabytes allocated per shell| Fixnum                | `150`
MaxProcessesPerShell   | Maximum number of processes that a shell can start       | Fixnum                | `15`
MaxShellsPerUser       | maximum number of shell a user can open                  | Fixnum                | `5`

Contributing
------------
1. Fork the [repository on Github][repository]
2. Create a named feature branch (like `add_component_x`)
3. Write your change
4. Write tests for your change (if applicable)
5. Run the tests, ensuring they all pass
6. Submit a Pull Request using Github

License and Authors
-------------------
Authors: [Baptiste Courtois][author] ()

```text
Copyright 2015, Criteo.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
```

[author]:             https://github.com/Annih
[repository]:         https://github.com/criteo-cookbooks/winrm-config
[build_status]:       https://api.travis-ci.org/criteo-cookbooks/winrm-config.svg?branch=master
[cookbook_version]:   https://img.shields.io/cookbook/v/winrm-config.svg
[cookbook]:           https://img.shields.io/cookbook/v/winrm-config.svg
[client_config]:      http://msdn.microsoft.com/library/aa384372#WINRM_CLIENT_DEFAULT_CONFIGURATION_SETTINGS
[service_config]:     http://msdn.microsoft.com/library/aa384372#WINRM_SERVICE_DEFAULT_CONFIGURATION_SETTINGS
[license]:            https://img.shields.io/github/license/criteo-cookbooks/winrm-config.svg
[listener_config]:    http://msdn.microsoft.com/library/aa384372#LISTENER_AND_WS-MANAGEMENT_PROTOCOL_DEFAULT_SETTINGS
[protocol_config]:    http://msdn.microsoft.com/library/aa384372#PROTOCOL_DEFAULT_SETTINGS_
[winrs_config]:       http://msdn.microsoft.com/library/aa384372#_WINRS_DEFAULT_CONFIGURATION_SETTINGS
[quote_issue]:        https://github.com/criteo-cookbooks/winrm-config/issues/8


text:
using Algebra.QL.Core.Factory;
using Algebra.QL.TypeCheck.Expr;
using Algebra.QL.TypeCheck.Expr.Literals;
using Algebra.QL.TypeCheck.Stmnt;
using Algebra.QL.TypeCheck.Type;

namespace Algebra.QL.TypeCheck.Factory
{
    public class TypeCheckFactory : IFactory<ITypeCheckStmnt, ITypeCheckExpr, ITypeCheckType>
    {
        public TypeCheckFactory()
        {

        }

        public ITypeCheckType StringType()
        {
            return new StringType();
        }

        public ITypeCheckType IntType()
        {
            return new IntType();
        }

        public ITypeCheckType RealType()
        {
            return new RealType();
        }

        public ITypeCheckType BoolType()
        {
            return new BoolType();
        }

        public ITypeCheckExpr String(string s)
        {
            return new StringLiteral(s);
        }

        public ITypeCheckExpr Int(int i)
        {
            return new IntLiteral(i);
        }

        public ITypeCheckExpr Real(double d)
        {
            return new RealLiteral(d);
        }

        public ITypeCheckExpr Bool(bool b)
        {
            return new BoolLiteral(b);
        }

        public ITypeCheckExpr Variable(string var)
        {
            return new VarExpr(var);
        }

        public ITypeCheckExpr Or(ITypeCheckExpr l, ITypeCheckExpr r)
        {
            return new OrExpr(l, r);
        }

        public ITypeCheckExpr And(ITypeCheckExpr l, ITypeCheckExpr r)
        {
            return new AndExpr(l, r);
        }

        public ITypeCheckExpr Eq(ITypeCheckExpr l, ITypeCheckExpr r)
        {
            return new EqualsExpr(l, r);
        }

        public ITypeCheckExpr NotEq(ITypeCheckExpr l, ITypeCheckExpr r)
        {
            return new NotEqualExpr(l, r);
        }

        public ITypeCheckExpr LessThen(ITypeCheckExpr l, ITypeCheckExpr r)
        {
            return new LessThenExpr(l, r);
        }

        public ITypeCheckExpr GreaterThen(ITypeCheckExpr l, ITypeCheckExpr r)
        {
            return new GreaterThenExpr(l, r);
        }

        public ITypeCheckExpr LessOrEqualTo(ITypeCheckExpr l, ITypeCheckExpr r)
        {
            return new LessOrEqualToExpr(l, r);
        }

        public ITypeCheckExpr GreaterOrEqualTo(ITypeCheckExpr l, ITypeCheckExpr r)
        {
            return new GreaterOrEqualToExpr(l, r);
        }

        public ITypeCheckExpr Add(ITypeCheckExpr l, ITypeCheckExpr r)
        {
            return new AddExpr(l, r);
        }

        public ITypeCheckExpr Subtract(ITypeCheckExpr l, ITypeCheckExpr r)
        {
            return new SubtractExpr(l, r);
        }

        public ITypeCheckExpr Multiply(ITypeCheckExpr l, ITypeCheckExpr r)
        {
            return new MultiplyExpr(l, r);
        }

        public ITypeCheckExpr Divide(ITypeCheckExpr l, ITypeCheckExpr r)
        {
            return new DivideExpr(l, r);
        }

        public ITypeCheckExpr NegateBool(ITypeCheckExpr e)
        {
            return new NegateBoolExpr(e);
        }

        public ITypeCheckExpr NegateNumeric(ITypeCheckExpr e)
        {
            return new NegateNumericExpr(e);
        }

        public ITypeCheckExpr VarDecl(string var, ITypeCheckType t)
        {
            return new VarInitExpr(var, t);
        }

        public ITypeCheckExpr VarAssign(string var, ITypeCheckType t, ITypeCheckExpr e)
        {
            return new VarInitExpr(var, t, e);
        }

        public ITypeCheckExpr IfElse(ITypeCheckExpr toEval, ITypeCheckExpr ifTrue, ITypeCheckExpr ifFalse)
        {
            return new IfElseExpr(toEval, ifTrue, ifFalse);
        }

        public ITypeCheckExpr ExpressionOrder(ITypeCheckExpr e)
        {
            return e; //We can skip this
        }

        public ITypeCheckStmnt Statements(ITypeCheckStmnt l, ITypeCheckStmnt r)
        {
            return new StatementsStmnt(l, r);
        }

        public ITypeCheckStmnt Form(string var, ITypeCheckStmnt s)
        {
            return new FormStmnt(var, s);
        }

        public ITypeCheckStmnt Question(string s, ITypeCheckExpr e)
        {
            return new QuestionStmnt(s, e);
        }

        public ITypeCheckStmnt Label(string s, ITypeCheckExpr e)
        {
            return new LabelStmnt(s, e);
        }

        public ITypeCheckStmnt If(ITypeCheckExpr toEval, ITypeCheckStmnt ifTrue)
        {
            return new IfStmnt(toEval, ifTrue);
        }

        public ITypeCheckStmnt IfElse(ITypeCheckExpr toEval, ITypeCheckStmnt ifTrue, ITypeCheckStmnt ifFalse)
        {
            return new IfElseStmnt(toEval, ifTrue, ifFalse);
        }

        public ITypeCheckStmnt Block(ITypeCheckStmnt s)
        {
            return s; //We can skip this
        }
    }
}


text:
var posix = require('posix');

exports.install = function install(Vroom) {
  Vroom.Config.addOption('viewDir', "The directory views are served from.", ['{String}']);
  Vroom.Config.addOption('reloadTemplates', "Reload templates on each request, great for development.", ['false', 'true']);

  Vroom.Request.prototype.ejs = function (name, opts) {
    opts = opts || {};
    var promise = new process.Promise();
    var renderPromise = new process.Promise();
    var r = this;
    var config = this.application.config;
    var path;
    if (/^\//.exec(config.viewDir))
      path = config.viewDir + "/" + name + ".html.ejs";
    else
      path = config.root + "/" + (config.viewDir || ".") + "/" + name + ".html.ejs";
    this.application.LOG.debug("Using template: " + path);

    renderPromise.addCallback(function (tmpl) {
      r.status = r.status || 200;

      if (opts.autoFinish !== false)
        r.addHeader("Content-Length", tmpl.length);

      r.addHeader('Content-Type', 'text/html');
      r.sendHeader();
      r.write(tmpl);

      if (opts.autoFinish !== false)
        r.finish();

      promise.emitSuccess(tmpl);
    });

    renderPromise.addErrback(function (err) {
      promise.emitError(err);
    });

    render(renderPromise, path, this, {reload: config.reloadTemplates});

    return promise;
  };

  var cache = {};

  function compile(path) {
    var promise = new process.Promise();

    var cat_promise = posix.cat(path, "binary");

    cat_promise.addCallback(function (contents) {
      var tmpl = compile_string(contents);
      if (tmpl) {
        cache[path] = tmpl;
        promise.emitSuccess(tmpl);
      } else {
        promise.emitError("Template " + path + " failed to compile.");
      }
    });

    cat_promise.addErrback(function () {
      promise.emitError("File " + path + " was unreadable.");
    });

    return promise;
  }

  function compile_string(template) {
    /*
      This is based of of Yehuda Katz's jQuery template plugin.
    */
    var begin = "<%";
    var end = "%>";

    var rebegin = begin.replace(/([\]{}[\\])/g, '\\$1');
    var reend = end.replace(/([\]{}[\\])/g, '\\$1');

    var code = "self = self || {}; helpers = helpers || {}; with (helpers) { with (self) {" +
      "var _result = '';" +
        template
          .replace(/\r/g, '__CARRIAGE__')
          .replace(/\t/, '__TAB__')
          .replace(/\n/g, '__NEWLINE__')
          .replace(/^(.*)$/, end + '$1' + begin)
          .replace(new RegExp(reend + "(.*?)" + rebegin, "g"), function (text) {
            return text
              .replace(new RegExp("^" + reend + "(.*)" + rebegin + "$"), "$1")
              .replace(/\\/g, "\\\\")
              .replace(/'/g, "\\'")
              .replace(/^(.*)$/, end + "_result += '$1';" + begin);
          })
          .replace(new RegExp(rebegin + "=(.*?)" + reend, "g"),
            "_result += (function () { if(typeof($1) == 'undefined' || ($1) == null) { if (helpers && helpers.undef) helpers.undef('$1'); return ''; } else return ($1) })(); ")
          .replace(new RegExp(rebegin + "(.*?)" + reend, "g"), ' $1 ')
          .replace(new RegExp("^" + reend + "(.*)" + rebegin + "$"), '$1')
          .replace(/__CARRIAGE__/g, '\\r')
          .replace(/__TAB__/g, '\\t')
          .replace(/__NEWLINE__/g, '\\n') +
      "_result = _result.replace(/^\\s*/, '').replace(/\\s*$/, '');\n" +
      "return _result;\n" +
    "}}";

    return new Function("self", "helpers", code);
  }

  function render(promise, path, data, opts, helpers) {
    opts = opts || {};
    if (cache[path] && opts.reload !== true) {
      promise.emitSuccess([cache[path](data, helpers)]);
    } else {
      compile(path)
        .addCallback(function (tmpl) {
          promise.emitSuccess(tmpl(data, helpers));
        })
        .addErrback(function (err) {
          promise.emitError(err);
        });
    }
  }
}


text:
from django.template import Context, Library, TemplateSyntaxError
from django.template.base import FilterExpression, Parser, Template, Token
from django.test import SimpleTestCase

from tag_parser import template_tag
from tag_parser.basetags import BaseNode
from tag_parser.tests.templatetags import tag_parser_test_tags as test_tags

try:
    from django.template.base import add_to_builtins  # Django 1.8-
except ImportError:
    add_to_builtins = None

try:
    from django.template.base import TokenType  # Django 2.1+

    TOKEN_TEXT = TokenType.TEXT
except ImportError:
    from django.template.base import TOKEN_TEXT  # Django 2.0-

class TagParserTests(SimpleTestCase):
    @classmethod
    def setUpClass(cls):
        super(TagParserTests, cls).setUpClass()
        if add_to_builtins is not None:
            # Django 1.8 and below.
            # Make it easier to run tests without needing to change INSTALLED_APPS
            add_to_builtins("tag_parser.tests.templatetags.tag_parser_test_tags")

    def test_base_no_args(self):
        """
        Detect when ``@register.tag`` was used directly on the class.
        It should fail, and tell developers how to handle tags.
        """
        tag = Template("{% BaseNoArgsTag %}").nodelist[0]
        self.assertIsInstance(tag, test_tags.BaseNoArgsTag)

    def test_base_any_args(self):
        """
        Detect when ``@register.tag`` was used directly on the class.
        It should fail, and tell developers how to handle tags.
        """
        t = Template("{% BaseAnyArgsTag foo=1 bar=1 %}")
        tag = t.nodelist[0]
        self.assertIsInstance(tag, test_tags.BaseAnyArgsTag)
        self.assertIsInstance(tag.kwargs["foo"], FilterExpression)
        self.assertIsInstance(tag.kwargs["bar"], FilterExpression)

    def test_base_arguments(self):
        """
        Test whether compiled template arguments come across properly
        """
        t = Template("{% BaseArgsTag arg1 arg2 kw1=key1 kw2=key2 %}")
        tag = t.nodelist[0]

        # See if the tags are parsed correctly:
        self.assertIsInstance(tag, test_tags.BaseArgsTag)
        self.assertEqual(tag.tag_name, "BaseArgsTag")
        self.assertEqual(len(tag.args), 2)
        self.assertEqual(sorted(tag.kwargs.keys()), ["kw1", "kw2"])
        self.assertIsInstance(tag.args[0], FilterExpression)
        self.assertIsInstance(tag.args[1], FilterExpression)
        self.assertIsInstance(tag.kwargs["kw1"], FilterExpression)
        self.assertIsInstance(tag.kwargs["kw2"], FilterExpression)

        text = t.render(
            Context({"arg1": "AA1", "arg2": "AA2", "key1": "KEY1", "key2": "KEY2"})
        )
        self.assertEqual(text, "{args: AA1 AA2 kwargs: kw1=KEY1 kw2=KEY2]}")

    def test_invalid_kwargs(self):
        with self.assertRaises(TemplateSyntaxError):
            Template("{% BaseArgsTag invalid_kwarg=1 %}")

    def test_base_repr(self):
        """
        Test whether repr shows some meaningful output (both with compile and non-compile)
        """

        class ArgsTest1(BaseNode):
            max_args = 2
            allowed_kwargs = ("kw",)

        class ArgsTest2(BaseNode):
            max_args = 2
            allowed_kwargs = ("kw",)
            compile_kwargs = False

        node = ArgsTest1.parse(
            parser=_get_parser(),
            token=Token(TOKEN_TEXT, 'ArgsTest  1  2  kw=foo|default:"1" '),
        )
        self.assertEqual(
            repr(node), '<ArgsTest1: {% ArgsTest 1 2 kw=foo|default:"1" %}>'
        )

        node = ArgsTest2.parse(
            parser=_get_parser(),
            token=Token(TOKEN_TEXT, 'ArgsTest  1  2  kw=foo|default:"1" '),
        )
        self.assertEqual(
            repr(node), '<ArgsTest2: {% ArgsTest 1 2 kw=foo|default:"1" %}>'
        )

    def test_inclusion_tag_list(self):
        """
        Test whether the inclusion tag can handle lists as template choices.
        """
        tag = Template('{% BaseInclusionTag FOOBAR|default:"123" %}')
        self.assertEqual(tag.render(Context({"FOOBAR": "456"})).strip(), "456")

    def test_register_decorator(self):
        """
        Test the old ``@template_tag`` decorator (can now just use ``@register.tag()``).
        """
        register = Library()

        @template_tag(register, "RegTest")
        class RegTest(BaseNode):
            pass

        self.assertIn("RegTest", register.tags)
        self.assertEqual(register.tags["RegTest"], RegTest.parse)

def _get_parser():
    import django

    parser = Parser([])
    if django.VERSION >= (1, 9):
        import django.template.defaultfilters

        parser.add_library(django.template.defaultfilters.register)
    return parser


text:
module Daemonize
  VERSION = "0.1.2"

  # Try to fork if at all possible retrying every 5 sec if the
  # maximum process limit for the system has been reached
  def safefork
    tryagain = true

    while tryagain
      tryagain = false
      begin
        if pid = fork
          return pid
        end
      rescue Errno::EWOULDBLOCK
        sleep 5
        tryagain = true
      end
    end
  end

  # This method causes the current running process to become a daemon
  # If closefd is true, all existing file descriptors are closed
  def daemonize(oldmode=0, closefd=false)
    srand # Split rand streams between spawning and daemonized process
    safefork and exit # Fork and exit from the parent

    # Detach from the controlling terminal
    unless sess_id = Process.setsid
      raise 'Cannot detach from controlled terminal'
    end

    # Prevent the possibility of acquiring a controlling terminal
    if oldmode.zero?
      trap 'SIGHUP', 'IGNORE'
      exit if pid = safefork
    end

    Dir.chdir "/"   # Release old working directory
    File.umask 0000 # Insure sensible umask

    if closefd
      # Make sure all file descriptors are closed
      ObjectSpace.each_object(IO) do |io|
        unless [STDIN, STDOUT, STDERR].include?(io)
          io.close rescue nil
        end
      end
    end

    STDIN.reopen "/dev/null"       # Free file descriptors and
    STDOUT.reopen "/dev/null", "a" # point them somewhere sensible
    STDERR.reopen STDOUT           # STDOUT/STDERR should go to a logfile
    return oldmode ? sess_id : 0   # Return value is mostly irrelevant
  end
end


text:
namespace Si
{
    template <class T>
    auto to_shared(T &&t)
#if !SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE
        -> std::shared_ptr<typename std::decay<T>::type>
#endif
    {
        typedef typename std::decay<T>::type decayed_T;
        return std::make_shared<decayed_T>(std::forward<T>(t));
    }
}

#endif


text:
module.exports = function(router, passport) {
    //localhost:3000/auth
    router.get('/', function(req, res) {
        res.render('index.ejs');
    });

    //localhost:3000/auth/login
    router.get('/login', function(req, res) {
        res.render('login.ejs', {message: req.flash('loginMessage')});
    });
    router.post('/login', passport.authenticate('local-login', {
        successRedirect: '/profile',
        failureRedirect: '/login',
        failureFlash: true
    }));

    //localhost:3000/auth/signup
    router.get('/signup', function(req, res) {
        res.render('signup.ejs', {message: req.flash('signupMessage')} );
    });
    router.post('/signup', passport.authenticate('local-signup', {
        successRedirect: '/',
        failureRedirect: '/signup',
        failureFlash: true
    }));

    // Facebook auth login - route: - localhost:3000/auth/signup
    router.get('/facebook', passport.authenticate('facebook', {scope: ['email']}));

	router.get('/facebook/callback',
	  passport.authenticate('facebook', { successRedirect: '/profile',
	                                      failureRedirect: '/' }));

    // Google Auth Login
    router.get('/google', passport.authenticate('google', {scope: ['profile', 'email']}));
	router.get('/google/callback',
	  passport.authenticate('google', { successRedirect: '/profile',
	                                      failureRedirect: '/' }));

    // Routes if user is already signed in with one or other acct
    router.get('/connect/facebook', passport.authorize('facebook', { scope: 'email' }));
	router.get('/connect/google', passport.authorize('google', { scope: ['profile', 'email'] }));
	router.get('/connect/local', function(req, res){
		res.render('connect-local.ejs', { message: req.flash('signupMessage')});
	});

	router.post('/connect/local', passport.authenticate('local-signup', {
		successRedirect: '/profile',
		failureRedirect: '/connect/local',
		failureFlash: true
	}));

    // Unlink Social-Accts
    router.get('/unlink/facebook', function(req, res){
		var user = req.user;
		user.facebook.token = null;
		user.save(function(err){
			if(err)
				throw err;
			res.redirect('/profile');
		})
	});

	router.get('/unlink/local', function(req, res){
		var user = req.user;
		user.local.username = null;
		user.local.password = null;
		user.save(function(err){
			if(err)
				throw err;
			res.redirect('/profile');
		});

	});

	router.get('/unlink/google', function(req, res){
		var user = req.user;
		user.google.token = null;
		user.save(function(err){
			if(err)
				throw err;
			res.redirect('/profile');
		});
	});

    // Logout
    router.get('/logout', function(req, res) {
        req.logout();
        res.redirect('/');
    });
};


text: <redirect to="value-groups/"/>


text:
package org.krzywicki.app

import org.krzywicki.app.Configs.{ConcurrentConfig, HybridConfig, SequentialConfig}
import org.krzywicki.golomb.GolombProblem
import org.krzywicki.localsearch._

object GolombSequentialNoLocalSearch extends SequentialConfig with GolombProblem with NoLocalSearch
object GolombSequentialTaboo extends SequentialConfig with GolombProblem with TabooSearch
object GolombSequentialRMHC extends SequentialConfig with GolombProblem with RandomMutationHillClimbing
object GolombSequentialSDLS extends SequentialConfig with GolombProblem with SteepestDescend

object GolombHybridNoLocalSearch extends HybridConfig with GolombProblem with NoLocalSearch
object GolombHybridTaboo extends HybridConfig with GolombProblem with TabooSearch
object GolombHybridRMHC extends HybridConfig with GolombProblem with RandomMutationHillClimbing
object GolombHybridSDLS extends HybridConfig with GolombProblem with SteepestDescend

object GolombConcurrentNoLocalSearch extends ConcurrentConfig with GolombProblem with NoLocalSearch
object GolombConcurrentTaboo extends ConcurrentConfig with GolombProblem with TabooSearch
object GolombConcurrentRMHC extends ConcurrentConfig with GolombProblem with RandomMutationHillClimbing
object GolombConcurrentSDLS extends ConcurrentConfig with GolombProblem with SteepestDescend


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>pandas.Series.align — pandas 0.24.0.dev0+81.g8d5032a8c.dirty documentation</title>
    <link rel="stylesheet" href="../_static/nature.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />

    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="next" title="pandas.Series.all" href="pandas.Series.all.html" />
    <link rel="prev" title="pandas.Series.aggregate" href="pandas.Series.aggregate.html" />

Navigation

          index

          modules |

          next |

          previous |

pandas 0.24.0.dev0+81.g8d5032a8c.dirty documentation »

API Reference »

pandas.Series »

Table Of Contents

What's New

Installation

Contributing to pandas

Package overview

10 Minutes to pandas

Tutorials

Cookbook

Intro to Data Structures

Essential Basic Functionality

Working with Text Data

Options and Settings

Indexing and Selecting Data

MultiIndex / Advanced Indexing

Computational tools

Working with missing data

Group By: split-apply-combine

Merge, join, and concatenate

Reshaping and Pivot Tables

Time Series / Date functionality

Time Deltas

Categorical Data

Visualization

Styling

IO Tools (Text, CSV, HDF5, …)

Enhancing Performance

Sparse data structures

Frequently Asked Questions (FAQ)

rpy2 / R interface

pandas Ecosystem

Comparison with R / R libraries

Comparison with SQL

Comparison with SAS

Comparison with Stata

API Reference

Input/Output

General functions

Series

Constructor

Attributes

Conversion

Indexing, iteration

Binary operator functions

Function application, GroupBy & Window

Computations / Descriptive Stats

Reindexing / Selection / Label manipulation

pandas.Series.align

pandas.Series.drop

pandas.Series.drop_duplicates

pandas.Series.duplicated

pandas.Series.equals

pandas.Series.first

pandas.Series.head

pandas.Series.idxmax

pandas.Series.idxmin

pandas.Series.isin

pandas.Series.last

pandas.Series.reindex

pandas.Series.reindex_like

pandas.Series.rename

pandas.Series.rename_axis

pandas.Series.reset_index

pandas.Series.sample

pandas.Series.select

pandas.Series.set_axis

pandas.Series.take

pandas.Series.tail

pandas.Series.truncate

pandas.Series.where

pandas.Series.mask

pandas.Series.add_prefix

pandas.Series.add_suffix

pandas.Series.filter

Missing data handling

Reshaping, sorting

Combining / joining / merging

Time series-related

Datetimelike Properties

String handling

Categorical

Plotting

Serialization / IO / Conversion

Sparse

DataFrame

Panel

Index

Numeric Index

CategoricalIndex

IntervalIndex

MultiIndex

DatetimeIndex

TimedeltaIndex

PeriodIndex

Scalars

Frequencies

Window

GroupBy

Resampling

Style

Plotting

General utility functions

Extensions

Developer

Internals

Extending Pandas

Release Notes

Search

                <form class="search" action="../search.html" method="get">
                    <input type="text" name="q" size="18"/>
                    <input type="submit" value="Go"/>
                    <input type="hidden" name="check_keywords" value="yes"/>
                    <input type="hidden" name="area" value="default"/>
                </form>

                    Enter search terms or a module, class or function name.

pandas.Series.align¶

Series.align(other, join='outer', axis=None, level=None, copy=True, fill_value=None, method=None, limit=None, fill_axis=0, broadcast_axis=None)[source]¶

Align two objects on their axes with the
specified join method for each axis Index

<col class="field-name" />
<col class="field-body" />

Parameters:

other : DataFrame or Series

join : {'outer', 'inner', 'left', 'right'}, default 'outer'

axis : allowed axis of the other object, default None

Align on index (0), columns (1), or both (None)

level : int or level name, default None

Broadcast across a level, matching Index values on the
passed MultiIndex level

copy : boolean, default True

Always returns new objects. If copy=False and no reindexing is
required then original objects are returned.

fill_value : scalar, default np.NaN

Value to use for missing values. Defaults to NaN, but can be any
"compatible" value

method : str, default None

limit : int, default None

fill_axis : {0 or 'index'}, default 0

Filling axis, method and limit

broadcast_axis : {0 or 'index'}, default None

Broadcast values along this axis, if aligning two objects of
different dimensions

Returns:
(left, right) : (Series, type of other)

Aligned objects

Navigation

          index

          modules |

          next |

          previous |

pandas 0.24.0.dev0+81.g8d5032a8c.dirty documentation »

API Reference »

pandas.Series »

Scroll To Top


text:
namespace TwitterCapture.Migrations
{
    using System.CodeDom.Compiler;
    using System.Data.Entity.Migrations;
    using System.Data.Entity.Migrations.Infrastructure;
    using System.Resources;

    [GeneratedCode("EntityFramework.Migrations", "6.1.3-40302")]
    public sealed partial class db11 : IMigrationMetadata
    {
        private readonly ResourceManager Resources = new ResourceManager(typeof(db11));

        string IMigrationMetadata.Id
        {
            get { return "201509301747203_db11"; }
        }

        string IMigrationMetadata.Source
        {
            get { return null; }
        }

        string IMigrationMetadata.Target
        {
            get { return Resources.GetString("Target"); }
        }
    }
}


text:
namespace Nethereum.UI.Core.ViewModels
{
    public static class AddressToGravatar
    {
        public static string GetImgUrl(string address)
        {
            var hash = address;
            if (address.StartsWith("0x")) hash = address.Substring(2);
            return "http://www.gravatar.com/avatar/" + hash + ".jpg?s=75&d=retro";
        }
    }
}


text:
@interface CrResourceData()

@property (nonatomic, copy  ) NSString                              *tmpfile;
@property (nonatomic, strong) NSMutableArray<CrResourceDataUnit *>  *dataRangeArray;

@end

@implementation CrResourceData

- (void)dealloc {
    [CrFileHandle removeTempFile:self.tmpfile];
}

#pragma mark - 数据读写
- (void)appendData:(NSData *)data atOffset:(NSUInteger)offset {
    for (int i=0; i<self.dataRangeArray.count; i++) {
        CrResourceDataUnit *resource = self.dataRangeArray[i];
        if ((resource.offset+resource.length) == offset) {
            [resource appendData:data];
            return;
        }
    }
    CrResourceDataUnit *resource = [[CrResourceDataUnit alloc] initWithOffset:offset diskCache:self.diskCache];
    [resource appendData:data];
    [self.dataRangeArray addObject:resource];
    [self sortDataArray];
    [self mergeDataArray];
}

- (NSData *)getDataOffset:(NSUInteger)offset length:(NSUInteger)length {
    for (int i=0; i<self.dataRangeArray.count; i++) {
        CrResourceDataUnit *resource = self.dataRangeArray[i];
        if (offset >= resource.offset && (offset < (resource.offset+resource.length))) {          //有数据
            NSUInteger readOffset = offset-resource.offset;
            NSUInteger canReadLength = resource.length - readOffset;
            NSUInteger readLength = MIN(canReadLength, length);
            NSData *data = [resource readDataAtOffset:readOffset length:readLength];
            return data;
        }
    }
    //无数据
    return nil;
}

- (NSData *)getAllData {
    if (self.dataRangeArray.count == 0) {
        return nil;
    }
    NSMutableData *data = [[NSMutableData alloc] init];
    for (int i=0; i<self.dataRangeArray.count; i++) {
        CrResourceDataUnit *resource = self.dataRangeArray[i];
        [data appendData:[resource readData]];
    }
    return data;
}

- (BOOL)allDataOffset:(NSUInteger)offset length:(NSUInteger)length {
    for (int i=0; i<self.dataRangeArray.count; i++) {
        CrResourceDataUnit *resource = self.dataRangeArray[i];
        if (offset >= resource.offset && ((offset+length) <= (resource.offset+resource.length))) {          //有连续数据
            return YES;
        }
    }
    return NO;
}

- (BOOL)hasDataOffset:(NSUInteger)offset length:(NSUInteger)length {
    for (int i=0; i<self.dataRangeArray.count; i++) {
        CrResourceDataUnit *resource = self.dataRangeArray[i];
        if (offset >= resource.offset && (offset < (resource.offset+resource.length))) {          //有数据
            return YES;
        }
    }
    return NO;
}

//判断是否缓冲完成,以单一数据且长度恰好等于文件长度判断
- (BOOL)completeCached {
    if (self.dataRangeArray.count == 1 && [self getCurrentLength] == self.fileLength) {
        //CrDebugLog("Cache Success");
        CrResourceDataUnit *resource = self.dataRangeArray.firstObject;

        //将数据拷贝一份
        NSString *uinqueId = [NSString uniqueId];
        self.tmpfile = [NSString stringWithFormat:@"%@.tmp", uinqueId];
        [CrFileHandle createTempFile:self.tmpfile];
        [CrFileHandle writeData:[resource readData] toTempFile:self.tmpfile];
        return YES;
    } else {
        return NO;
    }
}

- (NSUInteger)getCurrentLength {
    NSUInteger datalength = 0;
    for (CrResourceDataUnit *resource in self.dataRangeArray) {
        datalength = datalength + resource.length;
    }
    return datalength;
}

#pragma mark - 排序合并已有数据
//按offset排序,确保所有数据可以按序合并
- (void)sortDataArray {
    NSSortDescriptor *sortDes = [NSSortDescriptor sortDescriptorWithKey:@"offset" ascending:YES];
    [self.dataRangeArray sortUsingDescriptors:@[sortDes]];
}

//将连续数据合并成单一数据
- (void)mergeDataArray {
    NSMutableArray<CrResourceDataUnit *> *dataArray = [[NSMutableArray<CrResourceDataUnit *> alloc] init];
    for (int i=0; i<self.dataRangeArray.count; i++) {
        CrResourceDataUnit *lastresource = dataArray.lastObject;
        CrResourceDataUnit *resourcei = self.dataRangeArray[i];
        if (lastresource && (lastresource.offset+lastresource.length)>=resourcei.offset) {          //有连续数据
            NSUInteger readOffset = (lastresource.offset+lastresource.length) - resourcei.offset;
            NSData *data = [resourcei readDataAtOffset:readOffset];
            [lastresource appendData:data];
        } else {    //无连续数据
            [dataArray addObject:resourcei];
        }
    }
    [self.dataRangeArray removeAllObjects];
    [self.dataRangeArray addObjectsFromArray:dataArray];
}

#pragma mark - getter
- (NSMutableArray<CrResourceDataUnit *> *)dataRangeArray {
    if (_dataRangeArray == nil) {
        _dataRangeArray = [[NSMutableArray<CrResourceDataUnit *> alloc] init];
    }
    return _dataRangeArray;
}

@end


text:
register_long_diagnostics! {
E0454: r##"
A link name was given with an empty name. Erroneous code example:

```compile_fail,E0454
#[link(name = "")] extern {} // error: #[link(name = "")] given with empty name
```

The rust compiler cannot link to an external library if you don't give it its
name. Example:

```ignore
#[link(name = "some_lib")] extern {} // ok!
```
"##,

E0455: r##"
Linking with `kind=framework` is only supported when targeting OS X,
as frameworks are specific to that operating system.

Erroneous code example:

```ignore
#[link(name = "FooCoreServices", kind = "framework")] extern {}
// OS used to compile is Linux for example
```

To solve this error you can use conditional compilation:

```
#[cfg_attr(target="macos", link(name = "FooCoreServices", kind = "framework"))]
extern {}
```

See more: https://doc.rust-lang.org/book/conditional-compilation.html
"##,

E0458: r##"
An unknown "kind" was specified for a link attribute. Erroneous code example:

```compile_fail,E0458
#[link(kind = "wonderful_unicorn")] extern {}
// error: unknown kind: `wonderful_unicorn`
```

Please specify a valid "kind" value, from one of the following:
 * static
 * dylib
 * framework
"##,

E0459: r##"
A link was used without a name parameter. Erroneous code example:

```compile_fail,E0459
#[link(kind = "dylib")] extern {}
// error: #[link(...)] specified without `name = "foo"`
```

Please add the name parameter to allow the rust compiler to find the library
you want. Example:

```ignore
#[link(kind = "dylib", name = "some_lib")] extern {} // ok!
```
"##,

E0463: r##"
A plugin/crate was declared but cannot be found. Erroneous code example:

```compile_fail,E0463
#![feature(plugin)]
#![plugin(cookie_monster)] // error: can't find crate for `cookie_monster`
extern crate cake_is_a_lie; // error: can't find crate for `cake_is_a_lie`
```

You need to link your code to the relevant crate in order to be able to use it
(through Cargo or the `-L` option of rustc example). Plugins are crates as
well, and you link to them the same way.
"##,

E0466: r##"
Macro import declarations were malformed.

Erroneous code examples:

```compile_fail,E0466
#[macro_use(a_macro(another_macro))] // error: invalid import declaration
extern crate core as some_crate;

#[macro_use(i_want = "some_macros")] // error: invalid import declaration
extern crate core as another_crate;
```

This is a syntax error at the level of attribute declarations. The proper
syntax for macro imports is the following:

```ignore
// In some_crate:
#[macro_export]
macro_rules! get_tacos {
    ...
}

#[macro_export]
macro_rules! get_pimientos {
    ...
}

// In your crate:
#[macro_use(get_tacos, get_pimientos)] // It imports `get_tacos` and
extern crate some_crate;               // `get_pimientos` macros from some_crate
```

If you would like to import all exported macros, write `macro_use` with no
arguments.
"##,

E0467: r##"
Macro reexport declarations were empty or malformed.

Erroneous code examples:

```compile_fail,E0467
#[macro_reexport]                    // error: no macros listed for export
extern crate core as macros_for_good;

#[macro_reexport(fun_macro = "foo")] // error: not a macro identifier
extern crate core as other_macros_for_good;
```

This is a syntax error at the level of attribute declarations.

Currently, `macro_reexport` requires at least one macro name to be listed.
Unlike `macro_use`, listing no names does not reexport all macros from the
given crate.

Decide which macros you would like to export and list them properly.

These are proper reexport declarations:

```ignore
#[macro_reexport(some_macro, another_macro)]
extern crate macros_for_good;
```
"##,

E0468: r##"
A non-root module attempts to import macros from another crate.

Example of erroneous code:

```compile_fail,E0468
mod foo {
    #[macro_use(helpful_macro)] // error: must be at crate root to import
    extern crate core;          //        macros from another crate
    helpful_macro!(...);
}
```

Only `extern crate` imports at the crate root level are allowed to import
macros.

Either move the macro import to crate root or do without the foreign macros.
This will work:

```ignore
#[macro_use(helpful_macro)]
extern crate some_crate;

mod foo {
    helpful_macro!(...)
}
```
"##,

E0469: r##"
A macro listed for import was not found.

Erroneous code example:

```compile_fail,E0469
#[macro_use(drink, be_merry)] // error: imported macro not found
extern crate collections;

fn main() {
    // ...
}
```

Either the listed macro is not contained in the imported crate, or it is not
exported from the given crate.

This could be caused by a typo. Did you misspell the macro's name?

Double-check the names of the macros listed for import, and that the crate
in question exports them.

A working version would be:

```ignore
// In some_crate crate:
#[macro_export]
macro_rules! eat {
    ...
}

#[macro_export]
macro_rules! drink {
    ...
}

// In your crate:
#[macro_use(eat, drink)]
extern crate some_crate; //ok!
```
"##,

E0470: r##"
A macro listed for reexport was not found.

Erroneous code example:

```compile_fail,E0470
#[macro_reexport(drink, be_merry)]
extern crate collections;

fn main() {
    // ...
}
```

Either the listed macro is not contained in the imported crate, or it is not
exported from the given crate.

This could be caused by a typo. Did you misspell the macro's name?

Double-check the names of the macros listed for reexport, and that the crate
in question exports them.

A working version:

```ignore
// In some_crate crate:
#[macro_export]
macro_rules! eat {
    ...
}

#[macro_export]
macro_rules! drink {
    ...
}

// In your_crate:
#[macro_reexport(eat, drink)]
extern crate some_crate;
```
"##,

}

register_diagnostics! {
    E0456, // plugin `..` is not available for triple `..`
    E0457, // plugin `..` only found in rlib format, but must be available...
    E0514, // metadata version mismatch
    E0460, // found possibly newer version of crate `..`
    E0461, // couldn't find crate `..` with expected target triple ..
    E0462, // found staticlib `..` instead of rlib or dylib
    E0464, // multiple matching crates for `..`
    E0465, // multiple .. candidates for `..` found
    E0519, // local crate and dependency have same (crate-name, disambiguator)
    E0523, // two dependencies have same (crate-name, disambiguator) but different SVH
}


text:
layout: post
date: 2014-12-09
title: 'Thesis Tutorials #1: Thesis 101'
subtitle: 'Back to basics'
redirect: http://www.jayblanco.com/blog/2016/2/20/thesis-tutorials-1-thesis-101
---


text:
package com.iobeam.api.service;

import com.iobeam.api.client.RestClient;
import com.iobeam.api.resource.DataPoint;
import com.iobeam.api.resource.Import;
import com.iobeam.api.resource.ImportBatch;

import org.junit.Test;

import java.util.List;

import static junit.framework.TestCase.assertEquals;

public class ImportServiceTest {

    private static final String TEST_DEVICE_ID = "test1234only5678";

    private final ImportService service = new ImportService(new RestClient());

    private ImportBatch getSubmitData(ImportService.Submit req) {
        return (ImportBatch) req.getBuilder().getContent();
    }

    private long getSubmitSize(ImportService.Submit req) {
        return getSubmitData(req).getData().getDataSize();
    }

    @Test
    public void testSmallImport() throws Exception {
        Import imp = new Import(TEST_DEVICE_ID, 1000);

        for (int i = 0; i < ImportService.REQ_MAX_POINTS; i++) {
            imp.addDataPoint("series1", new DataPoint(i, i));
        }
        List<ImportService.Submit> reqs = service.submit(imp);
        assertEquals(1, reqs.size());
    }

    @Test
    public void testSingleBigSeriesImport() throws Exception {
        Import imp = new Import(TEST_DEVICE_ID, 1000);
        long total = ImportService.REQ_MAX_POINTS * 2;

        for (int i = 0; i < total; i++) {
            imp.addDataPoint("series1", new DataPoint(i, i));
        }
        List<ImportService.Submit> reqs = service.submit(imp);
        assertEquals(2, reqs.size());
        assertEquals(ImportService.REQ_MAX_POINTS, getSubmitSize(reqs.get(0)));
        assertEquals(ImportService.REQ_MAX_POINTS, getSubmitSize(reqs.get(1)));
    }

    @Test
    public void testSmallEnoughSeries() throws Exception {
        Import imp = new Import(TEST_DEVICE_ID, 1000);
        long total = (long) (ImportService.REQ_MAX_POINTS * 1.5);
        long midway = total / 2;

        for (int i = 0; i < total; i++) {
            if (i < midway) {
                imp.addDataPoint("series1", new DataPoint(i, i));
            } else {
                imp.addDataPoint("series2", new DataPoint(i, i));
            }
        }

        List<ImportService.Submit> reqs = service.submit(imp);
        assertEquals(2, reqs.size());
        assertEquals(midway, getSubmitSize(reqs.get(0)));
        assertEquals(total - midway, getSubmitSize(reqs.get(1)));
    }

    @Test
    public void testOneSmallOneBigSeries() throws Exception {
        Import imp = new Import(TEST_DEVICE_ID, 1000);
        long total = (long) (ImportService.REQ_MAX_POINTS * 2);
        long midway = ImportService.REQ_MAX_POINTS / 2;

        for (int i = 0; i < total; i++) {
            if (i < midway) {
                imp.addDataPoint("series1", new DataPoint(i, i));
            } else {
                imp.addDataPoint("series2", new DataPoint(i, i));
            }
        }

        List<ImportService.Submit> reqs = service.submit(imp);
        assertEquals(3, reqs.size());

        long series1Size = 0;
        series1Size += getSubmitData(reqs.get(0)).getData().getColumns().contains("series1") ?
                       getSubmitSize(reqs.get(0)) : 0;
        series1Size += getSubmitData(reqs.get(1)).getData().getColumns().contains("series1") ?
                       getSubmitSize(reqs.get(1)) : 0;
        series1Size += getSubmitData(reqs.get(2)).getData().getColumns().contains("series1") ?
                       getSubmitSize(reqs.get(2)) : 0;

        long series2Size = 0;
        series2Size += getSubmitData(reqs.get(0)).getData().getColumns().contains("series2") ?
                       getSubmitSize(reqs.get(0)) : 0;
        series2Size += getSubmitData(reqs.get(1)).getData().getColumns().contains("series2") ?
                       getSubmitSize(reqs.get(1)) : 0;
        series2Size += getSubmitData(reqs.get(2)).getData().getColumns().contains("series2") ?
                       getSubmitSize(reqs.get(2)) : 0;

        assertEquals(midway, series1Size);
        assertEquals(total - midway, series2Size);
    }
}


text:
Tip Calculator for Codepath.

Input the bill amount and this handy app will calculate tip and split the bill for up to 4 people.

You can set the default tip amount and preferred color theme in the settings menu.

This project took 2.5 hours to complete.

###I completed the following required stories:
* [x] Required: Allow the user to input bill amount
* [x] Required: Allow user to select tip amount
* [x] Required: Allow user to see total
* [x] Required: Add a tip calculator settings page
* [x] Required: Allow the user to select default tip amount
* [x] Optional: Allow user to select a color theme
* [x] Optional: Add animations
* [x] Optional: Split the bill up to 4 people

## Installation:
This app has no dependencies. Just open up the project in XCode and run!

### Walkthrough of all user stories
![Tabber|250](https://i.imgur.com/1pJVZzk.gif)


text:
namespace cc {

LayerTreeSettings::LayerTreeSettings()
    : impl_side_painting(false),
      allow_antialiasing(true),
      throttle_frame_production(true),
      single_thread_proxy_scheduler(true),
      begin_frame_scheduling_enabled(false),
      main_frame_before_draw_enabled(true),
      main_frame_before_activation_enabled(false),
      using_synchronous_renderer_compositor(false),
      report_overscroll_only_for_scrollable_axes(false),
      per_tile_painting_enabled(false),
      partial_swap_enabled(false),
      accelerated_animation_enabled(true),
      can_use_lcd_text(true),
      should_clear_root_render_pass(true),
      gpu_rasterization_enabled(false),
      gpu_rasterization_forced(false),
      recording_mode(RecordNormally),
      create_low_res_tiling(true),
      scrollbar_animator(NoAnimator),
      scrollbar_fade_delay_ms(0),
      scrollbar_fade_duration_ms(0),
      solid_color_scrollbar_color(SK_ColorWHITE),
      calculate_top_controls_position(false),
      timeout_and_draw_when_animation_checkerboards(true),
      maximum_number_of_failed_draws_before_draw_is_forced_(3),
      layer_transforms_should_scale_layer_contents(false),
      minimum_contents_scale(0.0625f),
      low_res_contents_scale_factor(0.25f),
      top_controls_height(0.f),
      top_controls_show_threshold(0.5f),
      top_controls_hide_threshold(0.5f),
      refresh_rate(60.0),
      max_partial_texture_updates(std::numeric_limits<size_t>::max()),
      default_tile_size(gfx::Size(256, 256)),
      max_untiled_layer_size(gfx::Size(512, 512)),
      minimum_occlusion_tracking_size(gfx::Size(160, 160)),
      use_pinch_zoom_scrollbars(false),
      use_pinch_virtual_viewport(false),
      // At 256x256 tiles, 128 tiles cover an area of 2048x4096 pixels.
      max_tiles_for_interest_area(128),
      skewport_target_time_multiplier(1.0f),
      skewport_extrapolation_limit_in_content_pixels(2000),
      max_unused_resource_memory_percentage(100),
      max_memory_for_prepaint_percentage(100),
      highp_threshold_min(0),
      strict_layer_property_change_checking(false),
      use_one_copy(false),
      use_zero_copy(false),
      ignore_root_layer_flings(false),
      use_rgba_4444_textures(false),
      texture_id_allocation_chunk_size(64),
      use_occlusion_for_tile_prioritization(false),
      record_full_layer(false) {
}

LayerTreeSettings::~LayerTreeSettings() {}

}  // namespace cc


text:
import {
  Directive, Input, HostListener, HostBinding, ContentChildren, QueryList,
  AfterViewInit, AfterContentInit, ElementRef, ChangeDetectorRef
} from '@angular/core';
import { MovableHandleDirective } from './movable-handle.directive';

export interface Coordinates {
  top: number;
  left: number;
}
export interface Rects {
  top: number;
  left: number;
  height: number;
  width: number;
}
// workaround to prevent error in MS Edge
export interface ITouchEvent extends UIEvent {
  changedTouches: Coordinates[];
}
export type Positions = Coordinates | Rects | ITouchEvent | MouseEvent;

export class Position {
  public top: number;
  public left: number;
  public height: number = null;
  public width: number = null;
  public get bottom() {
    return (this.height === null) ? null : this.top + this.height;
  }
  public get right() {
    return (this.width === null) ? null : this.left + this.width;
  }

  constructor(pos: Positions) {
    if (this.containsNumberProp(pos, ['top', 'left'])) {
      this.top = (<any>pos).top;
      this.left = (<any>pos).left;
      if (this.containsNumberProp(pos, ['height', 'width'])) {
        this.height = (<any>pos).height;
        this.width = (<any>pos).width;
      }
    } else if (this.containsNumberProp(pos, ['clientY', 'clientX'])) {
      this.top = (<any>pos).clientY;
      this.left = (<any>pos).clientX;
    } else if ((<any>pos).changedTouches
      && (<any>pos).changedTouches.length > 0
      && (<any>pos).changedTouches[0]
      && this.containsNumberProp((<any>pos).changedTouches[0], ['clientY', 'clientX'])
    ) {
      this.top = (<any>pos).changedTouches[0].clientY;
      this.left = (<any>pos).changedTouches[0].clientX;
    }
  }

  /**
   * substract the position argument to the current (top, left) and return the result as new position.
   * @param  {Coordinates} position     position to substract
   * @return {Position}
   */
  public minus(position: Coordinates) {
    return new Position({
      top: (this.top - position.top),
      left: (this.left - position.left),
      height: this.height,
      width: this.width
    });
  }

  /**
   * add the position argument to the current (top, left) and return the result as new position.
   * @param  {Coordinates} position     position to add
   * @return {Position}
   */
  public plus(position: Coordinates) {
    return new Position({
      top: (this.top + position.top),
      left: (this.left + position.left),
      height: this.height,
      width: this.width
    });
  }

  protected containsNumberProp(object: any, props: string[]) {
    return props.every(prop => prop in object && typeof object[prop] === 'number');
  }
}

@Directive({
  selector: '[movable]'
})
export class MovableDirective implements AfterViewInit, AfterContentInit {

  /** saved start position when moving starts. */
  protected startPosition: Position;

  /** true if moving is in progress. */
  @HostBinding('class.movable-moving')
  protected isMoving = false;

  @HostBinding('class.movable-handle')
  protected isHandle = false;

  /** set position style on host to relative. */
  @HostBinding('style.position')
  protected positionStyle: string;

  /** current Y position of the native element. */
  @HostBinding('style.top.px')
  protected positionTop: number;

  /** current X position of the native element. */
  @HostBinding('style.left.px')
  protected positionLeft: number;

  /** set class on host to indicate movable support. */
  @HostBinding('class.movable')
  protected isMovable = true;

  /** set class depending on the status. */
  @HostBinding('class.movable-enabled')
  protected _movableEnabled = true;
  protected get movableEnabled() {
    return this._movableEnabled;
  }

  /** optional input to toggle movable status. */
  @Input()
  protected set movableEnabled(value: boolean) {
    this._movableEnabled = value;
    // propagate enabled status to handles
    if (this.handles.length > 0) {
      this.handles.forEach(handle => handle.movableEnabled = value);
    }
  }

  protected movableName: string;
  @Input()
  protected set movable(value: string) {
    this.movableName = value;
  }

  @Input()
  public movableConstrained = true;

  @Input()
  public movableConstraint: string;

  @ContentChildren(MovableHandleDirective, { descendants: true })
  protected allHandles: QueryList<MovableHandleDirective>;
  protected handles: MovableHandleDirective[] = [];

  constructor(public element: ElementRef, protected cd: ChangeDetectorRef) {
  }

  ngAfterViewInit() {
    const position = this.getStyle(this.element.nativeElement, 'position');
    if (position === 'static') {
      this.positionStyle = 'relative';
      this.cd.detectChanges();
    }
  }

  ngAfterContentInit() {
    this.allHandles.changes.subscribe((handles: QueryList<MovableHandleDirective>) => this.updateQuery(handles));
    // TODO: workaround for https://github.com/angular/angular/issues/12818 and https://github.com/angular/angular/issues/9689
    // manually trigger first update.
    this.updateQuery(this.allHandles);
  }

  protected updateQuery(handles: QueryList<MovableHandleDirective>) {
    this.handles = handles.filter(handle => handle.movableHandle === this.movableName);
    // fallback to this as handle if not specified
    if (this.handles.length === 0) {
      this.isHandle = true;
    }
    // propagate enabled status to handles
    if (this.handles.length > 0) {
      this.handles.forEach(handle => handle.movableEnabled = this.movableEnabled);
    }
  }

  @HostListener('mousedown', ['$event'])
  protected onMouseDown(event: MouseEvent) {
    this.startMoving(event);
  }

  @HostListener('document:mouseup', ['$event'])
  protected onMouseUp(event: MouseEvent) {
    this.stopMoving();
  }

  // using document to move even pointer leaves the host (fast moving)
  @HostListener('document:mousemove', ['$event'])
  protected onMouseMove(event: MouseEvent) {
    this.moveElement(event);
  }

  @HostListener('touchstart', ['$event'])
  protected onTouchStart(event: ITouchEvent) {
    this.startMoving(event);
  }

  @HostListener('document:touchend', ['$event'])
  protected onTouchEnd(event: ITouchEvent) {
    this.stopMoving();
  }

  // using document to move even pointer leaves the host (fast moving)
  @HostListener('document:touchmove', ['$event'])
  protected onTouchMove(event: any) {
    this.moveElement(event);
  }

  protected startMoving(event: ITouchEvent | MouseEvent) {
    if (this.isEventInHandle(event) && this.movableEnabled) {
      this.startPosition = new Position(event).minus(this.getRelativeRect(this.element.nativeElement));
      this.isMoving = true;
      if (this.handles.length > 0) {
        this.handles.forEach(handle => handle.isMoving = true);
      }
      this.cd.detectChanges();
    }
  }

  protected stopMoving() {
    this.isMoving = false;
    if (this.handles.length > 0) {
      this.handles.forEach(handle => handle.isMoving = false);
    }
    this.cd.detectChanges();
  }

  /**
   * update host position for the specific event when moving.
   */
  protected moveElement(event: ITouchEvent | MouseEvent) {
    if (this.isMoving) {
      let moved = false;
      const newPosition = new Position(event).minus(this.startPosition);
      if (!this.movableConstrained) {
        this.positionTop = newPosition.top;
        this.positionLeft = newPosition.left;
        moved = true;
      } else {
        const constainedByElement: HTMLElement = this.element.nativeElement.ownerDocument.getElementById(this.movableConstraint);
        let constainedByAbsPos: Position;
        if (constainedByElement) {
          constainedByAbsPos = new Position(constainedByElement.getBoundingClientRect());
        } else {
          constainedByAbsPos = this.getViewPos(this.element.nativeElement);
        }
        const elementAbsPos = new Position(this.element.nativeElement.getBoundingClientRect());
        const diffAbsToRel = elementAbsPos.minus(this.getRelativeRect(this.element.nativeElement));
        const newAbsPos = diffAbsToRel.plus(newPosition);
        if (newAbsPos.top >= constainedByAbsPos.top && newAbsPos.bottom <= constainedByAbsPos.bottom) {
          this.positionTop = newPosition.top;
          moved = true;
        } else {
          if (newAbsPos.top < constainedByAbsPos.top) {
            // max to top limit, to prevent sticking of the movable on fast move
            this.positionTop = constainedByAbsPos.minus(diffAbsToRel).top;
            moved = true;
          }
          if (newAbsPos.bottom > constainedByAbsPos.bottom) {
            // max to bottom limit, to prevent sticking of the movable on fast move
            this.positionTop = constainedByAbsPos.minus(diffAbsToRel).bottom - elementAbsPos.height;
            moved = true;
          }
        }
        if (newAbsPos.left >= constainedByAbsPos.left && newAbsPos.right <= constainedByAbsPos.right) {
          this.positionLeft = newPosition.left;
          moved = true;
        } else {
          if (newAbsPos.left < constainedByAbsPos.left) {
            // max to left limit, to prevent sticking of the movable on fast move
            this.positionLeft = constainedByAbsPos.minus(diffAbsToRel).left;
            moved = true;
          }
          if (newAbsPos.right > constainedByAbsPos.right) {
            // max to right limit, to prevent sticking of the movable on fast move
            this.positionLeft = constainedByAbsPos.minus(diffAbsToRel).right - elementAbsPos.width;
            moved = true;
          }
        }
      }
      if (moved) {
        // prevent selection and other side effects during moving, only when position moved, i.e. to allow buttons to be clicked
        event.preventDefault();
        event.stopPropagation();
        this.cd.detectChanges();
      }
    }
  }

  /**
   * checks if the event occured inside the handle element.
   */
  protected isEventInHandle(event: ITouchEvent | MouseEvent): boolean {
    let srcElement = event.target || event.srcElement;
    if (this.isHandle) {
      // check parent elements too.
      while (srcElement instanceof HTMLElement && srcElement !== this.element.nativeElement && srcElement.parentElement) {
        srcElement = srcElement.parentElement;
      }
      return this.element.nativeElement === srcElement;
    } else {
      return this.handles.some(handle => {
        // check parent elements too.
        while (srcElement instanceof HTMLElement && srcElement !== handle.element.nativeElement && srcElement.parentElement) {
          srcElement = srcElement.parentElement;
        }
        return handle.element.nativeElement === srcElement;
      });
    }
  }

  /**
   * get the element's relative position.
   * similar to the absolute position with getBoundingClientRect().
   */
  protected getRelativeRect(element: HTMLElement): Position {
    return new Position({
      top: this.parseStyleInt(this.getStyle(element, 'top')) || 0,
      left: this.parseStyleInt(this.getStyle(element, 'left')) || 0,
      height: this.parseStyleInt(this.getStyle(element, 'height')) || 0,
      width: this.parseStyleInt(this.getStyle(element, 'width')) || 0
    });
  }

  /**
   * parse int.
   */
  protected parseStyleInt(value: string) {
    return parseInt(value, 10);
  }

  /**
   * get computed style property.
   */
  protected getStyle(element: HTMLElement, property: string) {
    const view = this.getView(element);
    return view.getComputedStyle(element, null).getPropertyValue(property);
  }

  /**
   * get the element's viewport.
   */
  protected getView(element: HTMLElement) {
    let view = element.ownerDocument.defaultView;
    if (!view || view.opener) {
      view = window;
    }
    return view;
  }

  /**
   * get the element's viewport position.
   */
  protected getViewPos(element: HTMLElement) {
    const view = this.getView(element);
    return new Position({
      top: 0,
      left: 0,
      height: view.innerHeight || element.ownerDocument.documentElement.clientHeight,
      width: view.innerWidth || element.ownerDocument.documentElement.clientWidth
    });
  }

}