text:
'use strict';

var chalk = require('chalk');
var relative = require('relative');

/**
 * Show a diff comparison of pre- and post-render content.
 */

module.exports = function(app) {
  return function (file, next) {
    var diff = app.get('argv.diff');

    if (!diff) return next();
    console.log();
    console.log('- end -');
    console.log('---------------------------------------------------------------');
    console.log(relative(file.path));
    console.log();

    if (file.content === '') {
      console.log(chalk.gray('  no content.'));
    } else if (file.content === file.orig) {
      console.log(chalk.gray('  content is unchanged.'));
    } else {
      app.diff(file.orig, file.content, 'diffLines');
    }
    next();
  };
};


text:
<?php
namespace Wa72\HtmlPageDom;

use Symfony\Component\CssSelector\CssSelector;

/**
 * This class represents a complete HTML document.
 *
 * It offers convenience functions for getting and setting elements of the document
 * such as setTitle(), getTitle(), setMeta($name, $value), getBody().
 *
 * It uses HtmlPageCrawler to navigate and manipulate the DOM tree.
 *
 * @author Christoph Singer
 * @license MIT
 */
class HtmlPage
{
    /**
     *
     * @var \DOMDocument
     */
    protected $dom;

    /**
     * @var string
     */
    protected $charset;

    /**
     * @var string
     */
    protected $url;

    /**
     *
     * @var HtmlPageCrawler
     */
    protected $crawler;

    public function __construct($content = '', $url = '', $charset = 'UTF-8')
    {
        $this->charset = $charset;
        $this->url = $url;
        if ($content == '') {
            $content = '<!DOCTYPE html><title></title>';
        }
        $current = libxml_use_internal_errors(true);
        $disableEntities = libxml_disable_entity_loader(true);

        $this->dom = new \DOMDocument('1.0', $charset);
        $this->dom->validateOnParse = true;

        if (function_exists('mb_convert_encoding') && in_array(strtolower($charset), array_map('strtolower', mb_list_encodings()))) {
            $content = mb_convert_encoding($content, 'HTML-ENTITIES', $charset);
        }

        @$this->dom->loadHTML($content);
        $this->dom->formatOutput = true;

        libxml_use_internal_errors($current);
        libxml_disable_entity_loader($disableEntities);
        $this->crawler = new HtmlPageCrawler($this->dom);
    }

    /**
     * Get a HtmlPageCrawler object containing the root node of the HTML document
     *
     * @return HtmlPageCrawler
     */
    public function getCrawler()
    {
        return $this->crawler;
    }

    /**
     * Get a DOMDocument object for the HTML document
     *
     * @return \DOMDocument
     */
    public function getDOMDocument()
    {
        return $this->dom;
    }

    /**
     * Sets the page title of the HTML document
     *
     * @param string $title
     */
    public function setTitle($title)
    {
        $t = $this->dom->getElementsByTagName('title')->item(0);
        if ($t == null) {
            $t = $this->dom->createElement('title');
            $this->getHeadNode()->appendChild($t);
        }
        $t->nodeValue = htmlspecialchars($title);
    }

    /**
     * Get the page title of the HTML document
     *
     * @return null|string
     */
    public function getTitle()
    {
        $t = $this->dom->getElementsByTagName('title')->item(0);
        if ($t == null) {
            return null;
        } else {
            return $t->nodeValue;
        }
    }

    /**
     * Set a META tag with specified 'name' and 'content' attributes
     *
     * @TODO: add support for multiple meta tags with the same name but different languages
     *
     * @param $name
     * @param $content
     */
    public function setMeta($name, $content)
    {
        $c = $this->filterXPath('descendant-or-self::meta[@name = \'' . $name . '\']');
        if (count($c) == 0) {
            $node = $this->dom->createElement('meta');
            $node->setAttribute('name', $name);
            $this->getHeadNode()->appendChild($node);
            $c->addNode($node);
        }
        $c->setAttribute('content', $content);
    }

    /**
     * Remove all meta tags with the specified name attribute
     *
     * @param string $name
     */
    public function removeMeta($name)
    {
        $meta = $this->filterXPath('descendant-or-self::meta[@name = \'' . $name . '\']');
        $meta->remove();
    }

    /**
     * Get the content attribute of a meta tag with the specified name attribute
     *
     * @param string $name
     * @return null|string
     */
    public function getMeta($name)
    {
        $node = $this->filterXPath('descendant-or-self::meta[@name = \'' . $name . '\']')->getFirstNode();
        if ($node instanceof \DOMElement) {
            return $node->getAttribute('content');
        } else {
            return null;
        }
    }

    /**
     * Set the base tag with href attribute set to parameter $url
     *
     * @param string $url
     */
    public function setBaseHref($url)
    {
        $node = $this->filterXPath('descendant-or-self::base')->getFirstNode();
        if ($node == null) {
            $node = $this->dom->createElement('base');
            $this->getHeadNode()->appendChild($node);
        }
        $node->setAttribute('href', $url);
    }

    /**
     * Get the href attribute from the base tag, null if not present in document
     *
     * @return null|string
     */
    public function getBaseHref()
    {
        $node = $this->filterXPath('descendant-or-self::base')->getFirstNode();
        if ($node instanceof \DOMElement) {
            return $node->getAttribute('href');
        } else {
            return null;
        }
    }

    /**
     * Sets innerHTML content of an element specified by elementId
     *
     * @param string $elementId
     * @param string $html
     */
    public function setHtmlById($elementId, $html)
    {
        $this->getElementById($elementId)->setInnerHtml($html);
    }

    /**
     * Get the document's HEAD section as DOMElement
     *
     * @return \DOMElement
     */
    public function getHeadNode()
    {
        $head = $this->dom->getElementsByTagName('head')->item(0);
        if ($head == null) {
            $head = $this->dom->createElement('head');
            $head = $this->dom->documentElement->insertBefore($head, $this->getBodyNode());
        }
        return $head;
    }

    /**
     * Get the document's body as DOMElement
     *
     * @return \DOMElement
     */
    public function getBodyNode()
    {
        $body = $this->dom->getElementsByTagName('body')->item(0);
        if ($body == null) {
            $body = $this->dom->createElement('body');
            $body = $this->dom->documentElement->appendChild($body);
        }
        return $body;
    }

    /**
     * Get the document's HEAD section wrapped in a HtmlPageCrawler instance
     *
     * @return HtmlPageCrawler
     */
    public function getHead()
    {
        return new HtmlPageCrawler($this->getHeadNode());
    }

    /**
     * Get the document's body wrapped in a HtmlPageCrawler instance
     *
     * @return HtmlPageCrawler
     */
    public function getBody()
    {
        return new HtmlPageCrawler($this->getBodyNode());
    }

    public function __toString()
    {
        return $this->dom->saveHTML();
    }

    /**
     * Save this document to a HTML file or return HTML code as string
     *
     * @param string $filename If provided, output will be saved to this file, otherwise returned
     * @return string|void
     */
    public function save($filename = null)
    {
        if ($filename != null) {
            file_put_contents($filename, $this->__toString());
            return;
        } else {
            return $this->__toString();
        }
    }

    /**
     * Get an element in the document by it's id attribute
     *
     * @param string $id
     * @return HtmlPageCrawler
     */
    public function getElementById($id)
    {
        return $this->filterXPath('descendant-or-self::*[@id = \'' . $id . '\']');
    }

    /**
     * Filter nodes by using a CSS selector
     *
     * @param string $selector CSS selector
     * @return HtmlPageCrawler
     */
    public function filter($selector)
    {
        //echo "\n" . CssSelector::toXPath($selector) . "\n";
        return $this->crawler->filter($selector);
    }

    /**
     * Filter nodes by XPath expression
     *
     * @param string $xpath XPath expression
     * @return HtmlPageCrawler
     */
    public function filterXPath($xpath)
    {
        return $this->crawler->filterXPath($xpath);
    }

    /**
     * remove newlines from string and minimize whitespace (multiple whitespace characters replaced by one space)
     *
     * useful for cleaning up text retrieved by HtmlPageCrawler::text() (nodeValue of a DOMNode)
     *
     * @param string $string
     * @return string
     */
    public static function trimNewlines($string)
    {
        return HtmlPageCrawler::trimNewlines($string);
    }

    public function __clone()
    {
        $this->dom = $this->dom->cloneNode(true);
        $this->dom->formatOutput = true;
        $this->crawler = new HtmlPageCrawler($this->dom);
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php
if (!class_exists("wpdreamsSelect")) {

    class wpdreamsSelect extends wpdreamsType {
        function getType() {
            parent::getType();
            $this->processData();
            echo "
";
            echo "" . $this->label . "";
            echo "<select class='wpdreamsselect' id='wpdreamsselect_" . self::$_instancenumber . "' name='" . $this->name . "_select'>";
            foreach ($this->selects as $sel) {
                preg_match('/(?<option>.*?)\\|(?<value>.*)/', $sel, $matches);
                $matches['value'] = trim($matches['value']);
                $matches['option'] = trim($matches['option']);
                if ($matches['value'] == $this->selected)
                    echo "<option value='" . $matches['value'] . "' selected='selected'>" . $matches['option'] . "</option>";
                else
                    echo "<option value='" . $matches['value'] . "'>" . $matches['option'] . "</option>";
            }
            echo "</select>";
            echo "<input isparam=1 type='hidden' value='" . $this->data . "' name='" . $this->name . "'>";
            echo "<input type='hidden' value='" . $this->selected . "' name='selected-" . $this->name . "'>";
            echo "

";
        }

        function processData() {
            //$this->data = str_replace("\n","",$this->data);
            $_temp = explode("||", $this->data);
            $this->selects = explode(";", $_temp[0]);
            $this->selected = trim($_temp[1]);
        }

        final function getData() {
            return $this->data;
        }

        final function getSelected() {
            return $this->selected;
        }
    }
}


text:
<?php

namespace BingAds\v10\CampaignManagement;

/**
 * Updates one or more website-placement bids in an ad group.
 *
 * @link http://msdn.microsoft.com/en-us/library/dn236298(v=msads.100).aspx UpdateSitePlacements Response Object
 *
 * @used-by BingAdsCampaignManagementService::UpdateSitePlacements
 */
final class UpdateSitePlacementsResponse
{
}


text:
from __future__ import print_function
from collections import MutableMapping
import ctypes as ct
from functools import reduce
import multiprocessing
import os
import errno
import re
import sys

from .libbcc import lib, _RAW_CB_TYPE, _LOST_CB_TYPE, _RINGBUF_CB_TYPE
from .perf import Perf
from .utils import get_online_cpus
from .utils import get_possible_cpus
from subprocess import check_output

BPF_MAP_TYPE_HASH = 1
BPF_MAP_TYPE_ARRAY = 2
BPF_MAP_TYPE_PROG_ARRAY = 3
BPF_MAP_TYPE_PERF_EVENT_ARRAY = 4
BPF_MAP_TYPE_PERCPU_HASH = 5
BPF_MAP_TYPE_PERCPU_ARRAY = 6
BPF_MAP_TYPE_STACK_TRACE = 7
BPF_MAP_TYPE_CGROUP_ARRAY = 8
BPF_MAP_TYPE_LRU_HASH = 9
BPF_MAP_TYPE_LRU_PERCPU_HASH = 10
BPF_MAP_TYPE_LPM_TRIE = 11
BPF_MAP_TYPE_ARRAY_OF_MAPS = 12
BPF_MAP_TYPE_HASH_OF_MAPS = 13
BPF_MAP_TYPE_DEVMAP = 14
BPF_MAP_TYPE_SOCKMAP = 15
BPF_MAP_TYPE_CPUMAP = 16
BPF_MAP_TYPE_XSKMAP = 17
BPF_MAP_TYPE_SOCKHASH = 18
BPF_MAP_TYPE_CGROUP_STORAGE = 19
BPF_MAP_TYPE_REUSEPORT_SOCKARRAY = 20
BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE = 21
BPF_MAP_TYPE_QUEUE = 22
BPF_MAP_TYPE_STACK = 23
BPF_MAP_TYPE_SK_STORAGE = 24
BPF_MAP_TYPE_DEVMAP_HASH = 25
BPF_MAP_TYPE_STRUCT_OPS = 26
BPF_MAP_TYPE_RINGBUF = 27

map_type_name = {BPF_MAP_TYPE_HASH: "HASH",
                 BPF_MAP_TYPE_ARRAY: "ARRAY",
                 BPF_MAP_TYPE_PROG_ARRAY: "PROG_ARRAY",
                 BPF_MAP_TYPE_PERF_EVENT_ARRAY: "PERF_EVENT_ARRAY",
                 BPF_MAP_TYPE_PERCPU_HASH: "PERCPU_HASH",
                 BPF_MAP_TYPE_PERCPU_ARRAY: "PERCPU_ARRAY",
                 BPF_MAP_TYPE_STACK_TRACE: "STACK_TRACE",
                 BPF_MAP_TYPE_CGROUP_ARRAY: "CGROUP_ARRAY",
                 BPF_MAP_TYPE_LRU_HASH: "LRU_HASH",
                 BPF_MAP_TYPE_LRU_PERCPU_HASH: "LRU_PERCPU_HASH",
                 BPF_MAP_TYPE_LPM_TRIE: "LPM_TRIE",
                 BPF_MAP_TYPE_ARRAY_OF_MAPS: "ARRAY_OF_MAPS",
                 BPF_MAP_TYPE_HASH_OF_MAPS: "HASH_OF_MAPS",
                 BPF_MAP_TYPE_DEVMAP: "DEVMAP",
                 BPF_MAP_TYPE_SOCKMAP: "SOCKMAP",
                 BPF_MAP_TYPE_CPUMAP: "CPUMAP",
                 BPF_MAP_TYPE_XSKMAP: "XSKMAP",
                 BPF_MAP_TYPE_SOCKHASH: "SOCKHASH",
                 BPF_MAP_TYPE_CGROUP_STORAGE: "CGROUP_STORAGE",
                 BPF_MAP_TYPE_REUSEPORT_SOCKARRAY: "REUSEPORT_SOCKARRAY",
                 BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: "PERCPU_CGROUP_STORAGE",
                 BPF_MAP_TYPE_QUEUE: "QUEUE",
                 BPF_MAP_TYPE_STACK: "STACK",
                 BPF_MAP_TYPE_SK_STORAGE: "SK_STORAGE",
                 BPF_MAP_TYPE_DEVMAP_HASH: "DEVMAP_HASH",
                 BPF_MAP_TYPE_STRUCT_OPS: "STRUCT_OPS",
                 BPF_MAP_TYPE_RINGBUF: "RINGBUF",}

stars_max = 40
log2_index_max = 65
linear_index_max = 1025

# helper functions, consider moving these to a utils module
def _stars(val, val_max, width):
    i = 0
    text = ""
    while (1):
        if (i > (width * val / val_max) - 1) or (i > width - 1):
            break
        text += "*"
        i += 1
    if val > val_max:
        text = text[:-1] + "+"
    return text

def _print_log2_hist(vals, val_type, strip_leading_zero):
    global stars_max
    log2_dist_max = 64
    idx_max = -1
    val_max = 0

    for i, v in enumerate(vals):
        if v > 0: idx_max = i
        if v > val_max: val_max = v

    if idx_max <= 32:
        header = "     %-19s : count     distribution"
        body = "%10d -> %-10d : %-8d |%-*s|"
        stars = stars_max
    else:
        header = "               %-29s : count     distribution"
        body = "%20d -> %-20d : %-8d |%-*s|"
        stars = int(stars_max / 2)

    if idx_max > 0:
        print(header % val_type)

    for i in range(1, idx_max + 1):
        low = (1 << i) >> 1
        high = (1 << i) - 1
        if (low == high):
            low -= 1
        val = vals[i]

        if strip_leading_zero:
            if val:
                print(body % (low, high, val, stars,
                              _stars(val, val_max, stars)))
                strip_leading_zero = False
        else:
            print(body % (low, high, val, stars,
                          _stars(val, val_max, stars)))

def _print_linear_hist(vals, val_type):
    global stars_max
    log2_dist_max = 64
    idx_max = -1
    val_max = 0

    for i, v in enumerate(vals):
        if v > 0: idx_max = i
        if v > val_max: val_max = v

    header = "     %-13s : count     distribution"
    body = "        %-10d : %-8d |%-*s|"
    stars = stars_max

    if idx_max >= 0:
        print(header % val_type);
    for i in range(0, idx_max + 1):
        val = vals[i]
        print(body % (i, val, stars,
                      _stars(val, val_max, stars)))

def get_table_type_name(ttype):
    try:
        return map_type_name[ttype]
    except KeyError:
        return "<unknown>"

def _get_event_class(event_map):
    ct_mapping = { 'char'              : ct.c_char,
                   's8'                : ct.c_char,
                   'unsigned char'     : ct.c_ubyte,
                   'u8'                : ct.c_ubyte,
                   'u8 *'              : ct.c_char_p,
                   'char *'            : ct.c_char_p,
                   'short'             : ct.c_short,
                   's16'               : ct.c_short,
                   'unsigned short'    : ct.c_ushort,
                   'u16'               : ct.c_ushort,
                   'int'               : ct.c_int,
                   's32'               : ct.c_int,
                   'enum'              : ct.c_int,
                   'unsigned int'      : ct.c_uint,
                   'u32'               : ct.c_uint,
                   'long'              : ct.c_long,
                   'unsigned long'     : ct.c_ulong,
                   'long long'         : ct.c_longlong,
                   's64'               : ct.c_longlong,
                   'unsigned long long': ct.c_ulonglong,
                   'u64'               : ct.c_ulonglong,
                   '__int128'          : (ct.c_longlong * 2),
                   'unsigned __int128' : (ct.c_ulonglong * 2),
                   'void *'            : ct.c_void_p }

    # handle array types e.g. "int [16] foo"
    array_type = re.compile(r"(.+) \[([0-9]+)\]$")

    fields = []
    num_fields = lib.bpf_perf_event_fields(event_map.bpf.module, event_map._name)
    i = 0
    while i < num_fields:
        field = lib.bpf_perf_event_field(event_map.bpf.module, event_map._name, i).decode()
        m = re.match(r"(.*)#(.*)", field)
        field_name = m.group(1)
        field_type = m.group(2)

        if re.match(r"enum .*", field_type):
            field_type = "enum"

        m = array_type.match(field_type)
        try:
            if m:
                fields.append((field_name, ct_mapping[m.group(1)] * int(m.group(2))))
            else:
                fields.append((field_name, ct_mapping[field_type]))
        except KeyError:
            # Using print+sys.exit instead of raising exceptions,
            # because exceptions are caught by the caller.
            print("Type: '%s' not recognized. Please define the data with ctypes manually."
                  % field_type, file=sys.stderr)
            sys.exit(1)
        i += 1
    return type('', (ct.Structure,), {'_fields_': fields})

def Table(bpf, map_id, map_fd, keytype, leaftype, name, **kwargs):
    """Table(bpf, map_id, map_fd, keytype, leaftype, **kwargs)

    Create a python object out of a reference to a bpf table handle"""

    ttype = lib.bpf_table_type_id(bpf.module, map_id)
    t = None
    if ttype == BPF_MAP_TYPE_HASH:
        t = HashTable(bpf, map_id, map_fd, keytype, leaftype)
    elif ttype == BPF_MAP_TYPE_ARRAY:
        t = Array(bpf, map_id, map_fd, keytype, leaftype)
    elif ttype == BPF_MAP_TYPE_PROG_ARRAY:
        t = ProgArray(bpf, map_id, map_fd, keytype, leaftype)
    elif ttype == BPF_MAP_TYPE_PERF_EVENT_ARRAY:
        t = PerfEventArray(bpf, map_id, map_fd, keytype, leaftype, name)
    elif ttype == BPF_MAP_TYPE_PERCPU_HASH:
        t = PerCpuHash(bpf, map_id, map_fd, keytype, leaftype, **kwargs)
    elif ttype == BPF_MAP_TYPE_PERCPU_ARRAY:
        t = PerCpuArray(bpf, map_id, map_fd, keytype, leaftype, **kwargs)
    elif ttype == BPF_MAP_TYPE_LPM_TRIE:
        t = LpmTrie(bpf, map_id, map_fd, keytype, leaftype)
    elif ttype == BPF_MAP_TYPE_STACK_TRACE:
        t = StackTrace(bpf, map_id, map_fd, keytype, leaftype)
    elif ttype == BPF_MAP_TYPE_LRU_HASH:
        t = LruHash(bpf, map_id, map_fd, keytype, leaftype)
    elif ttype == BPF_MAP_TYPE_LRU_PERCPU_HASH:
        t = LruPerCpuHash(bpf, map_id, map_fd, keytype, leaftype)
    elif ttype == BPF_MAP_TYPE_CGROUP_ARRAY:
        t = CgroupArray(bpf, map_id, map_fd, keytype, leaftype)
    elif ttype == BPF_MAP_TYPE_DEVMAP:
        t = DevMap(bpf, map_id, map_fd, keytype, leaftype)
    elif ttype == BPF_MAP_TYPE_CPUMAP:
        t = CpuMap(bpf, map_id, map_fd, keytype, leaftype)
    elif ttype == BPF_MAP_TYPE_XSKMAP:
        t = XskMap(bpf, map_id, map_fd, keytype, leaftype)
    elif ttype == BPF_MAP_TYPE_ARRAY_OF_MAPS:
        t = MapInMapArray(bpf, map_id, map_fd, keytype, leaftype)
    elif ttype == BPF_MAP_TYPE_HASH_OF_MAPS:
        t = MapInMapHash(bpf, map_id, map_fd, keytype, leaftype)
    elif ttype == BPF_MAP_TYPE_QUEUE or ttype == BPF_MAP_TYPE_STACK:
        t = QueueStack(bpf, map_id, map_fd, leaftype)
    elif ttype == BPF_MAP_TYPE_RINGBUF:
        t = RingBuf(bpf, map_id, map_fd, keytype, leaftype, name)
    if t == None:
        raise Exception("Unknown table type %d" % ttype)
    return t

class TableBase(MutableMapping):

    def __init__(self, bpf, map_id, map_fd, keytype, leaftype, name=None):
        self.bpf = bpf
        self.map_id = map_id
        self.map_fd = map_fd
        self.Key = keytype
        self.Leaf = leaftype
        self.ttype = lib.bpf_table_type_id(self.bpf.module, self.map_id)
        self.flags = lib.bpf_table_flags_id(self.bpf.module, self.map_id)
        self._cbs = {}
        self._name = name

    def get_fd(self):
        return self.map_fd

    def key_sprintf(self, key):
        buf = ct.create_string_buffer(ct.sizeof(self.Key) * 8)
        res = lib.bpf_table_key_snprintf(self.bpf.module, self.map_id, buf,
                                         len(buf), ct.byref(key))
        if res < 0:
            raise Exception("Could not printf key")
        return buf.value

    def leaf_sprintf(self, leaf):
        buf = ct.create_string_buffer(ct.sizeof(self.Leaf) * 8)
        res = lib.bpf_table_leaf_snprintf(self.bpf.module, self.map_id, buf,
                                          len(buf), ct.byref(leaf))
        if res < 0:
            raise Exception("Could not printf leaf")
        return buf.value

    def key_scanf(self, key_str):
        key = self.Key()
        res = lib.bpf_table_key_sscanf(self.bpf.module, self.map_id, key_str,
                                       ct.byref(key))
        if res < 0:
            raise Exception("Could not scanf key")
        return key

    def leaf_scanf(self, leaf_str):
        leaf = self.Leaf()
        res = lib.bpf_table_leaf_sscanf(self.bpf.module, self.map_id, leaf_str,
                                        ct.byref(leaf))
        if res < 0:
            raise Exception("Could not scanf leaf")
        return leaf

    def __getitem__(self, key):
        leaf = self.Leaf()
        res = lib.bpf_lookup_elem(self.map_fd, ct.byref(key), ct.byref(leaf))
        if res < 0:
            raise KeyError
        return leaf

    def __setitem__(self, key, leaf):
        res = lib.bpf_update_elem(self.map_fd, ct.byref(key), ct.byref(leaf), 0)
        if res < 0:
            errstr = os.strerror(ct.get_errno())
            raise Exception("Could not update table: %s" % errstr)

    def __delitem__(self, key):
        res = lib.bpf_delete_elem(self.map_fd, ct.byref(key))
        if res < 0:
            raise KeyError

    # override the MutableMapping's implementation of these since they
    # don't handle KeyError nicely
    def itervalues(self):
        for key in self:
            # a map entry may be deleted in between discovering the key and
            # fetching the value, suppress such errors
            try:
                yield self[key]
            except KeyError:
                pass

    def iteritems(self):
        for key in self:
            try:
                yield (key, self[key])
            except KeyError:
                pass

    def items(self):
        return [item for item in self.iteritems()]

    def values(self):
        return [value for value in self.itervalues()]

    def clear(self):
        # default clear uses popitem, which can race with the bpf prog
        for k in self.keys():
            self.__delitem__(k)

    def zero(self):
        # Even though this is not very efficient, we grab the entire list of
        # keys before enumerating it. This helps avoid a potential race where
        # the leaf assignment changes a hash table bucket that is being
        # enumerated by the same loop, and may lead to a hang.
        for k in list(self.keys()):
            self[k] = self.Leaf()

    def __iter__(self):
        return TableBase.Iter(self)

    def iter(self): return self.__iter__()
    def keys(self): return self.__iter__()

    class Iter(object):
        def __init__(self, table):
            self.table = table
            self.key = None
        def __iter__(self):
            return self
        def __next__(self):
            return self.next()
        def next(self):
            self.key = self.table.next(self.key)
            return self.key

    def next(self, key):
        next_key = self.Key()

        if key is None:
            res = lib.bpf_get_first_key(self.map_fd, ct.byref(next_key),
                                        ct.sizeof(self.Key))
        else:
            res = lib.bpf_get_next_key(self.map_fd, ct.byref(key),
                                       ct.byref(next_key))

        if res < 0:
            raise StopIteration()
        return next_key

    def print_log2_hist(self, val_type="value", section_header="Bucket ptr",
            section_print_fn=None, bucket_fn=None, strip_leading_zero=None,
            bucket_sort_fn=None):
        """print_log2_hist(val_type="value", section_header="Bucket ptr",
                           section_print_fn=None, bucket_fn=None,
                           strip_leading_zero=None, bucket_sort_fn=None):

        Prints a table as a log2 histogram. The table must be stored as
        log2. The val_type argument is optional, and is a column header.
        If the histogram has a secondary key, multiple tables will print
        and section_header can be used as a header description for each.
        If section_print_fn is not None, it will be passed the bucket value
        to format into a string as it sees fit. If bucket_fn is not None,
        it will be used to produce a bucket value for the histogram keys.
        If the value of strip_leading_zero is not False, prints a histogram
        that is omitted leading zeros from the beginning.
        If bucket_sort_fn is not None, it will be used to sort the buckets
        before iterating them, and it is useful when there are multiple fields
        in the secondary key.
        The maximum index allowed is log2_index_max (65), which will
        accommodate any 64-bit integer in the histogram.
        """
        if isinstance(self.Key(), ct.Structure):
            tmp = {}
            f1 = self.Key._fields_[0][0]
            f2 = self.Key._fields_[1][0]

            # The above code assumes that self.Key._fields_[1][0] holds the
            # slot. But a padding member may have been inserted here, which
            # breaks the assumption and leads to chaos.
            # TODO: this is a quick fix. Fixing/working around in the BCC
            # internal library is the right thing to do.
            if f2 == '__pad_1' and len(self.Key._fields_) == 3:
                f2 = self.Key._fields_[2][0]

            for k, v in self.items():
                bucket = getattr(k, f1)
                if bucket_fn:
                    bucket = bucket_fn(bucket)
                vals = tmp[bucket] = tmp.get(bucket, [0] * log2_index_max)
                slot = getattr(k, f2)
                vals[slot] = v.value

            buckets = list(tmp.keys())
            if bucket_sort_fn:
                buckets = bucket_sort_fn(buckets)

            for bucket in buckets:
                vals = tmp[bucket]
                if section_print_fn:
                    print("\n%s = %s" % (section_header,
                        section_print_fn(bucket)))
                else:
                    print("\n%s = %r" % (section_header, bucket))
                _print_log2_hist(vals, val_type, strip_leading_zero)
        else:
            vals = [0] * log2_index_max
            for k, v in self.items():
                vals[k.value] = v.value
            _print_log2_hist(vals, val_type, strip_leading_zero)

    def print_linear_hist(self, val_type="value", section_header="Bucket ptr",
            section_print_fn=None, bucket_fn=None, bucket_sort_fn=None):
        """print_linear_hist(val_type="value", section_header="Bucket ptr",
                           section_print_fn=None, bucket_fn=None,
                           bucket_sort_fn=None)

        Prints a table as a linear histogram. This is intended to span integer
        ranges, eg, from 0 to 100. The val_type argument is optional, and is a
        column header.  If the histogram has a secondary key, multiple tables
        will print and section_header can be used as a header description for
        each.  If section_print_fn is not None, it will be passed the bucket
        value to format into a string as it sees fit. If bucket_fn is not None,
        it will be used to produce a bucket value for the histogram keys.
        If bucket_sort_fn is not None, it will be used to sort the buckets
        before iterating them, and it is useful when there are multiple fields
        in the secondary key.
        The maximum index allowed is linear_index_max (1025), which is hoped
        to be sufficient for integer ranges spanned.
        """
        if isinstance(self.Key(), ct.Structure):
            tmp = {}
            f1 = self.Key._fields_[0][0]
            f2 = self.Key._fields_[1][0]
            for k, v in self.items():
                bucket = getattr(k, f1)
                if bucket_fn:
                    bucket = bucket_fn(bucket)
                vals = tmp[bucket] = tmp.get(bucket, [0] * linear_index_max)
                slot = getattr(k, f2)
                vals[slot] = v.value

            buckets = tmp.keys()
            if bucket_sort_fn:
                buckets = bucket_sort_fn(buckets)

            for bucket in buckets:
                vals = tmp[bucket]
                if section_print_fn:
                    print("\n%s = %s" % (section_header,
                        section_print_fn(bucket)))
                else:
                    print("\n%s = %r" % (section_header, bucket))
                _print_linear_hist(vals, val_type)
        else:
            vals = [0] * linear_index_max
            for k, v in self.items():
                try:
                    vals[k.value] = v.value
                except IndexError:
                    # Improve error text. If the limit proves a nusiance, this
                    # function be rewritten to avoid having one.
                    raise IndexError(("Index in print_linear_hist() of %d " +
                        "exceeds max of %d.") % (k.value, linear_index_max))
            _print_linear_hist(vals, val_type)

class HashTable(TableBase):
    def __init__(self, *args, **kwargs):
        super(HashTable, self).__init__(*args, **kwargs)

    def __len__(self):
        i = 0
        for k in self: i += 1
        return i

class LruHash(HashTable):
    def __init__(self, *args, **kwargs):
        super(LruHash, self).__init__(*args, **kwargs)

class ArrayBase(TableBase):
    def __init__(self, *args, **kwargs):
        super(ArrayBase, self).__init__(*args, **kwargs)
        self.max_entries = int(lib.bpf_table_max_entries_id(self.bpf.module,
                self.map_id))

    def _normalize_key(self, key):
        if isinstance(key, int):
            if key < 0:
                key = len(self) + key
            key = self.Key(key)
        if not isinstance(key, ct._SimpleCData):
            raise IndexError("Array index must be an integer type")
        if key.value >= len(self):
            raise IndexError("Array index out of range")
        return key

    def __len__(self):
        return self.max_entries

    def __getitem__(self, key):
        key = self._normalize_key(key)
        return super(ArrayBase, self).__getitem__(key)

    def __setitem__(self, key, leaf):
        key = self._normalize_key(key)
        super(ArrayBase, self).__setitem__(key, leaf)

    def __delitem__(self, key):
        key = self._normalize_key(key)
        super(ArrayBase, self).__delitem__(key)

    def clearitem(self, key):
        key = self._normalize_key(key)
        leaf = self.Leaf()
        res = lib.bpf_update_elem(self.map_fd, ct.byref(key), ct.byref(leaf), 0)
        if res < 0:
            raise Exception("Could not clear item")

    def __iter__(self):
        return ArrayBase.Iter(self, self.Key)

    class Iter(object):
        def __init__(self, table, keytype):
            self.Key = keytype
            self.table = table
            self.i = -1

        def __iter__(self):
            return self
        def __next__(self):
            return self.next()
        def next(self):
            self.i += 1
            if self.i == len(self.table):
                raise StopIteration()
            return self.Key(self.i)

class Array(ArrayBase):
    def __init__(self, *args, **kwargs):
        super(Array, self).__init__(*args, **kwargs)

    def __delitem__(self, key):
        # Delete in Array type does not have an effect, so zero out instead
        self.clearitem(key)

class ProgArray(ArrayBase):
    def __init__(self, *args, **kwargs):
        super(ProgArray, self).__init__(*args, **kwargs)

    def __setitem__(self, key, leaf):
        if isinstance(leaf, int):
            leaf = self.Leaf(leaf)
        if isinstance(leaf, self.bpf.Function):
            leaf = self.Leaf(leaf.fd)
        super(ProgArray, self).__setitem__(key, leaf)

class FileDesc:
    def __init__(self, fd):
        if (fd is None) or (fd < 0):
            raise Exception("Invalid file descriptor")
        self.fd = fd

    def clean_up(self):
        if (self.fd is not None) and (self.fd >= 0):
            os.close(self.fd)
            self.fd = None

    def __del__(self):
        self.clean_up()

    def __enter__(self, *args, **kwargs):
        return self

    def __exit__(self, *args, **kwargs):
        self.clean_up()

class CgroupArray(ArrayBase):
    def __init__(self, *args, **kwargs):
        super(CgroupArray, self).__init__(*args, **kwargs)

    def __setitem__(self, key, leaf):
        if isinstance(leaf, int):
            super(CgroupArray, self).__setitem__(key, self.Leaf(leaf))
        elif isinstance(leaf, str):
            # TODO: Add os.O_CLOEXEC once we move to Python version >3.3
            with FileDesc(os.open(leaf, os.O_RDONLY)) as f:
                super(CgroupArray, self).__setitem__(key, self.Leaf(f.fd))
        else:
            raise Exception("Cgroup array key must be either FD or cgroup path")

class PerfEventArray(ArrayBase):

    def __init__(self, *args, **kwargs):
        super(PerfEventArray, self).__init__(*args, **kwargs)
        self._open_key_fds = {}
        self._event_class = None

    def __del__(self):
        keys = list(self._open_key_fds.keys())
        for key in keys:
            del self[key]

    def __delitem__(self, key):
        if key not in self._open_key_fds:
            return
        # Delete entry from the array
        super(PerfEventArray, self).__delitem__(key)
        key_id = (id(self), key)
        if key_id in self.bpf.perf_buffers:
            # The key is opened for perf ring buffer
            lib.perf_reader_free(self.bpf.perf_buffers[key_id])
            del self.bpf.perf_buffers[key_id]
            del self._cbs[key]
        else:
            # The key is opened for perf event read
            lib.bpf_close_perf_event_fd(self._open_key_fds[key])
        del self._open_key_fds[key]

    def event(self, data):
        """event(data)

        When perf buffers are opened to receive custom perf event,
        the underlying event data struct which is defined in C in
        the BPF program can be deduced via this function. This avoids
        redundant definitions in Python.
        """
        if self._event_class == None:
            self._event_class = _get_event_class(self)
        return ct.cast(data, ct.POINTER(self._event_class)).contents

    def open_perf_buffer(self, callback, page_cnt=8, lost_cb=None):
        """open_perf_buffers(callback)

        Opens a set of per-cpu ring buffer to receive custom perf event
        data from the bpf program. The callback will be invoked for each
        event submitted from the kernel, up to millions per second. Use
        page_cnt to change the size of the per-cpu ring buffer. The value
        must be a power of two and defaults to 8.
        """

        if page_cnt & (page_cnt - 1) != 0:
            raise Exception("Perf buffer page_cnt must be a power of two")

        for i in get_online_cpus():
            self._open_perf_buffer(i, callback, page_cnt, lost_cb)

    def _open_perf_buffer(self, cpu, callback, page_cnt, lost_cb):
        def raw_cb_(_, data, size):
            try:
                callback(cpu, data, size)
            except IOError as e:
                if e.errno == errno.EPIPE:
                    exit()
                else:
                    raise e
        def lost_cb_(_, lost):
            try:
                lost_cb(lost)
            except IOError as e:
                if e.errno == errno.EPIPE:
                    exit()
                else:
                    raise e
        fn = _RAW_CB_TYPE(raw_cb_)
        lost_fn = _LOST_CB_TYPE(lost_cb_) if lost_cb else ct.cast(None, _LOST_CB_TYPE)
        reader = lib.bpf_open_perf_buffer(fn, lost_fn, None, -1, cpu, page_cnt)
        if not reader:
            raise Exception("Could not open perf buffer")
        fd = lib.perf_reader_fd(reader)
        self[self.Key(cpu)] = self.Leaf(fd)
        self.bpf.perf_buffers[(id(self), cpu)] = reader
        # keep a refcnt
        self._cbs[cpu] = (fn, lost_fn)
        # The actual fd is held by the perf reader, add to track opened keys
        self._open_key_fds[cpu] = -1

    def _open_perf_event(self, cpu, typ, config):
        fd = lib.bpf_open_perf_event(typ, config, -1, cpu)
        if fd < 0:
            raise Exception("bpf_open_perf_event failed")
        self[self.Key(cpu)] = self.Leaf(fd)
        self._open_key_fds[cpu] = fd

    def open_perf_event(self, typ, config):
        """open_perf_event(typ, config)

        Configures the table such that calls from the bpf program to
        table.perf_read(CUR_CPU_IDENTIFIER) will return the hardware
        counter denoted by event ev on the local cpu.
        """
        for i in get_online_cpus():
            self._open_perf_event(i, typ, config)

class PerCpuHash(HashTable):
    def __init__(self, *args, **kwargs):
        self.reducer = kwargs.pop("reducer", None)
        super(PerCpuHash, self).__init__(*args, **kwargs)
        self.sLeaf = self.Leaf
        self.total_cpu = len(get_possible_cpus())
        # This needs to be 8 as hard coded into the linux kernel.
        self.alignment = ct.sizeof(self.sLeaf) % 8
        if self.alignment == 0:
            self.Leaf = self.sLeaf * self.total_cpu
        else:
            # Currently Float, Char, un-aligned structs are not supported
            if self.sLeaf == ct.c_uint:
                self.Leaf = ct.c_uint64 * self.total_cpu
            elif self.sLeaf == ct.c_int:
                self.Leaf = ct.c_int64 * self.total_cpu
            else:
                raise IndexError("Leaf must be aligned to 8 bytes")

    def getvalue(self, key):
        result = super(PerCpuHash, self).__getitem__(key)
        if self.alignment == 0:
            ret = result
        else:
            ret = (self.sLeaf * self.total_cpu)()
            for i in range(0, self.total_cpu):
                ret[i] = result[i]
        return ret

    def __getitem__(self, key):
        if self.reducer:
            return reduce(self.reducer, self.getvalue(key))
        else:
            return self.getvalue(key)

    def __setitem__(self, key, leaf):
        super(PerCpuHash, self).__setitem__(key, leaf)

    def sum(self, key):
        if isinstance(self.Leaf(), ct.Structure):
            raise IndexError("Leaf must be an integer type for default sum functions")
        return self.sLeaf(sum(self.getvalue(key)))

    def max(self, key):
        if isinstance(self.Leaf(), ct.Structure):
            raise IndexError("Leaf must be an integer type for default max functions")
        return self.sLeaf(max(self.getvalue(key)))

    def average(self, key):
        result = self.sum(key)
        return result.value / self.total_cpu

class LruPerCpuHash(PerCpuHash):
    def __init__(self, *args, **kwargs):
        super(LruPerCpuHash, self).__init__(*args, **kwargs)

class PerCpuArray(ArrayBase):
    def __init__(self, *args, **kwargs):
        self.reducer = kwargs.pop("reducer", None)
        super(PerCpuArray, self).__init__(*args, **kwargs)
        self.sLeaf = self.Leaf
        self.total_cpu = len(get_possible_cpus())
        # This needs to be 8 as hard coded into the linux kernel.
        self.alignment = ct.sizeof(self.sLeaf) % 8
        if self.alignment == 0:
            self.Leaf = self.sLeaf * self.total_cpu
        else:
            # Currently Float, Char, un-aligned structs are not supported
            if self.sLeaf == ct.c_uint:
                self.Leaf = ct.c_uint64 * self.total_cpu
            elif self.sLeaf == ct.c_int:
                self.Leaf = ct.c_int64 * self.total_cpu
            else:
                raise IndexError("Leaf must be aligned to 8 bytes")

    def getvalue(self, key):
        result = super(PerCpuArray, self).__getitem__(key)
        if self.alignment == 0:
            ret = result
        else:
            ret = (self.sLeaf * self.total_cpu)()
            for i in range(0, self.total_cpu):
                ret[i] = result[i]
        return ret

    def __getitem__(self, key):
        if (self.reducer):
            return reduce(self.reducer, self.getvalue(key))
        else:
            return self.getvalue(key)

    def __setitem__(self, key, leaf):
        super(PerCpuArray, self).__setitem__(key, leaf)

    def __delitem__(self, key):
        # Delete in this type does not have an effect, so zero out instead
        self.clearitem(key)

    def sum(self, key):
        if isinstance(self.Leaf(), ct.Structure):
            raise IndexError("Leaf must be an integer type for default sum functions")
        return self.sLeaf(sum(self.getvalue(key)))

    def max(self, key):
        if isinstance(self.Leaf(), ct.Structure):
            raise IndexError("Leaf must be an integer type for default max functions")
        return self.sLeaf(max(self.getvalue(key)))

    def average(self, key):
        result = self.sum(key)
        return result.value / self.total_cpu

class LpmTrie(TableBase):
    def __init__(self, *args, **kwargs):
        super(LpmTrie, self).__init__(*args, **kwargs)

    def __len__(self):
        raise NotImplementedError

class StackTrace(TableBase):
    MAX_DEPTH = 127
    BPF_F_STACK_BUILD_ID = (1<<5)
    BPF_STACK_BUILD_ID_EMPTY =  0 #can't get stacktrace
    BPF_STACK_BUILD_ID_VALID = 1 #valid build-id,ip
    BPF_STACK_BUILD_ID_IP = 2 #fallback to ip

    def __init__(self, *args, **kwargs):
        super(StackTrace, self).__init__(*args, **kwargs)

    class StackWalker(object):
        def __init__(self, stack, flags, resolve=None):
            self.stack = stack
            self.n = -1
            self.resolve = resolve
            self.flags = flags

        def __iter__(self):
            return self

        def __next__(self):
            return self.next()

        def next(self):
            self.n += 1
            if self.n == StackTrace.MAX_DEPTH:
                raise StopIteration()

            if self.flags & StackTrace.BPF_F_STACK_BUILD_ID:
              addr = self.stack.trace[self.n]
              if addr.status == StackTrace.BPF_STACK_BUILD_ID_IP or \
                 addr.status == StackTrace.BPF_STACK_BUILD_ID_EMPTY:
                  raise StopIteration()
            else:
              addr = self.stack.ip[self.n]

            if addr == 0 :
                raise StopIteration()

            return self.resolve(addr) if self.resolve else addr

    def walk(self, stack_id, resolve=None):
        return StackTrace.StackWalker(self[self.Key(stack_id)], self.flags, resolve)

    def __len__(self):
        i = 0
        for k in self: i += 1
        return i

    def clear(self):
        pass

class DevMap(ArrayBase):
    def __init__(self, *args, **kwargs):
        super(DevMap, self).__init__(*args, **kwargs)

class CpuMap(ArrayBase):
    def __init__(self, *args, **kwargs):
        super(CpuMap, self).__init__(*args, **kwargs)

class XskMap(ArrayBase):
    def __init__(self, *args, **kwargs):
        super(XskMap, self).__init__(*args, **kwargs)

class MapInMapArray(ArrayBase):
    def __init__(self, *args, **kwargs):
        super(MapInMapArray, self).__init__(*args, **kwargs)

class MapInMapHash(HashTable):
    def __init__(self, *args, **kwargs):
        super(MapInMapHash, self).__init__(*args, **kwargs)

class RingBuf(TableBase):
    def __init__(self, *args, **kwargs):
        super(RingBuf, self).__init__(*args, **kwargs)
        self._ringbuf = None
        self._event_class = None

    def __delitem(self, key):
        pass

    def __del__(self):
        pass

    def __len__(self):
        return 0

    def event(self, data):
        """event(data)

        When ring buffers are opened to receive custom event,
        the underlying event data struct which is defined in C in
        the BPF program can be deduced via this function. This avoids
        redundant definitions in Python.
        """
        if self._event_class == None:
            self._event_class = _get_event_class(self)
        return ct.cast(data, ct.POINTER(self._event_class)).contents

    def open_ring_buffer(self, callback, ctx=None):
        """open_ring_buffer(callback)

        Opens a ring buffer to receive custom event data from the bpf program.
        The callback will be invoked for each event submitted from the kernel,
        up to millions per second.
        """

        def ringbuf_cb_(ctx, data, size):
            try:
                ret = callback(ctx, data, size)
                # Callback for ringbufs should _always_ return an integer.
                # If the function the user registers does not,
                # simply fall back to returning 0.
                try:
                    ret = int(ret)
                except:
                    ret = 0
            except IOError as e:
                if e.errno == errno.EPIPE:
                    exit()
                else:
                    raise e
            return ret

        fn = _RINGBUF_CB_TYPE(ringbuf_cb_)
        self.bpf._open_ring_buffer(self.map_fd, fn, ctx)
        # keep a refcnt
        self._cbs[0] = fn

class QueueStack:
    # Flag for map.push
    BPF_EXIST = 2

    def __init__(self, bpf, map_id, map_fd, leaftype):
        self.bpf = bpf
        self.map_id = map_id
        self.map_fd = map_fd
        self.Leaf = leaftype
        self.ttype = lib.bpf_table_type_id(self.bpf.module, self.map_id)
        self.flags = lib.bpf_table_flags_id(self.bpf.module, self.map_id)

    def leaf_sprintf(self, leaf):
        buf = ct.create_string_buffer(ct.sizeof(self.Leaf) * 8)
        res = lib.bpf_table_leaf_snprintf(self.bpf.module, self.map_id, buf,
                                          len(buf), ct.byref(leaf))
        if res < 0:
            raise Exception("Could not printf leaf")
        return buf.value

    def leaf_scanf(self, leaf_str):
        leaf = self.Leaf()
        res = lib.bpf_table_leaf_sscanf(self.bpf.module, self.map_id, leaf_str,
                                        ct.byref(leaf))
        if res < 0:
            raise Exception("Could not scanf leaf")
        return leaf

    def push(self, leaf, flags=0):
        res = lib.bpf_update_elem(self.map_fd, None, ct.byref(leaf), flags)
        if res < 0:
            errstr = os.strerror(ct.get_errno())
            raise Exception("Could not push to table: %s" % errstr)

    def pop(self):
        leaf = self.Leaf()
        res = lib.bpf_lookup_and_delete(self.map_fd, None, ct.byref(leaf))
        if res < 0:
            raise KeyError("Could not pop from table")
        return leaf

    def peek(self):
        leaf = self.Leaf()
        res = lib.bpf_lookup_elem(self.map_fd, None, ct.byref(leaf))
        if res < 0:
            raise KeyError("Could not peek table")
        return leaf


text:
const Property = require('./contact_property')

class Contact {
  constructor(client) {
    this.client = client
    this.properties = new Property(this.client)
  }

  get(options) {
    return this.client.apiRequest({
      method: 'GET',
      path: '/contacts/v1/lists/all/contacts/all',
      qs: options,
    })
  }

  getAll(options) {
    return this.get(options)
  }

  getRecentlyModified(options) {
    return this.client.apiRequest({
      method: 'GET',
      path: '/contacts/v1/lists/recently_updated/contacts/recent',
      qs: options,
    })
  }

  getRecentlyCreated(options) {
    return this.client.apiRequest({
      method: 'GET',
      path: '/contacts/v1/lists/all/contacts/recent',
      qs: options,
    })
  }

  getByEmail(email) {
    return this.client.apiRequest({
      method: 'GET',
      path: `/contacts/v1/contact/email/${email}/profile`,
    })
  }

  getByEmailBatch(emails) {
    return this.client.apiRequest({
      method: 'GET',
      path: '/contacts/v1/contact/emails/batch',
      qs: { email: emails },
      qsStringifyOptions: { indices: false },
    })
  }

  getById(id, options) {
    return this.client.apiRequest({
      method: 'GET',
      path: `/contacts/v1/contact/vid/${id}/profile`,
      qs: options,
    })
  }

  getByIdBatch(ids) {
    return this.client.apiRequest({
      method: 'GET',
      path: '/contacts/v1/contact/vids/batch',
      qs: { vid: ids },
      qsStringifyOptions: { indices: false },
    })
  }

  getByToken(token) {
    return this.client.apiRequest({
      method: 'GET',
      path: `/contacts/v1/contact/utk/${token}/profile`,
    })
  }

  delete(id) {
    return this.client.apiRequest({
      method: 'DELETE',
      path: `/contacts/v1/contact/vid/${id}`,
    })
  }

  update(id, data) {
    return this.client.apiRequest({
      method: 'POST',
      path: `/contacts/v1/contact/vid/${id}/profile`,
      body: data,
    })
  }

  create(data) {
    return this.client.apiRequest({
      method: 'POST',
      path: '/contacts/v1/contact',
      body: data,
    })
  }

  createOrUpdate(email, data) {
    return this.client.apiRequest({
      method: 'POST',
      path: `/contacts/v1/contact/createOrUpdate/email/${email}`,
      body: data,
    })
  }

  updateByEmail(email, data) {
    return this.client.apiRequest({
      method: 'POST',
      path: `/contacts/v1/contact/email/${email}/profile`,
      body: data,
    })
  }

  // note: response to successful batch update is undefined by design : http://developers.hubspot.com/docs/methods/contacts/batch_create_or_update
  createOrUpdateBatch(data) {
    return this.client.apiRequest({
      method: 'POST',
      path: '/contacts/v1/contact/batch',
      body: data,
    })
  }

  merge(primaryVid, secondaryVid) {
    const data = {
      vidToMerge: secondaryVid,
    }
    return this.client.apiRequest({
      method: 'POST',
      path: `/contacts/v1/contact/merge-vids/${primaryVid}`,
      body: data,
    })
  }

  search(query, options) {
    if (!options) options = {}
    options.q = query
    return this.client.apiRequest({
      method: 'GET',
      path: '/contacts/v1/search/query',
      qs: options,
    })
  }

  addSecondaryEmail(vid, secondaryEmail) {
    return this.client.apiRequest({
      method: 'PUT',
      path: `/contacts/v1/secondary-email/${vid}/email/${secondaryEmail}`,
    })
  }
}

module.exports = Contact


text:
<?xml version="1.0" encoding="UTF-8" ?>
<class name="VisualShaderNodeFloatOp" inherits="VisualShaderNode" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../class.xsd">
	<brief_description>
		A floating-point scalar operator to be used within the visual shader graph.
	</brief_description>
	<description>
		Applies [member operator] to two floating-point inputs: [code]a[/code] and [code]b[/code].
	</description>
	<tutorials>
	</tutorials>
	<members>
		<member name="operator" type="int" setter="set_operator" getter="get_operator" enum="VisualShaderNodeFloatOp.Operator" default="0">
			An operator to be applied to the inputs. See [enum Operator] for options.
		</member>
	</members>
	<constants>
		<constant name="OP_ADD" value="0" enum="Operator">
			Sums two numbers using [code]a + b[/code].
		</constant>
		<constant name="OP_SUB" value="1" enum="Operator">
			Subtracts two numbers using [code]a - b[/code].
		</constant>
		<constant name="OP_MUL" value="2" enum="Operator">
			Multiplies two numbers using [code]a * b[/code].
		</constant>
		<constant name="OP_DIV" value="3" enum="Operator">
			Divides two numbers using [code]a / b[/code].
		</constant>
		<constant name="OP_MOD" value="4" enum="Operator">
			Calculates the remainder of two numbers. Translates to [code]mod(a, b)[/code] in the Godot Shader Language.
		</constant>
		<constant name="OP_POW" value="5" enum="Operator">
			Raises the [code]a[/code] to the power of [code]b[/code]. Translates to [code]pow(a, b)[/code] in the Godot Shader Language.
		</constant>
		<constant name="OP_MAX" value="6" enum="Operator">
			Returns the greater of two numbers. Translates to [code]max(a, b)[/code] in the Godot Shader Language.
		</constant>
		<constant name="OP_MIN" value="7" enum="Operator">
			Returns the lesser of two numbers. Translates to [code]min(a, b)[/code] in the Godot Shader Language.
		</constant>
		<constant name="OP_ATAN2" value="8" enum="Operator">
			Returns the arc-tangent of the parameters. Translates to [code]atan(a, b)[/code] in the Godot Shader Language.
		</constant>
		<constant name="OP_STEP" value="9" enum="Operator">
			Generates a step function by comparing [code]b[/code](x) to [code]a[/code](edge). Returns 0.0 if [code]x[/code] is smaller than [code]edge[/code] and otherwise 1.0. Translates to [code]step(a, b)[/code] in the Godot Shader Language.
		</constant>
		<constant name="OP_ENUM_SIZE" value="10" enum="Operator">
			Represents the size of the [enum Operator] enum.
		</constant>
	</constants>
</class>


text:
<?php
namespace CESPres\Core\Exceptions;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;

class PersistenceException extends \Exception implements HttpExceptionInterface {

    /**
     * Returns the status code.
     *
     * @return int An HTTP response status code
     */
    public function getStatusCode()
    {
        return Response::HTTP_INTERNAL_SERVER_ERROR;
    }

    /**
     * Returns response headers.
     *
     * @return array Response headers
     */
    public function getHeaders()
    {
        return array();
    }
}


text:
using SharpAvi.Utilities;
using System;
using System.Threading.Tasks;

namespace SharpAvi.Output
{
    /// <summary>
    /// Adds asynchronous writes support for underlying stream.
    /// </summary>
    internal class AsyncAudioStreamWrapper : AudioStreamWrapperBase
    {
        private readonly SequentialInvoker writeInvoker = new SequentialInvoker();

        public AsyncAudioStreamWrapper(IAviAudioStreamInternal baseStream)
            : base(baseStream)
        {
        }

        public override void WriteBlock(byte[] data, int startIndex, int length)
        {
            Argument.IsNotNull(data, nameof(data));
            Argument.IsNotNegative(startIndex, nameof(startIndex));
            Argument.IsPositive(length, nameof(length));
            Argument.ConditionIsMet(startIndex + length <= data.Length, "End offset exceeds the length of data.");

            writeInvoker.Invoke(() => base.WriteBlock(data, startIndex, length));
        }

        public override Task WriteBlockAsync(byte[] data, int startIndex, int length)
        {
            Argument.IsNotNull(data, nameof(data));
            Argument.IsNotNegative(startIndex, nameof(startIndex));
            Argument.IsPositive(length, nameof(length));
            Argument.ConditionIsMet(startIndex + length <= data.Length, "End offset exceeds the length of data.");

            return writeInvoker.InvokeAsync(() => base.WriteBlock(data, startIndex, length));
        }

#if NET5_0_OR_GREATER
        public unsafe override void WriteBlock(ReadOnlySpan<byte> data)
        {
            Argument.Meets(data.Length > 0, nameof(data), "Cannot write an empty block.");

            fixed (void* ptr = data)
            {
                var dataPtr = new IntPtr(ptr);
                var dataLength = data.Length;
                writeInvoker.Invoke(() =>
                {
                    var dataSpan = new Span<byte>(dataPtr.ToPointer(), dataLength);
                    base.WriteBlock(dataSpan);
                });
            }
        }

        public override Task WriteBlockAsync(ReadOnlyMemory<byte> data)
        {
            Argument.Meets(data.Length > 0, nameof(data), "Cannot write an empty block.");

            return writeInvoker.InvokeAsync(() => base.WriteBlock(data.Span));
        }
#endif

        public override void FinishWriting()
        {
            // Perform all pending writes and then let the base stream to finish
            // (possibly writing some more data synchronously)
            writeInvoker.WaitForPendingInvocations();

            base.FinishWriting();
        }
    }
}


text:
var MongoClient = require('mongodb').MongoClient,
unzip = require('unzip'),
Converter = require("csvtojson").Converter,
fs = require('fs');

var DRS_COLLECTION = "drscollection"; // Direct reachable stops
var NEIGHBOURS_COLLECTION = "neighbours"; // Direct and indirect reachable stops
var K = 8; // connection radius

var stops = JSON.parse(require('fs').readFileSync('stops.json', 'utf8'));

var reload_drs = true; // reload DRS stops in MongoDB

initMOBcalculation();

// Updates every stop of stops with count of direct reachable stops
function initCountDRS(drs, feed, callback) {
    var csvConverter = new Converter({constructResult:false});
    var readstream = fs.createReadStream(drs).pipe(csvConverter);
    var departureStop = null;
    var done = false;
    var count_drs = 0;
    readstream.on('data', function (data) {
      var line = JSON.parse(data);
      // console.log(line);
      var start = line['start_stop_id'];
      var end = line['end_stop_id'];
      var time = line['minimum_time_seconds'];
      if (departureStop == null || departureStop != start) {
        if (departureStop != null) {
          stops[departureStop].count_direct_stops = count_drs; // update the stops object
        }
        count_drs = 0; // reset
        departureStop = start; // update
      }
      count_drs++;
    });
    readstream.on('end', function () {
      // Write last one
      stops[departureStop].count_direct_stops = count_drs; // update the stops object
      console.log("<<<<<<<<<<<<DONE READING COUNT DRS>>>>>>>>>>>>>>>>> ");
      callback();
    });
}

// Calculates a MOB of neighbouring stops for every stop of a feed
function startMOBcalculation(drs, url, feed, callback) {
  // First read the DRS file to update stops with metadata about amount of direct stops
  initCountDRS(drs, feed, function() {
    // Read DRS into direct_reachable_stops collection
    MongoClient.connect(url, function(err, db) {
      console.log("Connected correctly to server.");
      // Empty the collection
      db.collection(NEIGHBOURS_COLLECTION).deleteMany( {}, function(err, results) {
        if (err) {
          console.warn(err.message);
        }
      });
      if (reload_drs) {
        console.log("<<<<<<<<<<<<LOADING DRS>>>>>>>>>>>>>>>>> ")
        db.collection(DRS_COLLECTION).deleteMany( {}, function(err, results) {
          if (err) {
            console.warn(err.message);
          }
        });

        var csvConverter = new Converter({constructResult:false});
        var readstream = fs.createReadStream(drs).pipe(csvConverter);
        var departureStop = null;
        var readingEnded = false;
        var i = 0;
        var j = 0;
        var count_drs = 0;
        readstream.on('data', function (data) {
          var line = JSON.parse(data);
          // console.log(line);
          var start = line['start_stop_id'].toString();
          var end = line['end_stop_id'].toString();
          var time = line['minimum_time_seconds'];
          count_drs++;
          if (departureStop == null || departureStop.stop_id != start || (count_drs == stops[start].count_direct_stops)) {
            if (departureStop != null) {
              i++;
              departureStop.count_direct_stops = count_drs;
              count_drs = 0; // reset
              // Write to collection
              db.collection(DRS_COLLECTION).insertOne(departureStop, function() {
                j++;
                if (i === j+1 && readingEnded) {
                  i = 0;
                  j = 0;
                  readingEnded = false;
                  // Start neighbours algorithm on every stop of the feed
                  console.log("<<<<<<<<<<<<START MOB CALCULATION>>>>>>>>>>>>>>>>> ")
                  calcNeighbours(feed, db, callback);
                }
              });
            }
            // New starting departureStop
            departureStop = {
              stop_id : start.toString(),
              drs : [ { stop_id: end.toString(), timedistance : time } ]
            };
          } else {
            departureStop.drs.push({stop_id: end.toString(), timedistance: time});
          }
        });
        readstream.on('end', function () {
          readingEnded = true;
        });
      } else {
        calcNeighbours(feed, db, callback);
      }
    });
  });
}

function calcNeighbours(feed, db, callback) {
  var readingEnded = false;
  // For every stop in Stops.txt
  var csvConverter = new Converter({constructResult:false});
  var readstream = fs.createReadStream(feed);
  readstream.pipe(unzip.Parse())
  .on('entry', function (entry) {
    var fileName = entry.path;
    // Only interested in stops.txt
    if (fileName === "stops.txt") {
      // csv -> json -> mongoDB
      var stopStream = entry.pipe(csvConverter);
      // 2.1 Algorithm
      stopStream.on('data', function(data) {
        // Pause the stopStream
        stopStream.pause();
        var line = JSON.parse(data);
        console.log(line['stop_id']);
        // Convert to connection_stop_id
        var s = stops[line['stop_id']].connection_stop_id.toString();
        var mob = {stop_id: s.toString(), neighbours: {}};
        var queue = [];
        // Rechtstreekse buren ophalen
        db.collection(DRS_COLLECTION).find({ stop_id : s }).toArray(function(err, neighbours) {
          // Add the coordinates of the center to the MOB
          var coordinates = stops[s].loc.coordinates;
          var lon = coordinates[0];
          var lat = coordinates[1];
          mob.longitude = lon;
          mob.latitude = lat;
          if (neighbours && neighbours.length > 0) {
            for (var i = 0; i < neighbours[0].drs.length; i++) {
              var b = neighbours[0].drs[i];
              // We'll save the coordinates too so the fetcher of a client can easily calculate the importance of a stop
              var coordinates = stops[b.stop_id].loc.coordinates;
              var lon = coordinates[0];
              var lat = coordinates[1];
              mob.neighbours[b.stop_id] = { radius: 1, timedistance: b.timedistance, count_direct_stops: neighbours[0].count_direct_stops, latitude: lat, longitude: lon};
              mob.count_direct_stops = neighbours[0].count_direct_stops;
              if (K > 1) {
                queue.push(b.stop_id);
              }
            }
            loadDRSRecursion(stopStream, db, mob, queue, readingEnded, callback);
          } else {
            // the stop is not used in the time period of the calculated connections
            stopStream.resume();
          }
        });
      });
      stopStream.on('end', function () {
        readingEnded = true;
      });
    } else {
      entry.autodrain();
    }
  });
};

function loadDRSRecursion(stopStream, db, mob, queue, readingEnded, cb) {
  if (queue.length > 0) {
    var start = queue.shift();
    loadDRS(stopStream, db, start, mob, queue);
  } else if (readingEnded){
    db.collection(NEIGHBOURS_COLLECTION).insertOne(mob, function(err, result) {
      db.close();
      cb(); // starts next feed
    });
  } else {
    // 2.2 Write MOB to neighbours collection
    db.collection(NEIGHBOURS_COLLECTION).insertOne(mob, function(err, result) {
      // Next stop
      stopStream.resume();
    });
  }
};

function loadDRS(stopStream, db, start, mob, queue) {
  db.collection(DRS_COLLECTION).find({ stop_id : start }).toArray(function(err, neighbours) {
    if (neighbours && neighbours.length > 0) {
      for (var i = 0; i < neighbours[0].drs.length; i++) {
        var b = neighbours[0].drs[i];
        // Not in MST/MOB
        if (!mob.neighbours[b.stop_id]) {
          var cds = stops[b.stop_id].count_direct_stops; // should be defined, otherwise not driving on the connection dates
          if (!cds) cds = 0;
          var coordinates = stops[b.stop_id].loc.coordinates;
          var lon = coordinates[0];
          var lat = coordinates[1];
          mob.neighbours[b.stop_id] = {radius: (mob.neighbours[start].radius+1), timedistance: (mob.neighbours[start].timedistance+b.timedistance), count_direct_stops: cds, latitude: lat, longitude: lon};
          if (mob.neighbours[b.stop_id].radius < K) {
            queue.push(b.stop_id);
          }
        } else {
          if ((mob.neighbours[start].radius + 1) < mob.neighbours[b.stop_id].radius) {
            mob.neighbours[b.stop_id].radius = mob.neighbours[start].radius + 1;
          }
          if ((mob.neighbours[start].timedistance + b.timedistance) < mob.neighbours[b.stop_id].timedistance) {
            mob.neighbours[b.stop_id].timedistance = mob.neighbours[start].timedistance + b.timedistance;
          }
        }
      }
    }
    // Continue
    loadDRSRecursion(stopStream, db, mob, queue);
  });
};

function initMOBcalculation() {
  // Feed De Lijn
  // var DRS_DELIJN = 'drs-1.txt'; // path to drs file of De Lijn
  // var URL_CONTAINER_DELIJN = 'mongodb://192.168.99.100:28002/lc'; // url to docker container with MongoDB
  // var PATH_FEED_DELIJN = '../collectie-gtfs/de_lijn-gtfs.zip'; // path GTFS feed
  // startMOBcalculation(DRS_DELIJN, URL_CONTAINER_DELIJN, PATH_FEED_DELIJN, function() {
    // Feed NMBS
    var DRS_NMBS = 'drs-NMBS-SNCB.txt';
    var URL_CONTAINER_NMBS = 'mongodb://192.168.99.100:28001/lc';
    var PATH_FEED_NMBS = '../collectie-gtfs/GTFS_20150915.zip';
    startMOBcalculation(DRS_NMBS, URL_CONTAINER_NMBS, PATH_FEED_NMBS, function() {
      // Feed NS
      var DRS_NS = 'drs-100.txt';
      var URL_CONTAINER_NS = 'mongodb://192.168.99.100:28003/lc';
      var PATH_FEED_NS = '../collectie-gtfs/gtfs-iffns-latest.zip';
      startMOBcalculation(DRS_NS, URL_CONTAINER_NS, PATH_FEED_NS, function() {});
    });
  // });
};


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

<title>Minim : : MultiChannelBuffer : : setSample</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link href="stylesheet.css" rel="stylesheet" type="text/css">

    	Minim

    		core |
    		ugens |
    		analysis

MultiChannelBuffer

setSample

Description

    	Sets the value of a sample in the given channel at the given
 offset from the beginning of the buffer.

Signature

void setSample(int channelNumber, int sampleIndex, float value)

Parameters

        channelNumber — int: the channel of the buffer

        sampleIndex — int: the sample offset from the beginning of the buffer

        value — float: the sample value to set

Returns

None

Related

Example

None available

Usage

    	Web & Application


text:
package io.crate.executor.transport.task.elasticsearch;

import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;
import io.crate.analyze.WhereClause;
import io.crate.executor.JobTask;
import io.crate.executor.TaskResult;
import io.crate.jobs.ESJobContext;
import io.crate.jobs.JobContextService;
import io.crate.jobs.JobExecutionContext;
import io.crate.planner.node.dml.ESDeleteByQueryNode;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.deletebyquery.DeleteByQueryRequest;
import org.elasticsearch.action.deletebyquery.DeleteByQueryResponse;
import org.elasticsearch.action.deletebyquery.TransportDeleteByQueryAction;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.UUID;

public class ESDeleteByQueryTask extends JobTask {

    private final static ESQueryBuilder QUERY_BUILDER = new ESQueryBuilder();

    private final List<ListenableFuture<TaskResult>> resultList;
    private final JobExecutionContext context;

    public ESDeleteByQueryTask(UUID jobId,
                               ESDeleteByQueryNode node,
                               TransportDeleteByQueryAction transport,
                               JobContextService jobContextService) {
        super(jobId);
        resultList = new ArrayList<>(node.whereClauses().size());
        List<DeleteByQueryRequest> requests = new ArrayList<>(node.whereClauses().size());
        List<ActionListener> listeners = new ArrayList<>(node.whereClauses().size());

        for (int i = 0; i < node.whereClauses().size(); i++) {
            DeleteByQueryRequest request = new DeleteByQueryRequest();
            SettableFuture<TaskResult> result = SettableFuture.create();
            String[] indices = node.indices().get(i);
            WhereClause whereClause = node.whereClauses().get(i);
            String routing = node.routings().get(i);
            try {
                request.source(QUERY_BUILDER.convert(whereClause));
                request.indices(indices);
                if (whereClause.clusteredBy().isPresent()){
                    request.routing(routing);
                }
            } catch (IOException e) {
                result.setException(e);
            }
            resultList.add(result);
            requests.add(request);
            listeners.add(new Listener(result));
        }

        JobExecutionContext.Builder contextBuilder = jobContextService.newBuilder(jobId());
        ESJobContext esJobContext = new ESJobContext("delete by query", requests, listeners, resultList, transport, null);
        contextBuilder.addSubContext(node.executionPhaseId(), esJobContext);
        context = jobContextService.createContext(contextBuilder);
    }

    @Override
    public void start() {
        context.start();
    }

    @Override
    public List<? extends ListenableFuture<TaskResult>> result() {
        return resultList;
    }

    @Override
    public void upstreamResult(List<? extends ListenableFuture<TaskResult>> result) {
        throw new UnsupportedOperationException(
                String.format(Locale.ENGLISH, "upstreamResult not supported on %s",
                        getClass().getSimpleName()));
    }

    static class Listener implements ActionListener<DeleteByQueryResponse> {

        protected final SettableFuture<TaskResult> result;

        public Listener(SettableFuture<TaskResult> result) {
            this.result = result;
        }

        @Override
        public void onResponse(DeleteByQueryResponse indexDeleteByQueryResponses) {
            result.set(TaskResult.ROW_COUNT_UNKNOWN);
        }

        @Override
        public void onFailure(Throwable e) {
            result.setException(e);
        }
    }
}


text:
CurrentContextPusher::CurrentContextPusher(void):
  m_prior(CoreContext::CurrentContextOrNull())
{}

CurrentContextPusher::CurrentContextPusher(CoreContext& context):
  m_prior(context.SetCurrent())
{}

CurrentContextPusher::CurrentContextPusher(const std::shared_ptr<CoreContext>& pContext) :
  m_prior(pContext->SetCurrent())
{}

CurrentContextPusher::CurrentContextPusher(const std::shared_ptr<GlobalCoreContext>& pContext) :
  m_prior(pContext->SetCurrent())
{}

CurrentContextPusher::CurrentContextPusher(CoreContext* pContext):
  m_prior(pContext->SetCurrent())
{}

CurrentContextPusher::CurrentContextPusher(CurrentContextPusher&& rhs) {
  std::swap(m_prior, rhs.m_prior);
}

CurrentContextPusher::~CurrentContextPusher(void) {
  Pop();
}

std::shared_ptr<CoreContext> CurrentContextPusher::Pop(void) {
  if (pop_invoked)
    // Nothing to do
    return nullptr;

  pop_invoked = true;
  auto retVal = CoreContext::SetCurrent(std::move(m_prior));
  m_prior.reset();
  return retVal;
}


text:
layout: page
title: Hughes Company Conference
date: 2016-05-24
author: Bryan Dougherty
tags: weekly links, java
status: published
summary: Nam egestas posuere aliquam. Mauris a quam ac dolor.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 04/29/2016
  endDate: 05/04/2016
  ctyhocn: BUFEAHX
  groupCode: HCC
published: true
---
Suspendisse pellentesque purus eget magna condimentum sollicitudin. Praesent sit amet odio a arcu consequat posuere. Nunc sit amet finibus arcu, at pretium justo. Proin ac sapien dolor. Sed sodales sapien neque, sit amet venenatis ipsum volutpat sit amet. Nullam vestibulum laoreet lacus, ut ultrices mi tempus dignissim. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nam quam lorem, condimentum in dictum nec, laoreet id massa. Aliquam fringilla venenatis venenatis. Aenean aliquet sollicitudin convallis.

* Quisque eget sapien in nibh porta viverra
* Donec et metus ut felis mollis aliquet eu a nibh.

Vivamus ac eleifend sapien. Maecenas blandit placerat felis, vel dapibus magna faucibus eu. Integer felis elit, ornare tempor nulla eget, porttitor feugiat quam. Donec ac aliquam ante. Integer facilisis felis nec mi pretium venenatis. Ut nibh quam, congue vel nunc vel, aliquet faucibus nunc. Sed condimentum rutrum lectus id laoreet. Vivamus ut ipsum ac lectus tempor posuere. Lorem ipsum dolor sit amet, consectetur adipiscing elit.


text:
namespace MassTransit.Courier.Contracts
{
    using System;

    /// <summary>
    /// Capture the exception information thrown by an activity
    /// </summary>
    public interface ActivityException
    {
        /// <summary>
        /// The tracking number of the activity that threw the exception
        /// </summary>
        Guid ExecutionId { get; }

        /// <summary>
        /// The point in time when the exception occurred
        /// </summary>
        DateTime Timestamp { get; }

        /// <summary>
        /// The time from when the routing slip was created until the exception occurred
        /// </summary>
        TimeSpan Elapsed { get; }

        /// <summary>
        /// The name of the activity that caused the exception
        /// </summary>
        string Name { get; }

        /// <summary>
        /// The host where the exception was thrown
        /// </summary>
        HostInfo Host { get; }

        /// <summary>
        /// The exception details
        /// </summary>
        ExceptionInfo ExceptionInfo { get; }
    }
}


text:
using namespace std;
enum{
  FORWARDS=0,
  PUSH=1,
  POP=2,
  TURN_LEFT=3,
  TURN_RIGHT=4
};
struct operation{
  int optype,op_args;
};
typedef vector<operation> constant;
map<char,constant> Constants;//the "primitive" operations
map<char,string> Rewrite_rules;//the rules that REWRITE
string axiom;//the starting string
int scale=3;//the scale of each forward movement

void evaluate(csv&input,int iterations,const string& current){
  string next;
  if(iterations>0){
    for(char c : current){
      if(iterations > 0){
	if(Rewrite_rules.find(c) == Rewrite_rules.end()){
	  next.push_back(c);//maybe constant without rule
	}else{
	  next.append(Rewrite_rules.find(c)->second);//rewrite rule for sure, maybe operation, but not now
	}
      }
    }
    evaluate(input,iterations-1,next);
  }else{
    cout<<"Final string"<<endl<<current<<endl;
    cursor initial;
    vector<cursor> stack;
    for(int c=0 ; c < current.size(); ++c){
      if(Constants.find(current[c])==Constants.end())
	continue;
      constant current_op = Constants[ current[ c ] ];
      for(int i=0;i < current_op.size();i++){
	switch(current_op[i].optype){
	case FORWARDS:
	  {
	  cursor tmp=initial.forward(scale);
	  input.linefrom(floor(tmp.x),floor(tmp.y),floor(initial.x),floor(initial.y),"d");
	  initial=tmp;
	  }
	  break;
	case TURN_LEFT:
	  initial.left(current_op[i].op_args);

	  break;
	case TURN_RIGHT:
	  initial.right(current_op[i].op_args);
	  break;
	case PUSH:
	  stack.push_back(initial);
	  break;
	case POP:
	  initial=stack.back();
	  stack.pop_back();
	  break;
	}
      }
    }
  }
}
void read_file(const string& filename){
  Json::Value root;
  ifstream e(filename);
  e>>root;
  const Json::Value constants=root["Constant"];
  const Json::Value rewrites=root["Rewrite"];
  const Json::Value axom = root["Axiom"];
  for(int i=0; i < constants.size();i++){
    char key=constants[i].get("key","").asCString()[0];
    const Json::Value a=constants[i],operations=a["value"];
    constant f;
    for(int j=0;j<operations.size();j++){
      operation o;o.optype= operations[j].get("op_type",0).asInt();
      o.op_args=operations[j].get("op_args",0).asInt();
      f.push_back(o);
    }
    Constants[key]=f;
  }
  for(int i=0;i<rewrites.size();i++){
    const Json::Value c=rewrites[i];
    char key=c.get("key","").asCString()[0];
    string f=c.get("value","").asString();
    Rewrite_rules[key]=f;
  }
  axiom=axom.asString();
  e.close();
}
void print_help(int argc,char **argv);
int main(int argc, char** argv){
  int c;
  int iterations=4;
  string output;
  bool make_picture=false;
  string pict;
  scale=4;
  while((c=getopt(argc,argv,"i:r:o:s:p:?"))!=-1){
    switch(c){
    case 'i':
      {
	if(optarg!=NULL){
	string tmp=string(optarg);
      iterations = stoi(tmp);
	}
      }
      break;
    case 'r':
      if(optarg!=NULL){
	read_file(string(optarg));
      }
      break;
    case 'o':
      output= string(optarg);
      break;
    case '?':
      print_help(argc,argv);
      break;
    case 's':
      {
	string g(optarg);
	scale=stoi(g);
      }
      break;
    case 'p':
      pict=optarg;
      make_picture=true;
      break;
    default:
      print_help(argc,argv);
    }
  }
  csv out;
  out.recording=true;
  evaluate(out,iterations,axiom);
  out.writeToFile(output);
  if(make_picture){
    ofstream fc(pict);
    auto dim=out.getDim();
    fc<<"<svg  xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\">"<<endl;
    fc<<"<rect x=\""<<dim[0]<<"\" y=\""<<dim[1]<<"\" width=\""<<out.width()<<"\" height=\""<<out.height()<<"\"/>";
    for(auto q : out.stuff){
      fc<<"<line x1=\""<<q[0]<<"\" y1=\""<<q[1]<<"\" x2=\""<<q[2]<<"\" y2=\""<<q[3]<<"\" stroke=\"black\"/>"<<endl;
    }
    fc<<"</svg>";
  }
  std::cout<<out.width()<<" "<<out.height()<< endl;
}
void print_help(int argc,char **argv){
  cout<<"Proper usage is \""<<argv[0]<<"-i <integer> -r <input file> -o <output file>"<<endl;
}


text:
/**
 * postParameters     - an object of POST data to pass along with each Ajax request
 * modalClass         - class to add to the modal window to allow customization
 * uploadButton       - jQuery object of the element that should open the file chooser
 * uploadAction       - upload to this location (in form of "controller/action")
 * deleteButton       - jQuery object of the element that starts the image deletion process
 * deleteMessage      - confirmation message presented to the user for image deletion
 * deleteAction       - delete image at this location (in form of "controller/action")
 * cropAction         - crop image at this (in form of "controller/action")
 * areaToolOptions    - object with some options for the area tool selector
 *   aspectRatio      - decimal aspect ratio of width/height
 *   initialRectangle - object with options for the initial rectangle
 *     mode           - if set to auto, then the part selected will be the maximum size in the middle of image
 *     x1             - top left x coordinate of th rectangle, if the mode is not set to auto
 *     x2             - bottom right x coordinate of th rectangle, if the mode is not set to auto
 *     y1             - top left y coordinate of th rectangle, if the mode is not set to auto
 *     y2             - bottom right y coordinate of th rectangle, if the mode is not set to auto
 *
 * onImageDelete     - callback to call when image is deleted. First parameter will contain response data.
 * onImageSave       - callback to call when an cropped image is saved. First parameter will contain response data.
 */

/**
 * Image Upload tool.
 */
Craft.ImageUpload = Garnish.Base.extend(
{
	_imageHandler: null,

	init: function(settings)
	{
		this.setSettings(settings, Craft.ImageUpload.defaults);
		this._imageHandler = new Craft.ImageHandler(settings);
	},

	destroy: function()
	{
		this._imageHandler.destroy();
		delete this._imageHandler;

		this.base();
	}
},
{
	$modalContainerDiv: null,

	defaults: {
		postParameters: {},

		modalClass: "",
		uploadButton: {},
		uploadAction: "",

		deleteButton: {},
		deleteMessage: "",
		deleteAction: "",

		cropAction:"",

		constraint: 500,

		areaToolOptions:
		{
			aspectRatio: "1",
			initialRectangle: {
				mode: "auto",
				x1: 0,
				x2: 0,
				y1: 0,
				y2: 0
			}
		},

		onImageDelete: function(response)
		{
			location.reload();
		},
		onImageSave: function(response)
		{
			location.reload();
		}
	}
});

Craft.ImageHandler = Garnish.Base.extend(
{
	modal: null,
	progressBar: null,
	$container: null,

	init: function(settings)
	{
		this.setSettings(settings);

		var element = settings.uploadButton;
		var $uploadInput = $('<input type="file" name="image-upload"/>').hide().insertBefore(element);

		this.progressBar = new Craft.ProgressBar($('

').insertBefore(element));
		this.progressBar.$progressBar.css({
			top: Math.round(element.outerHeight() / 2) - 6
		});

		this.$container = element.parent();

		var options = {
			url: Craft.getActionUrl(this.settings.uploadAction),
			fileInput: $uploadInput,

			element:    this.settings.uploadButton[0],
			action:     Craft.actionUrl + '/' + this.settings.uploadAction,
			formData:   typeof this.settings.postParameters === 'object' ? this.settings.postParameters : {},
			events:     {
				fileuploadstart: $.proxy(function()
				{
					this.$container.addClass('uploading');
					this.progressBar.resetProgressBar();
					this.progressBar.showProgressBar();
				}, this),
				fileuploadprogressall: $.proxy(function(data)
				{
					var progress = parseInt(data.loaded / data.total * 100, 10);
					this.progressBar.setProgressPercentage(progress);
				}, this),
				fileuploaddone: $.proxy(function(event, data)
				{
					this.progressBar.hideProgressBar();
					this.$container.removeClass('uploading');

					var response = data.result;

					if (response.error)
					{
						alert(response.error);
						return;
					}

					if (Craft.ImageUpload.$modalContainerDiv == null)
					{
						Craft.ImageUpload.$modalContainerDiv = $('

').addClass(settings.modalClass).appendTo(Garnish.$bod);
					}

					if (response.fileName)
					{
						this.source = response.fileName;
					}

					if (response.html)
					{
						Craft.ImageUpload.$modalContainerDiv.empty().append(response.html);

						if (!this.modal)
						{
							this.modal = new Craft.ImageModal(Craft.ImageUpload.$modalContainerDiv, {
								postParameters: settings.postParameters,
								cropAction:     settings.cropAction
							});

							this.modal.imageHandler = this;
						}
						else
						{
							this.modal.show();
						}

						this.modal.bindButtons();
						this.modal.addListener(this.modal.$saveBtn, 'click', 'saveImage');
						this.modal.addListener(this.modal.$cancelBtn, 'click', 'cancel');

						this.modal.removeListener(Garnish.Modal.$shade, 'click');

						setTimeout($.proxy(function()
						{
							Craft.ImageUpload.$modalContainerDiv.find('img').load($.proxy(function()
							{
								var areaTool = new Craft.ImageAreaTool(settings.areaToolOptions, this.modal);
								areaTool.showArea();
								this.modal.cropAreaTool = areaTool;
							}, this));
						}, this), 1);
					}
				}, this)
			},
			acceptFileTypes: /(jpg|jpeg|gif|png)/
		};

		// If CSRF protection isn't enabled, these won't be defined.
		if (typeof Craft.csrfTokenName !== 'undefined' && typeof Craft.csrfTokenValue !== 'undefined')
		{
			// Add the CSRF token
			options.formData[Craft.csrfTokenName] = Craft.csrfTokenValue;
		}

		this.uploader = new Craft.Uploader(element, options);

		this.addListener($(settings.deleteButton), 'click', function(ev)
		{
			if (confirm(settings.deleteMessage))
			{
				$(ev.currentTarget).parent().append('

');
				Craft.postActionRequest(settings.deleteAction, settings.postParameters, $.proxy(function(response, textStatus)
				{
					if (textStatus == 'success')
					{
						this.onImageDelete(response);
					}

				}, this));

			}
		});

		this.addListener($(settings.uploadButton), 'click', function(ev)
		{
			$(ev.currentTarget).siblings('input[type=file]').click();
		});

	},

	onImageSave: function(data)
	{
		this.settings.onImageSave.apply(this, [data]);
	},

	onImageDelete: function(data)
	{
		this.settings.onImageDelete.apply(this, [data]);
	},

	destroy: function()
	{
		this.progressBar.destroy();
		delete this.progressBar;

		if (this.modal)
		{
			this.modal.destroy();
			delete this.modal;
		}

		if (this.uploader)
		{
			this.uploader.destroy();
			delete this.uploader;
		}

		this.base();
	}
});

Craft.ImageModal = Garnish.Modal.extend(
{
	$container: null,
	$saveBtn: null,
	$cancelBtn: null,

	areaSelect: null,
	source: null,
	_postParameters: null,
	_cropAction: "",
	imageHandler: null,
	cropAreaTool: null,

	init: function($container, settings)
	{
		this.cropAreaTool = null;
		this.base($container, settings);
		this._postParameters = settings.postParameters;
		this._cropAction = settings.cropAction;
	},

	bindButtons: function()
	{
		this.$saveBtn = this.$container.find('.submit:first');
		this.$cancelBtn = this.$container.find('.cancel:first');
	},

	cancel: function()
	{
		this.hide();
		this.$container.remove();
		this.destroy();
	},

	saveImage: function()
	{
		var selection = this.areaSelect.tellSelect();

		var params = {
			x1: selection.x,
			y1: selection.y,
			x2: selection.x2,
			y2: selection.y2,
			source: this.source
		};

		params = $.extend(this._postParameters, params);

		Craft.postActionRequest(this._cropAction, params, $.proxy(function(response, textStatus)
		{
			if (textStatus == 'success')
			{
				if (response.error)
				{
					Craft.cp.displayError(response.error);
				}
				else
				{
					this.imageHandler.onImageSave.apply(this.imageHandler, [response]);
				}
			}

			this.hide();
			this.$container.remove();
			this.destroy();
		}, this));

		this.areaSelect.setOptions({disable: true});
		this.removeListener(this.$saveBtn, 'click');
		this.removeListener(this.$cancelBtn, 'click');

		this.$container.find('.crop-image').fadeTo(50, 0.5);
	}

});

Craft.ImageAreaTool = Garnish.Base.extend(
{
	api:             null,
	$container:      null,
	containingModal: null,

	init: function(settings, containingModal)
	{
		this.$container = Craft.ImageUpload.$modalContainerDiv;
		this.setSettings(settings);
		this.containingModal = containingModal;
	},

	showArea: function()
	{
		var $target = this.$container.find('img');

		var cropperOptions = {
			aspectRatio: this.settings.aspectRatio,
			maxSize: [$target.width(), $target.height()],
			bgColor: 'none'
		};

		var initCropper = $.proxy(function (api)
		{
			this.api = api;

			var x1 = this.settings.initialRectangle.x1;
			var x2 = this.settings.initialRectangle.x2;
			var y1 = this.settings.initialRectangle.y1;
			var y2 = this.settings.initialRectangle.y2;

			if (this.settings.initialRectangle.mode == "auto")
			{
				var rectangleWidth = 0;
				var rectangleHeight = 0;

				if (this.settings.aspectRatio == "")
				{
					rectangleWidth = $target.width();
					rectangleHeight = $target.height();
				}
				else if (this.settings.aspectRatio > 1)
				{
					rectangleWidth = $target.width();
					rectangleHeight = rectangleWidth / this.settings.aspectRatio;
				}
				else if (this.settings.aspectRatio < 1)
				{
					rectangleHeight = $target.height();
					rectangleWidth = rectangleHeight * this.settings.aspectRatio;
				}
				else
				{
					rectangleHeight = rectangleWidth = Math.min($target.width(), $target.height());
				}

				x1 = Math.round(($target.width() - rectangleWidth) / 2);
				y1 = Math.round(($target.height() - rectangleHeight) / 2);
				x2 = x1 + rectangleWidth;
				y2 = y1 + rectangleHeight;

			}
			this.api.setSelect([x1, y1, x2, y2]);

			this.containingModal.areaSelect = this.api;
			this.containingModal.source = $target.attr('src').split('/').pop();
			this.containingModal.updateSizeAndPosition();

		}, this);

		$target.Jcrop(cropperOptions, function ()
		{
			initCropper(this);
		});
	}
});