text:
SOURCE=../../../../twitter4j-core/src/main/java/twitter4j/$1.java
TARGET=../../main/java/twitter4j/internal/json/Lazy$1.java
NOW=`date +'%Y-%m-%d'`
cp $SOURCE $TARGET

sed -i "" "s/A data interface/A data class/g" $TARGET
sed -i "" 's/package twitter4j;/\package twitter4j.internal.json;\
\
import twitter4j.*;\
import javax.annotation.Generated;/g' $TARGET
sed -i "" "s/public interface $1/final class Lazy$1/g" $TARGET
sed -i "" 's/final class/@Generated(\
        value = "generate-lazy-objects.sh",\
        comments = "This is Tool Generated Code. DO NOT EDIT",\
        date = "NOW"\
)\
final class/g' $TARGET

sed -i "" "s/extends .*{$/implements twitter4j.$1 {/g" $TARGET
sed -i "" "s/NOW/$NOW/g" $TARGET

sed -i "" 's/{$/{\
    private twitter4j.internal.http.HttpResponse res;\
    private z_T4JInternalFactory factory;\
    private XXX target = null;\
\
    LazyXXX(twitter4j.internal.http.HttpResponse res, z_T4JInternalFactory factory) {\
        this.res = res;\
        this.factory = factory;\
    }\
\
    private XXX getTarget() {\
        if (target == null) {\
            try {\
                target = factory.createXXX(res);\
            } catch (TwitterException e) {\
                throw new TwitterRuntimeException(e);\
            }\
        }\
        return target;\
    }\
/g' $TARGET

sed -i "" 's/    \(.*\) \(get[^;]*\);/    public \1 \2 {\
        return getTarget().\2;\
    }\
/g' $TARGET

sed -i "" 's/\([^ ]*\ \)\(is[^;]*\);/public \1\2 {\
        return getTarget().\2;\
    }\
/g' $TARGET

sed -i "" 's/^}/RATELIMITSTATUS\COMPARETO\
    @Override\
    public boolean equals(Object o) {\
        if (this == o) return true;\
        if (!(o instanceof XXX)) return false;\
        return getTarget().equals(o);\
    }\
\
    @Override\
    public int hashCode() {\
        return getTarget().hashCode();\
    }\
\
    @Override\
    public String toString() {\
        return "LazyXXX{" +\
                "target=" + getTarget() +\
                "}";\
    }\
}/g' $TARGET

sed -i "" 's/    boolean hasNext();/    public boolean hasNext() {\
        return getTarget().hasNext();\
    }\
/g' $TARGET

sed -i "" 's/    boolean hasPrevious();/    public boolean hasPrevious() {\
        return getTarget().hasPrevious();\
    }\
/g' $TARGET

if test 1 -eq `grep Comparable $SOURCE |wc -l`; then
 sed -i "" 's/COMPARETO/    public int compareTo(XXX target) {\
        return getTarget().compareTo(target);\
    }\
/g' $TARGET
else
 sed -i "" 's/COMPARETO//g' $TARGET
fi

# generate getRateLimitStatus() and getAccessLevel() if the class is not LazyRateLimitStatus|LazyQueryResult
if test 0 -eq `grep -E "(LazyRateLimitStatus|LazyQueryResult)" $TARGET |wc -l`; then
 sed -i "" 's/RATELIMITSTATUS/    public RateLimitStatus getRateLimitStatus() {\
        return getTarget().getRateLimitStatus();\
    }\
\
    public int getAccessLevel() {\
        return getTarget().getAccessLevel();\
    }\
\
/g' $TARGET
else
 sed -i "" 's/RATELIMITSTATUS//g' $TARGET
fi

sed -i "" "s/XXX/$1/g" $TARGET


text:
    <button type="button" class="close" ng-click="$dismiss()">×</button>

环节配置

    <form name="stageForm" role="form" class="form-horizontal stage-configuration-form">

            名称*

                <input id="stageTitle" name="stageTitle" type="text" class="form-control" data-ng-model="stage.title"
                       focus="true" placeholder="名称" autocomplete="off" maxlength="30" required/>

                    环节名称不能为空

            描述

                <textarea id="stageDescription" name="stageDescription" rows="3" ng-maxlength="100"
                          class="form-control ng-pristine ng-valid ng-valid-required ng-touched"
                          data-ng-model="stage.description" focus="true" placeholder="相关描述说明"
                          autocomplete="off"></textarea>

            类型*

                <ui-select data-ng-model="types.selected" name="stageType">
                    <ui-select-match placeholder="选择类型">{{$select.selected.name}}</ui-select-match>
                    <ui-select-choices repeat="type in types | filter: $select.search">

                    </ui-select-choices>
                </ui-select>

            状态

                <ui-select data-ng-model="statusList.selected" name="stageStatus">
                    <ui-select-match placeholder="选择类型">{{$select.selected.name}}</ui-select-match>
                    <ui-select-choices repeat="status in statusList | filter: $select.search">

                    </ui-select-choices>
                </ui-select>

            限额

                <input id="WIPLimit" class="form-control simple-input" type="number" name="WIPLimit"
                       ng-model="stage.wipLimit"
                       min="1" max="99" required>

    </form>

    <button class="btn btn-primary" type="button" ng-click="saveStage()"
            ng-disabled="(!stageForm.$dirty&&stageForm.$invalid)||isDisableStageSaveButton">
        {{stageSaveButton}}
    </button>

redpajama_set_name: RedPajamaGithub


text:
class OrganizationApi:
  def __init__(self, client, base_path = "/v1"):
    self.client = client
    self.base_path = base_path

  def addUser(self, body=None):
    __query = {
    }
    if body is None:
      raise Exception("Missing required parameter \"body\"")

    format_args = {}
    path = "/organization/addUser"
    if "$body" in path:
      path = path.replace("$body", "%(body)s")
      format_args["body"] = body
    ret = self.client.request("POST", self.base_path + path % format_args, __query, body)
    if ret is not None:
      from ..model.UacAddUserResponse import UacAddUserResponse
      ret = UacAddUserResponse.from_json(ret)

    return ret

  def deleteOrganization(self, body=None):
    __query = {
    }
    if body is None:
      raise Exception("Missing required parameter \"body\"")

    format_args = {}
    path = "/organization/deleteOrganization"
    if "$body" in path:
      path = path.replace("$body", "%(body)s")
      format_args["body"] = body
    ret = self.client.request("POST", self.base_path + path % format_args, __query, body)
    if ret is not None:
      from ..model.UacDeleteOrganizationResponse import UacDeleteOrganizationResponse
      ret = UacDeleteOrganizationResponse.from_json(ret)

    return ret

  def getOrganizationById(self, org_id=None):
    __query = {
      "org_id": client.to_query(org_id)
    }
    body = None

    format_args = {}
    path = "/organization/getOrganizationById"
    if "$org_id" in path:
      path = path.replace("$org_id", "%(org_id)s")
      format_args["org_id"] = org_id
    ret = self.client.request("GET", self.base_path + path % format_args, __query, body)
    if ret is not None:
      from ..model.UacGetOrganizationByIdResponse import UacGetOrganizationByIdResponse
      ret = UacGetOrganizationByIdResponse.from_json(ret)

    return ret

  def getOrganizationByName(self, org_name=None):
    __query = {
      "org_name": client.to_query(org_name)
    }
    body = None

    format_args = {}
    path = "/organization/getOrganizationByName"
    if "$org_name" in path:
      path = path.replace("$org_name", "%(org_name)s")
      format_args["org_name"] = org_name
    ret = self.client.request("GET", self.base_path + path % format_args, __query, body)
    if ret is not None:
      from ..model.UacGetOrganizationByNameResponse import UacGetOrganizationByNameResponse
      ret = UacGetOrganizationByNameResponse.from_json(ret)

    return ret

  def getOrganizationByShortName(self, short_name=None):
    __query = {
      "short_name": client.to_query(short_name)
    }
    body = None

    format_args = {}
    path = "/organization/getOrganizationByShortName"
    if "$short_name" in path:
      path = path.replace("$short_name", "%(short_name)s")
      format_args["short_name"] = short_name
    ret = self.client.request("GET", self.base_path + path % format_args, __query, body)
    if ret is not None:
      from ..model.UacGetOrganizationByShortNameResponse import UacGetOrganizationByShortNameResponse
      ret = UacGetOrganizationByShortNameResponse.from_json(ret)

    return ret

  def listMyOrganizations(self, ):
    __query = {
    }
    body = None

    format_args = {}
    path = "/organization/listMyOrganizations"
    ret = self.client.request("GET", self.base_path + path % format_args, __query, body)
    if ret is not None:
      from ..model.UacListMyOrganizationsResponse import UacListMyOrganizationsResponse
      ret = UacListMyOrganizationsResponse.from_json(ret)

    return ret

  def listTeams(self, org_id=None):
    __query = {
      "org_id": client.to_query(org_id)
    }
    body = None

    format_args = {}
    path = "/organization/listTeams"
    if "$org_id" in path:
      path = path.replace("$org_id", "%(org_id)s")
      format_args["org_id"] = org_id
    ret = self.client.request("GET", self.base_path + path % format_args, __query, body)
    if ret is not None:
      from ..model.UacListTeamsResponse import UacListTeamsResponse
      ret = UacListTeamsResponse.from_json(ret)

    return ret

  def listUsers(self, org_id=None):
    __query = {
      "org_id": client.to_query(org_id)
    }
    body = None

    format_args = {}
    path = "/organization/listUsers"
    if "$org_id" in path:
      path = path.replace("$org_id", "%(org_id)s")
      format_args["org_id"] = org_id
    ret = self.client.request("GET", self.base_path + path % format_args, __query, body)
    if ret is not None:
      from ..model.UacListUsersResponse import UacListUsersResponse
      ret = UacListUsersResponse.from_json(ret)

    return ret

  def removeUser(self, body=None):
    __query = {
    }
    if body is None:
      raise Exception("Missing required parameter \"body\"")

    format_args = {}
    path = "/organization/removeUser"
    if "$body" in path:
      path = path.replace("$body", "%(body)s")
      format_args["body"] = body
    ret = self.client.request("POST", self.base_path + path % format_args, __query, body)
    if ret is not None:
      from ..model.UacRemoveUserResponse import UacRemoveUserResponse
      ret = UacRemoveUserResponse.from_json(ret)

    return ret

  def setOrganization(self, body=None):
    __query = {
    }
    if body is None:
      raise Exception("Missing required parameter \"body\"")

    format_args = {}
    path = "/organization/setOrganization"
    if "$body" in path:
      path = path.replace("$body", "%(body)s")
      format_args["body"] = body
    ret = self.client.request("POST", self.base_path + path % format_args, __query, body)
    if ret is not None:
      from ..model.UacSetOrganizationResponse import UacSetOrganizationResponse
      ret = UacSetOrganizationResponse.from_json(ret)

    return ret


text:
/**
 * This package contains translation site model.
 *
 * @author Tommi S.E. Laukkanen
 */
package org.groom.translation.model;


text:
bref: ""
draft: false
menu:
  sidenav:
    name: Downloads  -
    weight: -258
    parent: Microservices
sidebar: sidenav
title: "Teiid Microservices Downloads"
toc: true
weight: 10
---

Teiid Microservices Downloads....


text:
'use strict';

// export client|server, local|remote, source|destin

const
  // dependencies core
  path = require('path'),
  fs   = require('fs'),
  // exec = require('child_process').execSync, // only for cksum
  crypto = require('crypto'),

  // dependencies pkgs
  // yaml = require('js-yaml'),
  ssh  = require('ssh2'),

  // settings
  cli  = require.main === module;
  // conf = yaml.safeLoad(fs.readFileSync('zinc.yaml', 'utf8'));
  // conf.ignore = conf.ignore || [];

if (cli) {
  var root = process.argv[2];
  var tree = buildTree(root);
  process.stdout.write(JSON.stringify(tree));
}
else {
  module.exports = {
    build: build,
    diff:  diff,
    sync:  sync
  };
}

function build (root) {
  // root path or config object

  // var rtree = sshTree();
  // console.log(rtree);
  // var stree = buildTree('publish');
  // var dtree = JSON.parse(sshTree());
  // console.log(tree)
  // console.log(rtree);

  // if (stree && dtree) {
  //   diffTree(stree, dtree);
  // }

}

function diff (source, destin) {

}

function sync () {

}

// function sshTree () {
//   var path = 'pubx';
//   var tree = exec(`node ../zinc ${path}`).toString();
//   // return JSON.parse(tree);
//   return tree; // json
// }

// function sync (root, diff) { // remote root
//   diff.remote = path.resolve(root);
//   return JSON.stringify(diff);
// }

function buildTree (absolute, ignore, relative, tree, depth, init = true) {

  if (init) {
    if (!absolute) {
      console.log(`Zinc Error: specify a root directory`);
      return;
    }
    else if (!fs.existsSync(absolute)) {
      console.log(`Zinc Error: "${path.resolve(path.resolve(absolute))}" does not exist`);
      return;
    }
    else if (!fs.statSync(absolute).isDirectory()) {
      console.log(`Zinc Error: "${path.resolve(path.resolve(absolute))}" is not a directory`);
      return;
    }
    else {
      absolute = path.resolve(absolute);
      ignore = ignore || [],
      relative = '';
      tree = [];
      depth = 0;
      init = false;
    }
  }

  fs.readdirSync(absolute).forEach(item => {

    // might include paths, not just items
    // might include except(tions)
    if (ignore.indexOf(item) > -1) {
      return;
    }

    var abs = path.join(absolute, item);
    var rel = path.join(relative, item);

    var stats = fs.statSync(abs);

    if (stats.isFile()) {
      tree.push({
        abs: abs,
        rel: rel,
        crc: crc(abs),
        depth: depth
      });
    }
    else if (stats.isDirectory()) {
      tree.push({
        abs: abs,
        rel: rel,
        crc: 'dir',
        depth: depth
      });
      buildTree(abs, ignore, rel, tree, depth + 1, init);
    }
  });

  return tree;
}

function crc (file, algo, enc) {

  let data = fs.readFileSync(file);

  return crypto
    .createHash(algo || 'md5')
    .update(data, 'utf8')
    .digest(enc || 'hex');

  // https://blog.tompawlak.org/calculate-checksum-hash-nodejs-javascript

  // nix only ...
  // return exec(`cksum ${file}`).toString().split(' ')[0];

  // https://stackoverflow.com/questions/12276426/windows-equivalent-of-linux-cksum-command
  // let winSum = `CertUtil -hashfile  ${file} MD5`;
  // let nixSum = `md5sum  ${file}`; // native nix md5
}

function diffTree (source, destin) {

  let diff = {upload: [], remove: []};

  // We can safely skip including children of directories
  // that we've already found and added to upload|remove
  // Directories are processed first in our buildTree,
  // otherwise we could do...
  // source.sort((A, B) => A.depth - B.depth);
  // destin.sort((A, B) => A.depth - B.depth);

  // process uploads
  source.forEach(item => {

    // if (diff.upload.some(test => item.rel.indexOf(test.rel) === 0)) {
    //   return;
    // }

    var saved = diff.upload.some(test => {
      return item.rel.indexOf(test.rel) === 0;
    });

    if (saved) {
      return;
    }

    // if (!destin.every(test => item.rel === test.rel && item.crc === test.crc;)) {
    //   diff.upload.push(item);
    // }

    var found = destin.some(test => {
      return item.rel === test.rel && item.crc === test.crc;
    });

    if (!found) {
      diff.upload.push(item);
    }
  });

  // process removes
  destin.forEach(item => {

    // if (diff.upload.some(test => item.rel.indexOf(test.rel) === 0)) {
    //   return;
    // }

    var saved = diff.remove.some(test => {
      return item.rel.indexOf(test.rel) === 0;
    });

    if (saved) {
      return;
    }

    // if (source.every(test => item.rel !== test.rel)) {
    //   diff.remove.push(item);
    // }

    var trash = source.every(test => {
      return item.rel !== test.rel;
    });

    if (trash) {
      diff.remove.push(item);
    }
  });

  // console.log(diff)
  return diff;
}


text:
/* eslint ember/order-in-components: 0 */
import Component from '@ember/component';
import ReportTitleMixin from 'ilios/mixins/report-title';
import { task } from 'ember-concurrency';

export default Component.extend(ReportTitleMixin, {
  reporttitle: null,
  classNames: ['myreports-list-item'],
  tagName: 'span',

  didReceiveAttrs() {
    this._super(...arguments);
    const report = this.report;
    this.loadTitle.perform(report);
  },

  loadTitle: task(function * (report) {
    const title = yield this.getReportTitle(report);
    this.set('reporttitle', title);
  }).restartable(),

  actions: {
    selectReport(report) {
      this.selectReport(report);
    }
  }
});


text:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;

namespace Aardvark.Base
{
    // AUTO GENERATED CODE - DO NOT CHANGE!

    //# Func<string, Action> Sep = s => () => Out(s);
    //# { // POLYGONS
    //# var planeArray = new[] { "", "", "line", "plane" };
    //# var typeArray = new[] { "", "Polygon", "Line", "Triangle", "Quad" };
    //# var nameArray = new[] { "", "polygon", "line", "triangle", "quad" };
    //# var scaleArray = new[] { "", "", "0.5", "Constant.OneThird", "0.25" };
    //# for (int d = 2; d < 4; d++) {
    //#     var dp1 = d + 1;
    //#     var dd = d.ToString() + "d";
    //#     var di = d.ToString() + "i";
    //#     var tvec = "V" + dd;
    //#     var tveci = "V" + di;
    //#     var tmat = "M" + d + dd;
    //#     var tmat1 = "M" + dp1 + dp1 + "d";
    //#     var plane = planeArray[d];
    //#     var tpolygon = "Polygon" + dd;
    //#     var tplane = "Plane" + dd;
    //#     var tline = "Line" + dd;
    //#     var tbox = "Box" + dd;
    //#     var thull = "Hull" + dd;
    //#     var ttriangle = "Triangle" + dd;
    //#     var tquad = "Quad" + dd;
    //#     var tidxpoly = "IndexPolygon" + dd;
    //#
    //# for (int pc = 1; pc < 5; pc++) {
    //#     var pcsub1 = pc - 1;
    //#     var type = typeArray[pc] + dd;
    //#     var name = nameArray[pc];
    //#     var isPoly = pc == 1;
    //#     var scale = scaleArray[pc];
    //#
    //# foreach (var isIndexed in new[] { false, true }) {
    //#     if (isIndexed && !isPoly) continue;
    //#     var tipolygon = isIndexed ? tidxpoly : tpolygon;
    //#
    //# if (isPoly) {
    //# if (!isIndexed) {
    #region __tpolygon__

    /// <summary>
    /// A polygon internally represented by an array of points. Implemented
    /// as a structure, the validity of the polygon can be checked via its
    /// PointCount, which must be bigger than 0 for a polygon to hold any
    /// points, and bigger than 2 for a polygon to be geometrically valid.
    /// </summary>
    [StructLayout(LayoutKind.Sequential)]
    public partial struct __tpolygon__ : IValidity, IPolygon<__tvec__>, IBounding__tbox__
    {
        internal int m_pointCount;
        internal __tvec__[] m_pointArray;

        #region Constructors

        /// <summary>
        /// Creates a polygon from given points.
        /// </summary>
        public __tpolygon__(__tvec__[] pointArray, int pointCount)
        {
            if (pointArray != null)
            {
                if (pointCount <= pointArray.Length)
                {
                    m_pointCount = pointCount;
                    m_pointArray = pointArray;
                }
                else
                    throw new ArgumentException(
                                "point count must be smaller or equal array length");
            }
            else
            {
                m_pointCount = 0;
                m_pointArray = null;
            }
        }

        /// <summary>
        /// Creates a polygon from given points.
        /// </summary>
        public __tpolygon__(params __tvec__[] pointArray)
        {
            m_pointCount = pointArray != null ? pointArray.Length : 0;
            m_pointArray = pointArray;
        }

        /// <summary>
        /// Creates a polygon from given points.
        /// </summary>
        public __tpolygon__(__tvec__[] pointArray, int startIndex, int count)
        {
            if (startIndex < 0 || startIndex >= pointArray.Length - 1) throw new ArgumentException();
            if (count <= 0 || startIndex + count >= pointArray.Length) throw new ArgumentException();
            m_pointCount = count;
            m_pointArray = new __tvec__[count];
            for (int i = 0; i < count; i++) m_pointArray[i] = pointArray[startIndex + i];
        }

        /// <summary>
        /// Creates a polygon from point count and point creator function.
        /// </summary>
        public __tpolygon__(int pointCount, Func<int, __tvec__> index_pointCreator)
            : this(new __tvec__[pointCount].SetByIndex(index_pointCreator))
        { }

        /// <summary>
        /// Creates a polygon from a sequence of points.
        /// </summary>
        public __tpolygon__(IEnumerable<__tvec__> points)
            : this(points.ToArray())
        { }

        /// <summary>
        /// Creates a polygon from the points of a pointArray that
        /// are selected by an index array.
        /// </summary>
        public __tpolygon__(int[] indexArray, __tvec__[] pointArray)
            : this(indexArray.Map(i => pointArray[i]))
        { }

        /// <summary>
        /// Creates a polygon from a triangle.
        /// </summary>
        public __tpolygon__(__ttriangle__ triangle)
            : this(triangle.GetPointArray())
        { }

        /// <summary>
        /// Creates a polygon from a quad.
        /// </summary>
        public __tpolygon__(__tquad__ quad)
            : this(quad.GetPointArray())
        { }

        /// <summary>
        /// Copy constructor.
        /// Performs deep copy of original.
        /// </summary>
        public __tpolygon__(__tpolygon__ original)
            : this(original.GetPointArray())
        { }

        #endregion

        #region Constants

        public static readonly __tpolygon__ Invalid = new __tpolygon__(null, 0);

        public bool IsValid => m_pointArray != null;

        public bool IsInvalid => m_pointArray == null;

        #endregion

        #region Properties

        /// <summary>
        /// The number of points in the polygon. If this is 0, the polygon
        /// is invalid.
        /// </summary>
        public int PointCount => m_pointCount;

        /// <summary>
        /// Enumerates points.
        /// </summary>
        public IEnumerable<__tvec__> Points
        {
            get { for (int pi = 0; pi < m_pointCount; pi++) yield return m_pointArray[pi]; }
        }

        #endregion

        #region Conversions

        /// <summary>
        /// Returns a copy of the polygons point array.
        /// </summary>
        public __tvec__[] GetPointArray()
        {
            var pc = m_pointCount;
            var pa = new __tvec__[pc];
            for (int pi = 0; pi < pc; pi++) pa[pi] = m_pointArray[pi];
            return pa;
        }

        /// <summary>
        /// [P0, P1, P2] -> [P0, P1, P2, P0].
        /// </summary>
        public __tvec__[] GetPointArrayWithRepeatedFirstPoint()
        {
            var pc = m_pointCount;
            var pa = new __tvec__[pc + 1];
            for (int pi = 0; pi < pc; pi++) pa[pi] = m_pointArray[pi];
            pa[pc] = pa[0];
            return pa;
        }

        /// <summary>
        /// Returns a transformed copy of the polygons point array.
        /// </summary>
        public T[] GetPointArray<T>(Func<__tvec__, T> point_copyFun)
        {
            var pc = m_pointCount;
            var pa = new T[pc];
            for (int pi = 0; pi < pc; pi++) pa[pi] = point_copyFun(m_pointArray[pi]);
            return pa;
        }

        /// <summary>
        /// Returns a transformed copy of the polygons point array.
        /// </summary>
        public T[] GetPointArray<T>(Func<__tvec__, int, T> point_index_copyFun)
        {
            var pc = m_pointCount;
            var pa = new T[pc];
            for (int pi = 0; pi < pc; pi++) pa[pi] = point_index_copyFun(m_pointArray[pi], pi);
            return pa;
        }

        #endregion

        #region Indexing

        /// <summary>
        /// Gets the index-th point of this polygon.
        /// </summary>
        public __tvec__ this[int index]
        {
            get { return m_pointArray[index]; }
            set { m_pointArray[index] = value; }
        }

        #endregion

        #region Edges and Lines

        /// <summary>
        /// Index-th edge as vector (edgeEndPos - edgeBeginPos).
        /// </summary>
        public __tvec__ Edge(int index)
        {
            var p0 = m_pointArray[index++];
            var p1 = m_pointArray[index < m_pointCount ? index : 0];
            return p1 - p0;
        }

        /// <summary>
        /// Edges as vectors (edgeEndPos - edgeBeginPos).
        /// </summary>
        public IEnumerable<__tvec__> Edges
        {
            get
            {
                var pc = m_pointCount;
                var p = m_pointArray[0];
                var p0 = p;
                for (int pi = 1; pi < pc; pi++)
                {
                    var p1 = m_pointArray[pi];
                    yield return p1 - p0;
                    p0 = p1;
                }
                yield return p - p0;
            }
        }

        /// <summary>
        /// Index-th edge as line segment (edgeBeginPos, edgeEndPos).
        /// </summary>
        public __tline__ EdgeLine(int index)
        {
            var p0 = m_pointArray[index++];
            var p1 = m_pointArray[index < m_pointCount ? index : 0];
            return new __tline__(p0, p1);
        }

        /// <summary>
        /// Edges as line segments (edgeBeginPos, edgeEndPos).
        /// </summary>
        public IEnumerable<__tline__> EdgeLines
        {
            get
            {
                var pc = m_pointCount;
                if (pc < 1) yield break;
                var p0 = m_pointArray[0];
                var p = p0;
                for (int pi = 1; pi < pc; pi++)
                {
                    var p1 = m_pointArray[pi];
                    yield return new __tline__(p0, p1);
                    p0 = p1;
                }
                yield return new __tline__(p0, p);
            }
        }

        /// <summary>
        /// Edges as vectors (edgeEndPos - edgeBeginPos).
        /// </summary>
        public __tvec__[] GetEdgeArray()
        {
            var pc = m_pointCount;
            if (pc < 2) return new __tvec__[0];
            var edgeArray = new __tvec__[pc];
            var p = m_pointArray[0];
            var p0 = p;
            for (int pi = 1; pi < pc; pi++)
            {
                var p1 = m_pointArray[pi];
                edgeArray[pi - 1] = p1 - p0;
                p0 = p1;
            }
            edgeArray[pc - 1] = p - p0;
            return edgeArray;
        }

        /// <summary>
        /// Edges as line segments (edgeBeginPos, edgeEndPos).
        /// </summary>
        public __tline__[] GetEdgeLineArray()
        {
            var pc = PointCount;
            if (pc < 2) return new __tline__[0];
            var ela = new __tline__[pc];
            var p = m_pointArray[0];
            var p0 = p;
            for (int pi = 1; pi < pc; pi++)
            {
                var p1 = m_pointArray[pi];
                ela[pi - 1] = new __tline__(p0, p1);
                p0 = p1;
            }
            ela[pc - 1] = new __tline__(p0, p);
            return ela;
        }

        #endregion

        #region Transformations

        /// <summary>
        /// Returns copy of polygon. Same as Map(p => p).
        /// </summary>
        public __tpolygon__ Copy()
        {
            return new __tpolygon__(m_pointArray.Copy());
        }

        /// <summary>
        /// Obsolete. Use 'Map' instead (same functionality and parameters).
        /// </summary>
        [Obsolete("Use 'Map' instead (same functionality and parameters).", false)]
        public __tpolygon__ Copy(Func<__tvec__, __tvec__> point_fun)
        {
            return Map(point_fun);
        }

        /// <summary>
        /// Returns transformed copy of this polygon.
        /// </summary>
        public __tpolygon__ Map(Func<__tvec__, __tvec__> point_fun)
        {
            var pc = m_pointCount;
            __tvec__[] opa = m_pointArray, npa = new __tvec__[pc];
            for (int pi = 0; pi < pc; pi++) npa[pi] = point_fun(opa[pi]);
            return new __tpolygon__(npa, pc);
        }

        /// <summary>
        /// Gets copy with reversed order of vertices.
        /// </summary>
        public __tpolygon__ Reversed
        {
            get
            {
                var pc = m_pointCount;
                __tvec__[] opa = m_pointArray, npa = new __tvec__[pc];
                for (int pi = 0, pj = pc - 1; pi < pc; pi++, pj--) npa[pi] = opa[pj];
                return new __tpolygon__(npa, pc);
            }
        }

        /// <summary>
        /// Obsolete. Use 'Reverse' instead..
        /// </summary>
        [Obsolete("Use 'Reverse' instead.", false)]
        public void Revert() => Reverse();

        /// <summary>
        /// Reverses order of vertices in-place.
        /// </summary>
        public void Reverse()
        {
            var pa = m_pointArray;
            for (int pi = 0, pj = m_pointCount - 1; pi < pj; pi++, pj--)
            { var t = pa[pi]; pa[pi] = pa[pj]; pa[pj] = t; }
        }

        #endregion

        #region Comparisons

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static bool operator ==(__tpolygon__ a, __tpolygon__ b)
        {
            if (a.m_pointCount != b.m_pointCount) return false;
            for (int pi = 0; pi < a.m_pointCount; pi++)
                if (a.m_pointArray[pi] != b.m_pointArray[pi]) return false;
            return true;
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static bool operator !=(__tpolygon__ a, __tpolygon__ b)
            => !(a == b);

        #endregion

        #region Overrides

        public override int GetHashCode()
        {
            return m_pointArray.GetCombinedHashCode(m_pointCount);
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public bool Equals(__tpolygon__ other)
        {
            if (m_pointCount != other.m_pointCount) return false;
            for (int pi = 0; pi < m_pointCount; pi++)
                if (!m_pointArray[pi].Equals(other.m_pointArray[pi])) return false;
            return true;
        }

        public override bool Equals(object other)
            => (other is __tpolygon__ o) ? Equals(o) : false;

        public override string ToString()
        {
            return string.Format(CultureInfo.InvariantCulture,
                "[{0}]", Points.Select(x => x.ToString()).Join(", ")
                );
        }

        public static __tpolygon__ Parse(string s)
        {
            var va = s.NestedBracketSplitLevelOne().ToArray();
            return new __tpolygon__(va.Select(x => __tvec__.Parse(x)));
        }

        #endregion

        #region IBounding__tbox__ Members

        /// <summary>
        /// Bounding box of polygon.
        /// </summary>
        public __tbox__ Bounding__tbox__
        {
            get { return new __tbox__(m_pointArray, 0, m_pointCount); }
        }

        #endregion
    }

    public static partial class Fun
    {
        /// <summary>
        /// Returns whether the given <see cref="__tpolygon__"/> are equal within the given tolerance.
        /// </summary>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static bool ApproximateEquals(this __tpolygon__ a, __tpolygon__ b, double tolerance)
        {
            if (a.m_pointCount != b.m_pointCount) return false;
            for (int pi = 0; pi < a.m_pointCount; pi++)
                if (!ApproximateEquals(a.m_pointArray[pi], b.m_pointArray[pi], tolerance)) return false;
            return true;
        }

        /// <summary>
        /// Returns whether the given <see cref="__tpolygon__"/> are equal within
        /// Constant<double>.PositiveTinyValue.
        /// </summary>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static bool ApproximateEquals(this __tpolygon__ a, __tpolygon__ b)
            => ApproximateEquals(a, b, Constant<double>.PositiveTinyValue);
    }

    #endregion

    //# } // !isIndexed
    //# if (isIndexed) {
    #region __tidxpoly__

    [StructLayout(LayoutKind.Sequential)]
    public partial struct __tidxpoly__ : IValidity, IPolygon<__tvec__>
    {
        private int m_pointCount;
        private int m_firstIndex;
        private int[] m_indexArray;
        private __tvec__[] m_pointArray;

        #region Constructors

        public __tidxpoly__(int[] indexArray, int firstIndex, int pointCount, __tvec__[] pointArray)
        {
            m_indexArray = indexArray;
            m_firstIndex = firstIndex;
            m_pointCount = pointCount;
            m_pointArray = pointArray;
        }

        public __tidxpoly__(__tvec__[] pointArray, int firstIndex, int pointCount)
            : this(new int[pointCount].SetByIndex(i => firstIndex + i), 0, pointCount, pointArray)
        { }

        public __tidxpoly__(__tvec__[] pointArray)
            : this(new int[pointArray.Length].SetByIndex(i => i), 0, pointArray.Length, pointArray)
        { }

        #endregion

        #region Constants

        public static readonly __tidxpoly__ Invalid = new __tidxpoly__(null, 0, 0, null);

        #endregion

        #region Properties

        public bool IsValid { get { return m_indexArray != null && m_pointArray != null; } }
        public bool IsInvalid { get { return m_indexArray == null || m_pointArray == null; } }

        public int PointCount
        {
            get { return m_pointCount; }
        }

        public int FirstIndex { get { return m_firstIndex; } }

        /// <summary>
        /// The index array that contains the point indices of the
        /// index polygon at the index range [FirstIndex, FirstIndex + PointCount).
        /// NOTE: This is different from the array returned by GetIndexArray().
        /// </summary>
        public int[] IndexArray { get { return m_indexArray; } }

        /// <summary>
        /// The point array that contains the points referenced by
        /// the index array. Note: This is different from the array
        /// returned by GetPointArray().
        /// </summary>
        public __tvec__[] PointArray { get { return m_pointArray; } }

        public IEnumerable<__tvec__> Points
        {
            get
            {
                for (int i = 0; i < m_pointCount; i++)
                    yield return m_pointArray[m_indexArray[m_firstIndex + i]];
            }
        }

        public IEnumerable<int> Indices
        {
            get
            {
                for (int i = 0; i < m_pointCount; i++)
                    yield return m_indexArray[m_firstIndex + i];
            }
        }

        #endregion

        #region Indexing

        public __tvec__ this[int index]
        {
            get { return m_pointArray[m_indexArray[m_firstIndex + index]]; }
            set { m_pointArray[m_indexArray[m_firstIndex + index]] = value; }
        }

        #endregion

        #region Conversions

        public void ForEachIndex(Action<int> index_act)
        {
            var ia = m_indexArray; int fi = m_firstIndex;
            for (int i = 0; i < m_pointCount; i++) index_act(ia[fi + i]);
        }

        /// <summary>
        /// Returns a newly created array containing only the actual indices
        /// of the index polygon. NOTE: This is different from the
        /// IndexArray property!
        /// </summary>
        public int[] GetIndexArray()
        {
            return m_indexArray.Copy(m_firstIndex, m_pointCount);
        }

        /// <summary>
        /// Returns a newly created array containing only the actual points
        /// of the index polygon. NOTE: This is different from the
        /// PointArray property!
        /// </summary>
        public __tvec__[] GetPointArray()
        {
            var pa = m_pointArray;
            return m_indexArray.Map(m_firstIndex, m_pointCount, i => pa[i]);
        }

        public T[] GetPointArray<T>(T[] pointArray)
        {
            return m_indexArray.Map(m_firstIndex, m_pointCount, i => pointArray[i]);
        }

        public T[] GetPointArray<T>(List<T> pointList)
        {
            return m_indexArray.Map(m_firstIndex, m_pointCount, i => pointList[i]);
        }

        #endregion
    }

    #endregion

    //# } // isIndexed
    #region __tipolygon__Extensions

    public static partial class __tipolygon__Extensions
    {
        //# if (isIndexed) {
        #region Conversions

        public static __tpolygon__ To__tpolygon__(this __tipolygon__ polygon)
        {
            return new __tpolygon__(polygon.GetPointArray());
        }

        #endregion

        //# } // isIndexed
        #region Geometric Properties

        /// <summary>
        /// The vertex centroid is the average of the vertex coordinates.
        /// </summary>
        public static __tvec__ ComputeVertexCentroid(this __tipolygon__ polygon)
        {
            var sum = __tvec__.Zero;
            int pc = polygon.PointCount;
            for (int i = 0; i < pc; i++) sum += polygon[i];
            var scale = 1.0 / (double)pc;
            return sum * scale;
        }

        public static double ComputePerimeter(this __tipolygon__ polygon)
        {
            var pc = polygon.PointCount;
            var p0 = polygon[pc - 1];
            var r = 0.0;
            for (int i = 0; i < pc; i++)
            {
                var p1 = polygon[i];
                r += Vec.Distance(p0, p1);
                p0 = p1;
            }
            return r;
        }

        #endregion
        //# if (!isIndexed) {

        #region Geometric Transformations

        public static __tpolygon__ Scaled(
                this __tpolygon__ polygon, double scale)
        {
            return polygon.Map(p => p * scale);
        }

        public static __tpolygon__ Scaled(
                this __tpolygon__ polygon, __tvec__ center, double scale)
        {
            return polygon.Map(p => center + (p - center) * scale);
        }

        public static __tpolygon__ ScaledAboutVertexCentroid(
                this __tpolygon__ polygon, double scale)
        {
            return polygon.Scaled(polygon.ComputeVertexCentroid(), scale);
        }

        public static __tpolygon__ Scaled(
                this __tpolygon__ polygon, __tvec__ scale)
        {
            return polygon.Map(p => p * scale);
        }

        public static __tpolygon__ Scaled(
                this __tpolygon__ polygon, __tvec__ center, __tvec__ scale)
        {
            return polygon.Map(p => center + (p - center) * scale);
        }

        public static __tpolygon__ ScaledAboutVertexCentroid(
                this __tpolygon__ polygon, __tvec__ scale)
        {
            return polygon.Scaled(polygon.ComputeVertexCentroid(), scale);
        }

        public static __tpolygon__ Transformed(
                this __tpolygon__ polygon, __tmat__ m)
        {
            return polygon.Map(p => m.Transform(p));
        }

        public static __tpolygon__ Transformed(
                this __tpolygon__ polygon, __tmat1__ m)
        {
            return polygon.Map(p => m.TransformPos(p));
        }

        public static __tpolygon__ WithoutMultiplePoints(
                this __tpolygon__ polygon, double eps = 1e-8)
        {
            eps *= eps;
            var opc = polygon.PointCount;
            var pa = new __tvec__[opc];
            var pc = 0;
            pa[0] = polygon[0];
            for (int pi = 1; pi < opc; pi++)
                if (Vec.DistanceSquared(pa[pc], polygon[pi]) > eps)
                    pa[++pc] = polygon[pi];
            if (Vec.DistanceSquared(pa[pc], polygon[0]) > eps)
                ++pc;
            return new __tpolygon__(pa, pc);
        }

        #endregion

        #region Clipping

        /// <summary>
        /// Clip the supplied polygon at the supplied __plane__. The method should
        /// work with all non-selfintersecting polygons. Returns all parts of
        /// the polygon that are at the positive side of the __plane__.
        /// </summary>
        public static __tpolygon__ ConvexClipped(
                this __tpolygon__ polygon, __tplane__ __plane__, double eps = 1e-8)
        {
            var opc = polygon.PointCount;
            __tvec__[] pa = new __tvec__[opc + 1];
            var pc = 0;
            var pf = polygon[0];
            var hf = __plane__.Height(pf); bool hfp = hf > eps, hfn = hf < -eps;
            if (hf >= -eps) pa[pc++] = pf;
            var p0 = pf; var h0 = hf; var h0p = hfp; var h0n = hfn;
            for (int vi = 1; vi < opc; vi++)
            {
                var p1 = polygon[vi];
                var h1 = __plane__.Height(p1); bool h1p = h1 > eps, h1n = h1 < -eps;
                if (h0p && h1n || h0n && h1p) pa[pc++] = p0 + (p1 - p0) * (h0 / (h0 - h1));
                if (h1 >= -eps) pa[pc++] = p1;
                p0 = p1; h0 = h1; h0p = h1p; h0n = h1n;
            }
            if (h0p && hfn || h0n && hfp) pa[pc++] = p0 + (pf - p0) * (h0 / (h0 - hf));
            return new __tpolygon__(pa, pc);
        }

        /// <summary>
        /// Returns the convex polygon clipped by the set of __plane__s (defined
        /// as __tplane__s), i.e. all parts of the polygon that are at the positive
        /// side of the __plane__s.
        /// </summary>
        public static __tpolygon__ ConvexClipped(
                this __tpolygon__ polygon, __tplane__[] __plane__s, double eps = 1e-8)
        {
            foreach (var c in __plane__s)
            {
                polygon = polygon.ConvexClipped(c, eps);
                if (polygon.PointCount == 0) break;
            }
            return polygon;
        }

        /// <summary>
        /// Returns the polygon clipped by the hull, i.e. all parts of the
        /// polygon that are at the positive side of the hull __plane__s.
        /// </summary>
        public static __tpolygon__ ConvexClipped(
                this __tpolygon__ polygon, __thull__ hull, double eps = 1e-8)
        {
            return polygon.ConvexClipped(hull.PlaneArray, eps);
        }

        /// <summary>
        /// TODO summary.
        /// </summary>
        public static __tpolygon__ ConvexClipped(
                this __tpolygon__ polygon, __tbox__ box, double eps = 1e-8)
        {
            var __plane__s = new[]
            {
                //# Meta.VecFields.Take(d).ForEach(axis => {
                new __tplane__(__tvec__.__axis__Axis, box.Min), new __tplane__(-__tvec__.__axis__Axis, box.Max),
                //# });
            };
            return polygon.ConvexClipped(__plane__s);
        }

        #endregion
        //# } // !isIndexed
    }

    #endregion

    //# } else { // !isPoly
    #region __type__

    [StructLayout(LayoutKind.Sequential)]
    public partial struct __type__ : IValidity, IPolygon<__tvec__>, IBounding__tbox__
    {
        public __tvec__ /*# pc.ForEach(i => { */P__i__/*# }, Sep(", ")); */;

        #region Constructors

        /// <summary>
        /// Creates __name__ from __pc__ points.
        /// </summary>
        public __type__(/*# pc.ForEach(i => { */__tvec__ p__i__/*# }, Sep(", ")); */)
        {
            /*# pc.ForEach(i => { */P__i__ = p__i__/*# }, Sep("; ")); */;
        }

        /// <summary>
        /// Creates __name__ from first __pc__ points in the sequence.
        /// </summary>
        public __type__(IEnumerable<__tvec__> points)
        {
            var pa = points.TakeToArray(__pc__);
            /*# pc.ForEach(i => { */P__i__ = pa[__i__]/*# }, Sep("; ")); */;
        }

        //# if (pc == 4) {
        /// <summary>
        /// Creates quad from point and two vectors representing edges.
        /// </summary>
        public __type__(__tvec__ p0, __tvec__ edge01, __tvec__ edge03)
        {
            P0 = p0;
            P1 = p0 + edge01;
            P2 = P1 + edge03;
            P3 = p0 + edge03;
        }

        //# }
        #endregion

        #region Properties

        public bool IsValid { get { return true; } }
        public bool IsInvalid { get { return false; } }

        //# if (pc > 2) {
        //# pc.ForEach(i => { foreach (var j in new[] { (i + 1) % pc, (i + pcsub1) % pc }) {
        /// <summary>
        /// Edge P__j__ - P__i__
        /// </summary>
        public __tvec__ Edge__i____j__ { get { return P__j__ - P__i__; } }
        //# } });

        public IEnumerable<__tvec__> Edges
        {
            get
            {
                //# pc.ForEach(i => { var j = (i + 1) % pc;
                yield return P__j__ - P__i__;
                //# });
            }
        }

        public __tvec__[] EdgeArray
        {
            get
            {
                var a = new __tvec__[__pc__];
                //# pc.ForEach(i => { var j = (i + 1) % pc;
                a[__i__] = P__j__ - P__i__;
                //# });
                return a;
            }
        }

        public IEnumerable<__tline__> EdgeLines
        {
            get
            {
                //# pc.ForEach(i => { var j = (i + 1) % pc;
                yield return new __tline__(P__i__, P__j__);
                //# });
            }
        }

        public __tline__[] EdgeLineArray
        {
            get
            {
                var a = new __tline__[__pc__];
                //# pc.ForEach(i => { var j = (i + 1) % pc;
                a[__i__] = new __tline__(P__i__, P__j__);
                //# });
                return a;
            }
        }

        public __tline__ GetEdgeLine(int index)
        {
            switch (index)
            {
                //# pc.ForEach(i => { var j = (i + 1) % pc;
                case __i__: return new __tline__(P__i__, P__j__);
                //# });
            }
            throw new InvalidOperationException();
        }

        public __tvec__ GetEdge(int index)
        {
            switch (index)
            {
                //# pc.ForEach(i => { var j = (i + 1) % pc;
                case __i__: return P__j__ - P__i__;
                //# });
            }
            throw new InvalidOperationException();
        }

        //# pc.ForEach(i => { foreach (var j in new[] { (i + 1) % pc, (i + pcsub1) % pc }) {
        public __tline__ Line__i____j__ { get { return new __tline__(P__i__, P__j__); } }
        //# } });

        //# } // pc > 2
        public int PointCount { get { return __pc__; } }

        public IEnumerable<__tvec__> Points
        {
            get { /*# pc.ForEach(i => { */yield return P__i__/*# }, Sep("; ")); */; }
        }

        public __type__ Reversed
        {
            get { return new __type__(/*# pc.ForEach(i => { var j = pcsub1 - i; */P__j__/*# }, Sep(", ")); */); }
        }

        #endregion

        #region Indexer

        public __tvec__ this[int index]
        {
            get
            {
                switch (index)
                {
                    //# pc.ForEach(i => {
                    case __i__: return P__i__;
                    //# });
                    default: throw new IndexOutOfRangeException();
                }
            }
            set
            {
                switch (index)
                {
                    //# pc.ForEach(i => {
                    case __i__: P__i__ = value; return;
                    //# });
                    default: throw new IndexOutOfRangeException();
                }
            }
        }

        #endregion

        #region Transformations

        public __type__ Copy(Func<__tvec__, __tvec__> point_copyFun)
        {
            return new __type__(/*# pc.ForEach(i => { */point_copyFun(P__i__)/*# }, Sep(", ")); */);
        }

        //# for (int od = 2; od < 4; od++) { if (d == od) continue;
        //#     var otype = typeArray[pc] + od + "d"; var otvec = "V" + od + "d";
        public __otype__ To__otype__(Func<__tvec__, __otvec__> point_copyFun)
        {
            return new __otype__(/*# pc.ForEach(i => { */point_copyFun(P__i__)/*# }, Sep(", ")); */);
        }

        //# } // od
        #endregion

        #region Comparisons

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static bool operator ==(__type__ a, __type__ b)
            => /*# pc.ForEach(i => { */(a.P__i__ == b.P__i__)/*# }, Sep(" && ")); */;

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static bool operator !=(__type__ a, __type__ b)
            => !(a == b);

        #endregion

        #region Overrides

        public override int GetHashCode()
        {
            return HashCode.GetCombined(/*# pc.ForEach(i => { */P__i__/*# }, Sep(", ")); */);
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public bool Equals(__type__ other)
            => /*# pc.ForEach(i => { */P__i__.Equals(other.P__i__)/*# }, Sep(" && ")); */;

        public override bool Equals(object other)
             => (other is __type__ o) ? Equals(o) : false;

        public override string ToString()
        {
            //# var format = "["; pc.ForEach(i => format += "{" + i + "}", () => format += ", "); format += "]";
            return string.Format(CultureInfo.InvariantCulture, "__format__", /*# pc.ForEach(i => { */P__i__/*# }, Sep(", ")); */);
        }

        public static __type__ Parse(string s)
        {
            var x = s.NestedBracketSplitLevelOne().ToArray();
            return new __type__(/*# pc.ForEach(i => { */__tvec__.Parse(x[__i__])/*# }, Sep(", ")); */);
        }

        #endregion

        #region IBounding__tbox__ Members

        public __tbox__ Bounding__tbox__
        {
            get
            {
                return new __tbox__(/*# pc.ForEach(i => { */P__i__/*# }, Sep(", "));
                                        */)/*#if (pc == 2) {*/.Repair()/*# } */;
            }
        }

        #endregion
    }

    public static partial class Fun
    {
        /// <summary>
        /// Returns whether the given <see cref="__type__"/> are equal within the given tolerance.
        /// </summary>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static bool ApproximateEquals(this __type__ a, __type__ b, double tolerance)
            => /*# pc.ForEach(i => { */ApproximateEquals(a.P__i__, b.P__i__, tolerance)/*# }, Sep(" && ")); */;

        /// <summary>
        /// Returns whether the given <see cref="__type__"/> are equal within
        /// Constant<double>.PositiveTinyValue.
        /// </summary>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static bool ApproximateEquals(this __type__ a, __type__ b)
            => ApproximateEquals(a, b, Constant<double>.PositiveTinyValue);
    }

    #endregion

    #region __type__Extensions

    public static partial class __type__Extensions
    {
        public static __tvec__[] GetPointArray(this __type__ __name__)
        {
            var pa = new __tvec__[__pc__];
            //# pc.ForEach(i => {
            pa[__i__] = __name__.P__i__;
            //# });
            return pa;
        }

        public static __tvec__ ComputeCentroid(this __type__ __name__)
        {
            return __scale__ * (/*# pc.ForEach(i => { */__name__.P__i__/*# }, Sep(" + ")); */);
        }
    }

    #endregion

    //# } // !isPoly
    //# } // isIndexed
    //# } // pc
    //# } // d
    //# } // POLYGONS
    //# { // ELLIPSES
    //# for (int d = 2; d < 4; d++) {
    //#     var vt = "V" + d + "d";
    //#     var et = "Ellipse" + d + "d";
    #region __et__

    /// <summary>
    /// A __d__D ellipse is defined by its center/*# if (d == 3) { */, its plane normal,/*# } */
    /// and two half-axes.
    /// Note that in principle any two conjugate half-diameters
    /// can be used as axes, however some algorithms require that
    /// the major and minor half axes are known. By convention
    /// in this case, axis0 is the major half axis.
    /// </summary>
    [StructLayout(LayoutKind.Sequential)]
    public partial struct __et__
    {
        public __vt__ Center;
        //# if (d == 3) {
        public __vt__ Normal;
        //# }
        public __vt__ Axis0;
        public __vt__ Axis1;

        #region Constructors

        public __et__(__vt__ center, /*# if (d == 3) { */__vt__ normal, /*# } */__vt__ axis0, __vt__ axis1)
        {
            Center = center;
            //# if (d == 3) {
            Normal = normal;
            //# }
            Axis0 = axis0;
            Axis1 = axis1;
        }

        /// <summary>
        /// Construct ellipse from two conjugate diameters, and set
        /// Axis0 to the major axis and Axis1 to the minor axis.
        /// The algorithm was constructed from first principles.
        /// </summary>
        public static __et__ FromConjugateDiameters(__vt__ center, /*# if (d == 3) { */__vt__ normal, /*# } */__vt__ a, __vt__ b)
        {
            var ab = Vec.Dot(a, b);
            double a2 = a.LengthSquared, b2 = b.LengthSquared;
            if (ab.IsTiny())
            {
                if (a2 >= b2)   return new __et__(center, /*# if (d == 3) { */normal, /*# } */a, b);
                else            return new __et__(center, /*# if (d == 3) { */normal, /*# } */b, a);
            }
            else
            {
                var t = 0.5 * Fun.Atan2(2 * ab, a2 - b2);
                double ct = Fun.Cos(t), st = Fun.Sin(t);
                __vt__ v0 = a * ct + b * st, v1 = b * ct - a * st;
                if (v0.LengthSquared >= v1.LengthSquared)   return new __et__(center, /*# if (d == 3) { */normal, /*# } */v0, v1);
                else                                        return new __et__(center, /*# if (d == 3) { */normal, /*# } */v1, v0);
            }
        }

        /// <summary>
        /// Construct ellipse from two conjugate diameters, and set
        /// Axis0 to the major axis and Axis1 to the minor axis.
        /// The algorithm was constructed from first principles.
        /// Also computes the squared lengths of the major and minor
        /// half axis.
        /// </summary>
        public static __et__ FromConjugateDiameters(__vt__ center, /*# if (d == 3) { */__vt__ normal, /*# } */__vt__ a, __vt__ b,
                out double major2, out double minor2)
        {
            var ab = Vec.Dot(a, b);
            double a2 = a.LengthSquared, b2 = b.LengthSquared;
            if (ab.IsTiny())
            {
                if (a2 >= b2)   { major2 = a2; minor2 = b2; return new __et__(center, /*# if (d == 3) { */normal, /*# } */a, b); }
                else            { major2 = b2; minor2 = a2; return new __et__(center, /*# if (d == 3) { */normal, /*# } */b, a); }
            }
            else
            {
                var t = 0.5 * Fun.Atan2(2 * ab, a2 - b2);
                double ct = Fun.Cos(t), st = Fun.Sin(t);
                __vt__ v0 = a * ct + b * st, v1 = b * ct - a * st;
                a2 = v0.LengthSquared; b2 = v1.LengthSquared;
                if (a2 >= b2)   { major2 = a2; minor2 = b2; return new __et__(center, /*# if (d == 3) { */normal, /*# } */v0, v1); }
                else            { major2 = b2; minor2 = a2; return new __et__(center, /*# if (d == 3) { */normal, /*# } */v1, v0); }
            }
        }

        #endregion

        #region Constants

        public static readonly __et__ Zero = new __et__(__vt__.Zero, /*# if (d == 3) { */__vt__.Zero, /*# } */__vt__.Zero, __vt__.Zero);

        #endregion

        #region Operations

        public __vt__ GetVector(double alpha)
        {
            return Axis0 * Fun.Cos(alpha) + Axis1 * Fun.Sin(alpha);
        }

        public __vt__ GetPoint(double alpha)
        {
            return Center + Axis0 * Fun.Cos(alpha) + Axis1 * Fun.Sin(alpha);
        }

        /// <summary>
        /// Perform the supplied action for each of count vectors from the center
        /// of the ellipse to the circumference.
        /// </summary>
        public void ForEachVector(int count, Action<int, __vt__> index_vector_act)
        {
            double d = Constant.PiTimesTwo / count;
            double a = Fun.Sin(d * 0.5).Square() * 2.0, b = Fun.Sin(d); // init trig. recurrence
            double ct = 1.0, st = 0.0;

            index_vector_act(0, Axis0);
            for (int i = 1; i < count; i++)
            {
                double dct = a * ct + b * st, dst = a * st - b * ct; ;  // trig. recurrence
                ct -= dct; st -= dst;                                   // cos (t + d), sin (t + d)
                index_vector_act(i, Axis0 * ct + Axis1 * st);
            }
        }

        /// <summary>
        /// Get count points on the circumference of the ellipse.
        /// </summary>
        public __vt__[] GetPoints(int count)
        {
            var array = new __vt__[count];
            var c = Center;
            ForEachVector(count, (i, v) => array[i] = c + v);
            return array;
        }

        #endregion

        #region Comparisons

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static bool operator ==(__et__ a, __et__ b) =>
            (a.Center == b.Center) &&
            //# if (d == 3) {
            (a.Normal == b.Normal) &&
            //# }
            (a.Axis0 == b.Axis0) &&
            (a.Axis1 == b.Axis1);

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static bool operator !=(__et__ a, __et__ b)
            => !(a == b);

        #endregion

        #region Overrides

        public override int GetHashCode()
        {
            return HashCode.GetCombined(Center, /*# if (d == 3) { */Normal, /*# }*/Axis0, Axis1);
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public bool Equals(__et__ other) =>
            Center.Equals(other.Center) &&
            //# if (d == 3) {
            Normal.Equals(other.Normal) &&
            //# }
            Axis0.Equals(other.Axis0) &&
            Axis1.Equals(other.Axis1);

        public override bool Equals(object other)
             => (other is __et__ o) ? Equals(o) : false;

        public override string ToString()
        {
            //# if (d == 3) {
            return string.Format(CultureInfo.InvariantCulture, "[{0}, {1}, {2}, {3}]", Center, Normal, Axis0, Axis1);
            //# } else {
            return string.Format(CultureInfo.InvariantCulture, "[{0}, {1}, {2}]", Center, Axis0, Axis1);
            //# }
        }

        public static __et__ Parse(string s)
        {
            var x = s.NestedBracketSplitLevelOne().ToArray();
            return new __et__(
                __vt__.Parse(x[0]),
                __vt__.Parse(x[1]),
                __vt__.Parse(x[2])/*# if (d == 3) { */,
                __vt__.Parse(x[3])/*# }*/
            );
        }

        #endregion
    }

    public static partial class Fun
    {
        /// <summary>
        /// Returns whether the given <see cref="__et__"/> are equal within the given tolerance.
        /// </summary>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static bool ApproximateEquals(this __et__ a, __et__ b, double tolerance) =>
            ApproximateEquals(a.Center, b.Center, tolerance) &&
            //# if (d == 3) {
            ApproximateEquals(a.Normal, b.Normal, tolerance) &&
            //# }
            ApproximateEquals(a.Axis0, b.Axis0, tolerance) &&
            ApproximateEquals(a.Axis1, b.Axis1, tolerance);

        /// <summary>
        /// Returns whether the given <see cref="__et__"/> are equal within
        /// Constant<double>.PositiveTinyValue.
        /// </summary>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static bool ApproximateEquals(this __et__ a, __et__ b)
            => ApproximateEquals(a, b, Constant<double>.PositiveTinyValue);
    }

    #endregion

    //# } // d
    //# } // ELLIPSES
}


text:
import wx
from cairis.core.armid import *
import WidgetFactory

__author__ = 'Shamal Faily'

class RevisionEntryDialog(wx.Dialog):
  def __init__(self,parent):
    wx.Dialog.__init__(self,parent,REVISIONENTRY_ID,'Add Revision',style=wx.DEFAULT_DIALOG_STYLE|wx.MAXIMIZE_BOX|wx.THICK_FRAME|wx.RESIZE_BORDER,size=(300,300))
    self.theRemarks = ''
    mainSizer = wx.BoxSizer(wx.VERTICAL)

    mainSizer.Add(WidgetFactory.buildMLTextSizer(self,'Remarks',(87,30),REVISIONENTRY_TEXTREMARKS_ID),1,wx.EXPAND)
    mainSizer.Add(WidgetFactory.buildAddCancelButtonSizer(self,REVISIONENTRY_BUTTONCOMMIT_ID),0,wx.ALIGN_CENTER)
    self.SetSizer(mainSizer)

    wx.EVT_BUTTON(self,REVISIONENTRY_BUTTONCOMMIT_ID,self.onCommit)
    self.commitLabel = 'Add'

  def onCommit(self,evt):
    remarksCtrl = self.FindWindowById(REVISIONENTRY_TEXTREMARKS_ID)
    self.theRemarks = remarksCtrl.GetValue()
    if (len(self.theRemarks) == 0):
      dlg = wx.MessageDialog(self,'No revision remarks','Add revision',wx.OK)
      dlg.ShowModal()
      dlg.Destroy()
      return
    else:
      self.EndModal(REVISIONENTRY_BUTTONCOMMIT_ID)

  def remarks(self): return self.theRemarks


text:
using System;
using System.Diagnostics;

namespace TypeLess.Debugging
{
    public class PerfLogger
    {
        private long ticks;
        private long ticksBetween;
        private string msg;

        private Action<string> _output;

        public PerfLogger Start(string msg = "", Action<string> output = null)
        {
            ticks = DateTime.UtcNow.Ticks;
            ticksBetween = ticks;
            this.msg = msg;

            if (output == null)
            {
#if DEBUG
                _output = x => Debug.WriteLine(x);
#else
                _output = x => { };
#endif
            }
            else
            {
                _output = output;
            }

            _output("START -> " + msg);
            return this;
        }

        public TimeSpan Total { get; set; }

        public void Log(string msg2)
        {
            if (msg2 != null)
            {
                _output(msg + " MSG: " + msg2 + " Duration: " + TimeSpan.FromTicks(DateTime.UtcNow.Ticks - ticksBetween).ToString("mm\\:ss\\:fff") + " Time: " + TimeSpan.FromTicks(DateTime.UtcNow.Ticks - ticks).ToString("mm\\:ss\\:fff"));
                ticksBetween = DateTime.UtcNow.Ticks;
            }
        }

        public TimeSpan End()
        {
            Total = TimeSpan.FromTicks(DateTime.UtcNow.Ticks - ticks);
            _output("END -> " + msg + " TOTAL Duration: " + Total.ToString("mm\\:ss\\:fff"));
            return Total;
        }
    }
}


text:
<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Kapster_model extends CI_Model {
	public function __construct() {
        parent::__construct();
		}
	public function create(){
		$data = array('nama_kapster'=>$this->input->post('nama_kapster')
					);
		$this->db->insert('kapster3',$data);
	}
	public function createCashier(){
		$data = array('nama_cashier'=>$this->input->post('nama_cashier'),
						 'rate_cashier'=>$this->input->post('rate')
					);
		$this->db->insert('cashier3',$data);
	}
	public function createRange(){
		$this->db->select('range_atas, range_bawah, rate_gaji, id_range');
		$this->db->from('range_gaji');
		$this->db->where('rate_gaji',$this->input->post('rate_gaji'));
		$query = $this->db->get();
		if($query->num_rows() > 0){
			return false;
		}else{
			$data = array('range_atas'=>$this->input->post('range_atas'),
					'range_bawah'=>$this->input->post('range_bawah'),
					'rate_gaji'=>$this->input->post('rate_gaji')
				);
			$this->db->insert('range_gaji',$data);
			return true;
		}

	}
	public function loadData() {
		$query = $this->db->get('kapster3');

		if ($query->num_rows() > 0) {
			return $query->result();
		} else {
			return 0;
		}
    }
	public function loadDataCashier() {
		$query = $this->db->get('cashier3');
		if ($query->num_rows() > 0) {
			return $query->result();
		} else {
			return 0;
		}
    }
	public function loadRange() {
		$this->db->select('range_atas, range_bawah, rate_gaji, id_range');
		$this->db->from('range_gaji');
		$this->db->order_by('range_atas','DESC');
		$query = $this->db->get();
		if ($query->num_rows() > 0) {
			return $query->result();
		} else {
			return 0;
		}
    }
	public function loadRange2() {
		$this->db->select('range_atas, range_bawah, rate_gaji, id_range');
		$this->db->from('range_gaji');
		$this->db->order_by('range_atas','ASC');
		$query = $this->db->get();
		if ($query->num_rows() > 0) {
			return $query->result();
		} else {
			return 0;
		}
    }
	function updateKapster($id){
		$data = array(	'nama_kapster'=>$this->input->post('nama_kapster')
		);
		$this->db->where('id_kapster', $id);
		$this->db->update('kapster3',$data);
	}
	function updateCashier($id){
		$data = array('nama_cashier'=>$this->input->post('nama_cashier'),
						 'rate_cashier'=>$this->input->post('rate')
		);
		$this->db->where('id_cashier', $id);
		$this->db->update('cashier3',$data);
	}
	function getKapster($id){
		$this->db->where('id_kapster', $id);
		$query = $this->db->get('kapster3');
        return $query->result();
	 }
	function getCashier($id){
		$this->db->where('id_cashier', $id);
		$query = $this->db->get('cashier3');
        return $query->result();
	 }
	function delete($id) {
	$this -> db -> where('id_kapster',$id);
	return $this -> db -> delete('kapster3');
	}
	function updateRange($id){
		$data = array('range_atas'=>$this->input->post('range_atas'),
						'range_bawah'=>$this->input->post('range_bawah'),
						'rate_gaji'=>$this->input->post('rate_gaji')
		);
		$this->db->where('id_range', $id);
		$this->db->update('range_gaji',$data);
	}
	function getRange($id){
		$this->db->where('id_range', $id);
		$query = $this->db->get('range_gaji');
        return $query->result();
	 }
	function deleteRange($id) {
	$this -> db -> where('id_range',$id);
	return $this -> db -> delete('range_gaji');
	}
	function deleteCashier($id) {
	$this -> db -> where('id_cashier',$id);
	return $this -> db -> delete('cashier3');
	}
}


text:
FENNEL_BEGIN_CPPFILE("$Id$");

/**
 * The official SQL-92 standard (ISO/IEC 9075:1992).  To reference
 * this standard from comments on methods that implement its rules, use
 * the format
 * <SectionId> [ ItemType <ItemId> ],
 * where
 *
 *

 *
 *
SectionId is the numbered or named section in the table of
 *contents, e.g. "Section 4.18.9" or "Annex A"
 *
 *
 *
ItemType is one of { Table, Syntax Rule, Access Rule,
 *General Rule, or Leveling Rule }
 *
 *
ItemId is a dotted path expression to the specific item
 *
 *

 *
 * For example,
 *
 *
SQL92 Section 11.4 Syntax Rule 7.c

 *
 * is a well-formed reference to the rule for the default character
 * set to use for column definitions of character type.
 */
struct SQL92
{
    // NOTE:  dummy class for doxygen
};

/**
 * The official SQL:1999 standard (ISO/IEC 9075:1999), which
 * is broken up into five parts.  To reference
 * this standard from comments on methods that implement its rules, use
 * the format
 * <PartId> <SectionId>
 * [ ItemType <ItemId> ], where
 *
 *

 *
 *
PartId is the numbered part (up to Part 5)
 *
 *
SectionId is the numbered or named section in the part's
 *table of contents, e.g. "Section 4.18.9" or "Annex A"
 *
 *
ItemType is one of { Table, Syntax Rule, Access Rule,
 *General Rule, or Conformance Rule }
 *
 *
ItemId is a dotted path expression to the specific item
 *
 *

 *
 * For example,
 *
 *
SQL99 Part 2 Section 11.4 Syntax Rule 7.b

 *
 * is a well-formed reference to the rule for the default character
 * set to use for column definitions of character type.
 */
struct SQL99
{
    // NOTE:  dummy class for doxygen
};

/**
 * The official SQL:2003 standard (ISO/IEC 9075:2003), which
 * is broken up into numerous parts.  To reference
 * this standard from comments on methods that implement its rules, use
 * the format
 * <PartId> <SectionId>
 * [ ItemType <ItemId> ], where
 *
 *

 *
 *
PartId is the numbered part
 *
 *
SectionId is the numbered or named section in the part's
 *table of contents, e.g. "Section 4.11.2" or "Annex A"
 *
 *
ItemType is one of { Table, Syntax Rule, Access Rule,
 *General Rule, or Conformance Rule }
 *
 *
ItemId is a dotted path expression to the specific item
 *
 *

 *
 * For example,
 *
 *
SQL2003 Part 2 Section 11.4 Syntax Rule 10.b

 *
 * is a well-formed reference to the rule for the default character
 * set to use for column definitions of character type.
 */
struct SQL2003
{
    // NOTE:  dummy class for doxygen
};

FENNEL_END_CPPFILE("$Id$");

// End CommonTerms.cpp


text:
/sbin/ip route | awk '/default/ { print $3 }' > /etc/host_ip
LOCALHOST_IP=`cat /etc/host_ip`

# Config synapse to use the docker watcher on localhost
sed -ri "s/#LOCALHOST_IP#/${LOCALHOST_IP}/" /etc/synapse.json.conf

# Start the load balancer on port 8080
#service haproxy start

# Start synapse for service discovery
synapse -c /etc/synapse.json.conf


text:
package com.anarsoft.vmlens.concurrent.example;

public class AtomicPositiveValue {
   private int value;
   public AtomicPositiveValue(int value) {
	this.value = value;
   }
   public synchronized int get()
   {
	return value;
   }
   public synchronized void set(int newValue)
   {
	   value = newValue;
   }
   public synchronized int update(int delta) throws Exception
   {
	   int temp = value + delta;
	   if( temp < 0 )
	   {
		   throw new Exception("value is negative");
	   }
	   value = temp;
	   return value;
   }
   public synchronized void transfer(AtomicPositiveValue other, int amount) throws Exception
   {
	   other.update( -1 * amount );
	   update(amount);

   }
}


text:
/**
 * Various low-level, bit-manipulation routines.
 *
 * findFirstSet(x)
 *    find first (least significant) bit set in a value of an integral type,
 *    1-based (like ffs()).  0 = no bits are set (x == 0)
 *
 * findLastSet(x)
 *    find last (most significant) bit set in a value of an integral type,
 *    1-based.  0 = no bits are set (x == 0)
 *    for x != 0, findFirstSet(x) == 1 + floor(log2(x))
 *
 * nextPowTwo(x)
 *    Finds the next power of two >= x.
 *
 * Endian
 *    convert between native, big, and little endian representation
 *    Endian::big(x)      big <-> native
 *    Endian::little(x)   little <-> native
 *    Endian::swap(x)     big <-> little
 *
 * BitIterator
 *    Wrapper around an iterator over an integral type that iterates
 *    over its underlying bits in MSb to LSb order
 *
 * findFirstSet(BitIterator begin, BitIterator end)
 *    return a BitIterator pointing to the first 1 bit in [begin, end), or
 *    end if all bits in [begin, end) are 0
 *
 * @author Tudor Bosman (tudorb@fb.com)
 */

#ifndef FOLLY_BITS_H_
#define FOLLY_BITS_H_

#include "folly/Portability.h"

#ifndef _GNU_SOURCE
#define _GNU_SOURCE 1
#endif

#include "folly/detail/BitIteratorDetail.h"
#include "folly/Likely.h"

#include <byteswap.h>
#include <cassert>
#include <cinttypes>
#include <cstring>  // for ffs, ffsl, ffsll
#include <endian.h>
#include <iterator>
#include <limits>
#include <type_traits>
#include <boost/iterator/iterator_adaptor.hpp>
#include <stdint.h>

namespace folly {

// Generate overloads for findFirstSet as wrappers around
// appropriate ffs, ffsl, ffsll functions from glibc.
// We first define these overloads for signed types (because ffs, ffsl, ffsll
// take int, long, and long long as arguments, respectively) and then
// define an overload for unsigned that forwards to the overload for the
// corresponding signed type.
template <class T>
typename std::enable_if<
  (std::is_integral<T>::value &&
   std::is_signed<T>::value &&
   (std::numeric_limits<T>::digits <= std::numeric_limits<int>::digits)),
  unsigned int>::type
  findFirstSet(T x) {
  return ::ffs(static_cast<int>(x));
}

template <class T>
typename std::enable_if<
  (std::is_integral<T>::value &&
   std::is_signed<T>::value &&
   (std::numeric_limits<T>::digits > std::numeric_limits<int>::digits) &&
   (std::numeric_limits<T>::digits <= std::numeric_limits<long>::digits)),
  unsigned int>::type
  findFirstSet(T x) {
  return ::ffsl(static_cast<long>(x));
}

#ifdef FOLLY_HAVE_FFSLL

template <class T>
typename std::enable_if<
  (std::is_integral<T>::value &&
   std::is_signed<T>::value &&
   (std::numeric_limits<T>::digits > std::numeric_limits<long>::digits) &&
   (std::numeric_limits<T>::digits <= std::numeric_limits<long long>::digits)),
  unsigned int>::type
  findFirstSet(T x) {
  return ::ffsll(static_cast<long long>(x));
}

#endif

template <class T>
typename std::enable_if<
  (std::is_integral<T>::value &&
   !std::is_signed<T>::value),
  unsigned int>::type
  findFirstSet(T x) {
  // Note that conversion from an unsigned type to the corresponding signed
  // type is technically implementation-defined, but will likely work
  // on any impementation that uses two's complement.
  return findFirstSet(static_cast<typename std::make_signed<T>::type>(x));
}

namespace detail {

// Portable, but likely slow...
inline unsigned int findLastSetPortable(uint64_t x) {
  unsigned int r = (x != 0);  // 1-based index, except for x==0
  while (x >>= 1) {
    ++r;
  }
  return r;
}

}  // namespace detail

#ifdef __GNUC__

// findLastSet: return the 1-based index of the highest bit set
// for x > 0, findLastSet(x) == 1 + floor(log2(x))
template <class T>
typename std::enable_if<
  (std::is_integral<T>::value &&
   std::is_unsigned<T>::value &&
   (std::numeric_limits<T>::digits <=
    std::numeric_limits<unsigned int>::digits)),
  unsigned int>::type
  findLastSet(T x) {
  return x ? 8 * sizeof(unsigned int) - __builtin_clz(x) : 0;
}

template <class T>
typename std::enable_if<
  (std::is_integral<T>::value &&
   std::is_unsigned<T>::value &&
   (std::numeric_limits<T>::digits >
    std::numeric_limits<unsigned int>::digits) &&
   (std::numeric_limits<T>::digits <=
    std::numeric_limits<unsigned long>::digits)),
  unsigned int>::type
  findLastSet(T x) {
  return x ? 8 * sizeof(unsigned long) - __builtin_clzl(x) : 0;
}

template <class T>
typename std::enable_if<
  (std::is_integral<T>::value &&
   std::is_unsigned<T>::value &&
   (std::numeric_limits<T>::digits >
    std::numeric_limits<unsigned long>::digits) &&
   (std::numeric_limits<T>::digits <=
    std::numeric_limits<unsigned long long>::digits)),
  unsigned int>::type
  findLastSet(T x) {
  return x ? 8 * sizeof(unsigned long long) - __builtin_clzll(x) : 0;
}

#else  /* !__GNUC__ */

template <class T>
typename std::enable_if<
  (std::is_integral<T>::value &&
   std::is_unsigned<T>::value),
  unsigned int>::type
  findLastSet(T x) {
  return detail:findLastSetPortable(x);
}

#endif

template <class T>
typename std::enable_if<
  (std::is_integral<T>::value &&
   std::is_signed<T>::value),
  unsigned int>::type
  findLastSet(T x) {
  return findLastSet(static_cast<typename std::make_unsigned<T>::type>(x));
}

namespace detail {

template <class T>
inline
typename std::enable_if<
  std::is_integral<T>::value && std::is_unsigned<T>::value,
  T>::type
nextPowTwoPortable(T v) {
  if (UNLIKELY(v == 0)) {
    return 1;
  }

  --v;
  for (uint32_t i = 1; i < sizeof(T) * 8; i <<= 8) {
    v |= (v >> i);
    v |= (v >> (i << 1));
    v |= (v >> (i << 2));
    v |= (v >> (i << 3));
    v |= (v >> (i << 4));
    v |= (v >> (i << 5));
    v |= (v >> (i << 6));
    v |= (v >> (i << 7));
  }
  return v + 1;
}

}  // namespace detail

#ifdef __GNUC__

template <class T>
inline
typename std::enable_if<
  std::is_integral<T>::value && std::is_unsigned<T>::value,
  T>::type
nextPowTwo(T v) {
  if (UNLIKELY(v == 0)) {
    return 1;
  }
  return 1ul << findLastSet(v - 1);
}

#else /* __GNUC__ */

template <class T>
inline
typename std::enable_if<
  std::is_integral<T>::value && std::is_unsigned<T>::value,
  T>::type
nextPowTwo(T v) {
  return detail::nextPowTwoPortable(v);
}

#endif /* __GNUC__ */

/**
 * Endianness detection and manipulation primitives.
 */
namespace detail {

template <class T>
struct EndianIntBase {
 public:
  static T swap(T x);
};

#define FB_GEN(t, fn) \
template<> inline t EndianIntBase<t>::swap(t x) { return fn(x); }

// fn(x) expands to (x) if the second argument is empty, which is exactly
// what we want for [u]int8_t
FB_GEN( int8_t,)
FB_GEN(uint8_t,)
FB_GEN( int64_t, bswap_64)
FB_GEN(uint64_t, bswap_64)
FB_GEN( int32_t, bswap_32)
FB_GEN(uint32_t, bswap_32)
FB_GEN( int16_t, bswap_16)
FB_GEN(uint16_t, bswap_16)

#undef FB_GEN

#if __BYTE_ORDER == __LITTLE_ENDIAN

template <class T>
struct EndianInt : public detail::EndianIntBase<T> {
 public:
  static T big(T x) { return EndianInt::swap(x); }
  static T little(T x) { return x; }
};

#elif __BYTE_ORDER == __BIG_ENDIAN

template <class T>
struct EndianInt : public detail::EndianIntBase<T> {
 public:
  static T big(T x) { return x; }
  static T little(T x) { return EndianInt::swap(x); }
};

#else
# error Your machine uses a weird endianness!
#endif  /* __BYTE_ORDER */

}  // namespace detail

// big* convert between native and big-endian representations
// little* convert between native and little-endian representations
// swap* convert between big-endian and little-endian representations
//
// ntohs, htons == big16
// ntohl, htonl == big32
#define FB_GEN1(fn, t, sz) \
  static t fn##sz(t x) { return fn<t>(x); } \

#define FB_GEN2(t, sz) \
  FB_GEN1(swap, t, sz) \
  FB_GEN1(big, t, sz) \
  FB_GEN1(little, t, sz)

#define FB_GEN(sz) \
  FB_GEN2(uint##sz##_t, sz) \
  FB_GEN2(int##sz##_t, sz)

class Endian {
 public:
  template <class T> static T swap(T x) {
    return detail::EndianInt<T>::swap(x);
  }
  template <class T> static T big(T x) {
    return detail::EndianInt<T>::big(x);
  }
  template <class T> static T little(T x) {
    return detail::EndianInt<T>::little(x);
  }

  FB_GEN(64)
  FB_GEN(32)
  FB_GEN(16)
  FB_GEN(8)
};

#undef FB_GEN
#undef FB_GEN2
#undef FB_GEN1

/**
 * Fast bit iteration facility.
 */

template <class BaseIter> class BitIterator;
template <class BaseIter>
BitIterator<BaseIter> findFirstSet(BitIterator<BaseIter>,
                                   BitIterator<BaseIter>);
/**
 * Wrapper around an iterator over an integer type that iterates
 * over its underlying bits in LSb to MSb order.
 *
 * BitIterator models the same iterator concepts as the base iterator.
 */
template <class BaseIter>
class BitIterator
  : public bititerator_detail::BitIteratorBase<BaseIter>::type {
 public:
  /**
   * Return the number of bits in an element of the underlying iterator.
   */
  static size_t bitsPerBlock() {
    return std::numeric_limits<
      typename std::make_unsigned<
        typename std::iterator_traits<BaseIter>::value_type
      >::type
    >::digits;
  }

  /**
   * Construct a BitIterator that points at a given bit offset (default 0)
   * in iter.
   */
  explicit BitIterator(const BaseIter& iter, size_t bitOffset=0)
    : bititerator_detail::BitIteratorBase<BaseIter>::type(iter),
      bitOffset_(bitOffset) {
    assert(bitOffset_ < bitsPerBlock());
  }

  size_t bitOffset() const {
    return bitOffset_;
  }

  void advanceToNextBlock() {
    bitOffset_ = 0;
    ++this->base_reference();
  }

  BitIterator& operator=(const BaseIter& other) {
    this->~BitIterator();
    new (this) BitIterator(other);
    return *this;
  }

 private:
  friend class boost::iterator_core_access;
  friend BitIterator findFirstSet<>(BitIterator, BitIterator);

  typedef bititerator_detail::BitReference<
      typename std::iterator_traits<BaseIter>::reference,
      typename std::iterator_traits<BaseIter>::value_type
    > BitRef;

  void advanceInBlock(size_t n) {
    bitOffset_ += n;
    assert(bitOffset_ < bitsPerBlock());
  }

  BitRef dereference() const {
    return BitRef(*this->base_reference(), bitOffset_);
  }

  void advance(ssize_t n) {
    size_t bpb = bitsPerBlock();
    ssize_t blocks = n / bpb;
    bitOffset_ += n % bpb;
    if (bitOffset_ >= bpb) {
      bitOffset_ -= bpb;
      ++blocks;
    }
    this->base_reference() += blocks;
  }

  void increment() {
    if (++bitOffset_ == bitsPerBlock()) {
      advanceToNextBlock();
    }
  }

  void decrement() {
    if (bitOffset_-- == 0) {
      bitOffset_ = bitsPerBlock() - 1;
      --this->base_reference();
    }
  }

  bool equal(const BitIterator& other) const {
    return (bitOffset_ == other.bitOffset_ &&
            this->base_reference() == other.base_reference());
  }

  ssize_t distance_to(const BitIterator& other) const {
    return
      (other.base_reference() - this->base_reference()) * bitsPerBlock() +
      (other.bitOffset_ - bitOffset_);
  }

  ssize_t bitOffset_;
};

/**
 * Helper function, so you can write
 * auto bi = makeBitIterator(container.begin());
 */
template <class BaseIter>
BitIterator<BaseIter> makeBitIterator(const BaseIter& iter) {
  return BitIterator<BaseIter>(iter);
}

/**
 * Find first bit set in a range of bit iterators.
 * 4.5x faster than the obvious std::find(begin, end, true);
 */
template <class BaseIter>
BitIterator<BaseIter> findFirstSet(BitIterator<BaseIter> begin,
                                   BitIterator<BaseIter> end) {
  // shortcut to avoid ugly static_cast<>
  static const typename BaseIter::value_type one = 1;

  while (begin.base() != end.base()) {
    typename BaseIter::value_type v = *begin.base();
    // mask out the bits that don't matter (< begin.bitOffset)
    v &= ~((one << begin.bitOffset()) - 1);
    size_t firstSet = findFirstSet(v);
    if (firstSet) {
      --firstSet;  // now it's 0-based
      assert(firstSet >= begin.bitOffset());
      begin.advanceInBlock(firstSet - begin.bitOffset());
      return begin;
    }
    begin.advanceToNextBlock();
  }

  // now begin points to the same block as end
  if (end.bitOffset() != 0) {  // assume end is dereferenceable
    typename BaseIter::value_type v = *begin.base();
    // mask out the bits that don't matter (< begin.bitOffset)
    v &= ~((one << begin.bitOffset()) - 1);
    // mask out the bits that don't matter (>= end.bitOffset)
    v &= (one << end.bitOffset()) - 1;
    size_t firstSet = findFirstSet(v);
    if (firstSet) {
      --firstSet;  // now it's 0-based
      assert(firstSet >= begin.bitOffset());
      begin.advanceInBlock(firstSet - begin.bitOffset());
      return begin;
    }
  }

  return end;
}

}  // namespace folly

#endif /* FOLLY_BITS_H_ */


text:
#include <iostream>
#include <sstream>
#include <core/client/proto_tcp_text_client.hpp>
#include "director_pipeline.hpp"
#include "cmd_parser.hpp"
#include <boost/program_options.hpp>

namespace po = boost::program_options;

using namespace proto_net::data;
using namespace proto_net;
using namespace proto_net::client;

static const std::string ver = "1.1.0";
static const std::string bld_date_time = "3/16/16; 4:20 PM";

void
print(const std::string& out)
{
    std::cout << out;
}

void
print_ln(const std::string& out)
{
    print(out);
    std::cout << std::endl;
}

void
print_error(const std::string& err)
{
    std::string out = "ERROR: " + err;
    std::cerr << out << std::endl;
}

void
print_banner(void)
{
    print_ln("c4-client - A command line tool to send C4SOAP commands to a Control4 controller.");
    print_ln("Version: " + ver);
    print_ln("Built: " + bld_date_time);
    print_ln("Copyright 2016 Terry Seyler.  All rights reserved.");
    print_ln("------------");
}

void
print_usage(void)
{
    std::cout << "Usage:" << std::endl;
    std::cout << "$ c4-client <host> <command> [id] [param1] [param2] ..." << std::endl;
}

bool
print_shell(cmd_parser& parser, bool in_shell)
{
    if (in_shell)
    {
        std::cout << "Command >> ";
        char shell[1024];
        std::cin.getline(shell, 1024);
        in_shell = parser.parse(std::string(shell));
    }

    return in_shell;
}

void
print_verbose(const std::string& msg)
{
    print_ln("<<--Out-->>");
    print_ln(msg);
    print_ln("<<--End Out-->>");
}

char**
get_args(char* argv[], int first_arg)
{
    return &argv[first_arg];
}

int
main(int argc, char* argv[])
{
    bool silent(false);
    bool is_shell(false);
    bool is_verbose(false);
    int first_arg(1);

    po::options_description desc("Options");
    desc.add_options()
            ("help,h", "Prints the help message")
            ("silent,s", "Suppresses the copyright banner")
            ("interactive,i", "Executes as an interactive shell")
            ("verbose,v", "Prints outgoing messages as well as incoming responses");

    po::variables_map vm;
    try
    {
        po::store(po::parse_command_line(argc--, argv, desc), vm);

        if (vm.count("silent"))
        {
            silent = true;
            argc--;
            first_arg++;
        }

        if (!silent)
            print_banner();

        if (vm.count("interactive"))
        {
            is_shell = true;
            argc--;
            first_arg++;
        }

        if (vm.count("verbose"))
        {
            is_verbose = true;
            argc--;
            first_arg++;
        }

        if (vm.count("help"))
        {
            print_usage();
            return 0;
        }

    }
    catch (po::error& e)
    {
        print_error(e.what());
        std::cerr << desc << std::endl;
        return 1;
    }

    if (argc > 0)
    {
        char **args = get_args(argv, first_arg);
        cmd_parser parser(args, argc);
        std::string host = parser.host();
        std::string cmd = parser.cmd();
        // authenticate

        unsigned long seq(1);
        std::string msg = parser.to_authenticate(seq);

        // create a pipeline for the client
        director_pipeline dir_pipeline(host);
        // create the client
        proto_tcp_text_client dir_client(host, 5020, dir_pipeline);

        // authenticate c4soap message for director to allow a connection
        proto_net_in_data auth_data(msg);
        // connect to the downstream server (director)
        dir_client.ps_async_connect(auth_data);
        // start the client service
        dir_client.ps_start();

        do
        {
            msg = parser.to_c4soap(seq);
            if (parser.parsed())
            {
                if (is_verbose)
                    print_verbose(msg);
                proto_net_in_data cmd_data(msg);
                dir_client.ps_async_write(cmd_data);
                dir_client.ps_write_complete();
            }
            else
                print_ln("Unknown or malformed command: " + cmd);
            is_shell = print_shell(parser, is_shell);
        }
        while (is_shell);

        dir_client.ps_stop();
    }
    else
        print_usage();

    std::cout << "Done." << std::endl;

    return 0;
}


text:
L.GPX.include(L.Mixin.Selectable);

L.GpxGroup = L.Class.extend({
	options: {
		highlight: {
			color: '#fff',
			opacity: 1,
		},
	},

	initialize: function (routes, options) {
		this._routes = routes;
		this._layers = L.featureGroup();
		this._elevation = L.control.elevation({ width: 500 });
		this._distance = 0;
		L.Util.setOptions(this, options);
	},

	getBounds: function() {
		return this._layers.getBounds();
	},

	addTo: function (map) {
		this._layers.addTo(map);

		var this_ = this;
		var elevation_ = this._elevation;

		var routeCount = this._routes.length;
		var colors = this.options.colors || ColorUtils.uniqueColors(routeCount);
		var count = 0;
		var loadedCount = 0;

		this.on('selectionChanged', function() {
			var route = this_.getSelection();
			if (route && route.isSelected()) {
				if (!elevation_.getContainer()) {
					elevation_.addTo(map);
				}
				elevation_.clear();
				route.getLayers().forEach(function(layer) {
					if (layer instanceof L.Polyline) {
						elevation_.addData(layer);
					}
				});
			} else {
				if (elevation_.getContainer()) {
					elevation_.removeFrom(map);
				}
				elevation_.clear();
			}
		});

		this._routes.forEach(function(track) {
			var color = colors[count++ % colors.length];
			$.get(track, function(data) {
				var route = new L.GPX(data, {
					async: true,
					marker_options: { startIconUrl: null, endIconUrl: null },
					polyline_options: {
						color: color,
						opacity: 0.85,
						distanceMarkers: { offset: 5000, lazy: true },
					}
				});
				route.on('addline', function(evt) {
					var polyline = evt.line;
					var originalStyle = polyline.options;

					var highlight = function() {
						polyline.setStyle(this_.options.highlight)
						polyline.addDistanceMarkers();
					};
					var unhighlight = function() {
						polyline.setStyle(originalStyle)
						polyline.removeDistanceMarkers();
					};
					polyline.on('mouseover', function() {
						if (!route.isSelected()) {
							highlight();
						}
					});
					polyline.on('mouseout', function() {
						if (!route.isSelected()) {
							unhighlight();
						}
					});
					polyline.on('click', function() {
						this_.setSelection(route);
					});
					route.on('selected', function() {
						if (!route.isSelected()) {
							unhighlight();
						}
					});

					polyline.bindLabel(route.get_name(), { direction: 'auto' });
				});
				route.on('loaded', function() {
					this_._distance += route.get_distance();
					if (++loadedCount === routeCount) {
						this_.fire('loaded');
					}
				});
				route.addTo(this_._layers);
			});
		});
	},

	removeFrom: function (map) {
		this._layers.removeFrom(map);
	},

	get_distance: function() {
		return this._distance;
	},

});
L.GpxGroup.include(L.Mixin.Events);
L.GpxGroup.include(L.Mixin.Selection);

L.gpxGroup = function(routes, options) {
	return new L.GpxGroup(routes, options);
};


text:
'use strict';

const cfgFactory = require('../utils/cfg-factory');
const cfgPath = require('../utils/cfg-constants');
const pkg = require('../../package');

module.exports = (app) => {

  let localsConfig = cfgFactory.getConfig('locals');
  localsConfig = Object.assign({}, localsConfig, {
    NODE_ENV: cfgPath.NODE_ENV,
    VERSION: localsConfig.VERSION.slice(0, 2) + Date.now()
  });

  app.name = pkg.name;
  app.env = cfgPath.NODE_ENV;

  app.use((ctx, next) => {
    // 设置模板的全局属性
    ctx.state.locals = Object.assign({}, ctx.state, localsConfig);
    // 页面不缓存
    ctx.set('Cache-Control', 'no-cache');
    return next();
  });

};