text:
package com.github.megatronking.svg.applet.graphics;

import com.github.megatronking.svg.generator.utils.PathDataNode;

import org.dom4j.Attribute;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.awt.geom.Path2D;
import java.awt.geom.PathIterator;
import java.util.List;

/**
 * Used to represent one VectorDrawable's path element.
 */
class VdPath extends VdElement {

    private static final String PATH_ID = "android:name";
    private static final String PATH_DESCRIPTION = "android:pathData";
    private static final String PATH_FILL = "android:fillColor";
    private static final String PATH_FILL_OPACITY = "android:fillAlpha";
    private static final String PATH_FILL_TYPE = "android:fillType";
    private static final String PATH_STROKE = "android:strokeColor";
    private static final String PATH_STROKE_OPACTIY = "android:strokeAlpha";

    private static final String FILL_TYPE_EVEN_ODD = "evenOdd";

    private static final String PATH_STROKE_WIDTH = "android:strokeWidth";
    private static final String PATH_STROKE_LINECAP = "android:strokeLineCap";
    private static final String PATH_STROKE_LINEJOIN = "android:strokeLineJoin";
    private static final String PATH_STROKE_MITERLIMIT = "android:strokeMiterLimit";

    private static final String LINECAP_BUTT = "butt";
    private static final String LINECAP_ROUND = "round";
    private static final String LINECAP_SQUARE = "square";
    private static final String LINEJOIN_MITER = "miter";
    private static final String LINEJOIN_ROUND = "round";
    private static final String LINEJOIN_BEVEL = "bevel";

    private PathDataNode[] mNodeList = null;
    private int mStrokeColor = 0;
    private int mFillColor = 0;

    private float mStrokeWidth = 0;
    private int mStrokeLineCap = 0;
    private int mStrokeLineJoin = 0;
    private float mStrokeMiterlimit = 4;
    private float mStrokeAlpha = 1.0f;
    private float mFillAlpha = 1.0f;
    private int mFillType = PathIterator.WIND_NON_ZERO;

    private void toPath(Path2D path) {
        path.reset();
        if (mNodeList != null) {
            VdNodeRender.createPath(mNodeList, path);
        }
    }

    /**
     * @return color value in #AARRGGBB format.
     */
    private static int calculateColor(String value) {
        int len = value.length();
        int ret;
        int k = 0;
        switch (len) {
            case 7: // #RRGGBB
                ret = (int) Long.parseLong(value.substring(1), 16);
                ret |= 0xFF000000;
                break;
            case 9: // #AARRGGBB
                ret = (int) Long.parseLong(value.substring(1), 16);
                break;
            case 4: // #RGB
                ret = (int) Long.parseLong(value.substring(1), 16);

                k |= ((ret >> 8) & 0xF) * 0x110000;
                k |= ((ret >> 4) & 0xF) * 0x1100;
                k |= ((ret) & 0xF) * 0x11;
                ret = k | 0xFF000000;
                break;
            case 5: // #ARGB
                ret = (int) Long.parseLong(value.substring(1), 16);
                k |= ((ret >> 12) & 0xF) * 0x11000000;
                k |= ((ret >> 8) & 0xF) * 0x110000;
                k |= ((ret >> 4) & 0xF) * 0x1100;
                k |= ((ret) & 0xF) * 0x11;
                ret = k;
                break;
            default:
                return 0xFF000000;
        }
        return ret;
    }

    private void setNameValue(String name, String value) {
        if (PATH_DESCRIPTION.equals(name)) {
            mNodeList = PathDataNode.createNodesFromPathData(value);
        } else if (PATH_ID.equals(name)) {
            mName = value;
        } else if (PATH_FILL.equals(name)) {
            mFillColor = calculateColor(value);
        } else if (PATH_FILL_TYPE.equals(name)) {
            mFillType = parseFillType(value);
        } else if (PATH_STROKE.equals(name)) {
            mStrokeColor = calculateColor(value);
        } else if (PATH_FILL_OPACITY.equals(name)) {
            mFillAlpha = Float.parseFloat(value);
        } else if (PATH_STROKE_OPACTIY.equals(name)) {
            mStrokeAlpha = Float.parseFloat(value);
        } else if (PATH_STROKE_WIDTH.equals(name)) {
            mStrokeWidth = Float.parseFloat(value);
        } else if (PATH_STROKE_LINECAP.equals(name)) {
            if (LINECAP_BUTT.equals(value)) {
                mStrokeLineCap = 0;
            } else if (LINECAP_ROUND.equals(value)) {
                mStrokeLineCap = 1;
            } else if (LINECAP_SQUARE.equals(value)) {
                mStrokeLineCap = 2;
            }
        } else if (PATH_STROKE_LINEJOIN.equals(name)) {
            if (LINEJOIN_MITER.equals(value)) {
                mStrokeLineJoin = 0;
            } else if (LINEJOIN_ROUND.equals(value)) {
                mStrokeLineJoin = 1;
            } else if (LINEJOIN_BEVEL.equals(value)) {
                mStrokeLineJoin = 2;
            }
        } else if (PATH_STROKE_MITERLIMIT.equals(name)) {
            mStrokeMiterlimit = Float.parseFloat(value);
        }
    }

    private static int parseFillType(String value) {
        if (FILL_TYPE_EVEN_ODD.equalsIgnoreCase(value)) {
            return PathIterator.WIND_EVEN_ODD;
        }
        return PathIterator.WIND_NON_ZERO;
    }

    /**
     * Multiply the alpha value into the alpha channel color.
     */
    private static int applyAlpha(int color, float alpha) {
        int alphaBytes = (color >> 24) & 0xff;
        color &= 0x00FFFFFF;
        color |= ((int) (alphaBytes * alpha)) << 24;
        return color;
    }

    /**
     * Draw the current path
     */
    @Override
    public void draw(Graphics2D g, AffineTransform currentMatrix, float scaleX, float scaleY) {
        Path2D path2d = new Path2D.Double(mFillType);
        toPath(path2d);

        // SWing operate the matrix is using pre-concatenate by default.
        // Below is how this is handled in Android framework.
        // pathMatrix.set(groupStackedMatrix);
        // pathMatrix.postScale(scaleX, scaleY);
        g.setTransform(new AffineTransform());
        g.scale(scaleX, scaleY);
        g.transform(currentMatrix);

        // TODO: support clip path here.
        if (mFillColor != 0) {
            g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            Color fillColor = new Color(applyAlpha(mFillColor, mFillAlpha), true);
            g.setColor(fillColor);
            g.fill(path2d);
        }
        if (mStrokeColor != 0) {
            g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            BasicStroke stroke = new BasicStroke(mStrokeWidth, mStrokeLineCap, mStrokeLineJoin, mStrokeMiterlimit);
            g.setStroke(stroke);
            Color strokeColor = new Color(applyAlpha(mStrokeColor, mStrokeAlpha), true);
            g.setColor(strokeColor);
            g.draw(path2d);
        }
    }

    @Override
    public void parseAttributes(List<?> attributes) {
        int len = attributes.size();
        for (int i = 0; i < len; i++) {
            String name = ((Attribute)attributes.get(i)).getQualifiedName();
            String value = ((Attribute)attributes.get(i)).getValue();
            setNameValue(name, value);
        }
    }

    @Override
    public boolean isGroup() {
        return false;
    }

    @Override
    public String toString() {
        //noinspection ImplicitArrayToString
        return "Path:" +
                " Name: " + mName +
                " Node: " + mNodeList.toString() +
                " mFillColor: " + Integer.toHexString(mFillColor) +
                " mFillAlpha:" + mFillAlpha +
                " mFillType:" + mFillType +
                " mStrokeColor:" + Integer.toHexString(mStrokeColor) +
                " mStrokeWidth:" + mStrokeWidth +
                " mStrokeAlpha:" + mStrokeAlpha;
    }
}


text:
/**
 * This package contains the main API related to the triggers that initiate the validation process.
 */
package com.google.code.validationframework.api.trigger;

redpajama_set_name: RedPajamaGithub


text:
//  (C) Copyright John Maddock 2000.
//  Use, modification and distribution are subject to the
//  Boost Software License, Version 1.0. (See accompanying file
//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#include "test.hpp"
#include "check_integral_constant.hpp"
#ifdef TEST_STD
#  include <type_traits>
#else
#  include <boost/type_traits/is_lvalue_reference.hpp>
#endif

TT_TEST_BEGIN(is_lvalue_reference)

BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_lvalue_reference<int&>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_lvalue_reference<const int&>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_lvalue_reference<volatile int &>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_lvalue_reference<const volatile int &>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_lvalue_reference<r_type>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_lvalue_reference<cr_type>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_lvalue_reference<UDT&>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_lvalue_reference<const UDT&>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_lvalue_reference<volatile UDT&>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_lvalue_reference<const volatile UDT&>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_lvalue_reference<int (&)(int)>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_lvalue_reference<int (&)[2]>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_lvalue_reference<int [2]>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_lvalue_reference<const int [2]>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_lvalue_reference<volatile int [2]>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_lvalue_reference<const volatile int [2]>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_lvalue_reference<bool>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_lvalue_reference<void>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_lvalue_reference<test_abc1>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_lvalue_reference<foo0_t>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_lvalue_reference<incomplete_type>::value, false);
#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_lvalue_reference<int&&>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_lvalue_reference<UDT&&>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_lvalue_reference<const UDT&&>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_lvalue_reference<volatile UDT&&>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_lvalue_reference<const volatile UDT&&>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_lvalue_reference<int (&&)(int)>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_lvalue_reference<int (&&)[2]>::value, false);
#endif

TT_TEST_END


text:
```bash
$ git clone https://github.com/lampe/rockPaperScissors.git
$ cd rockPaperScissors
$ meteor
```

# Api calls

```bash
#rock
curl -H "Content-Type: application/json" -X POST -d '{"move":"rock"}' http://localhost:3000/api/move
#paper
curl -H "Content-Type: application/json" -X POST -d '{"move":"paper"}' http://localhost:3000/api/move
#scissors
curl -H "Content-Type: application/json" -X POST -d '{"move":"scissors"}' http://localhost:3000/api/move
```
# Testing
you have to download the latest ChromeDriver
https://sites.google.com/a/chromium.org/chromedriver/

```bash
# install gagarin
$ sudo npm -g i gagarin
# start Meteor
$ meteor
# in a second tab/terminal
$ cd <path to your ChromeDriver>
#run chromeDriver
$ ./chromedriver
#in a third tab/terminal run this command in the meteor project folder
$ gagarin -B -m -c
```

## License

MIT License. See [LICENSE](https://github.com/lampe/rockPaperScissors/blob/master/LICENSE) for
details.


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/container/v1/cluster_service.proto

package com.google.container.v1;

public interface NetworkPolicyConfigOrBuilder
    extends
    // @@protoc_insertion_point(interface_extends:google.container.v1.NetworkPolicyConfig)
    com.google.protobuf.MessageOrBuilder {

  /**
   *
   *
   *

   * Whether NetworkPolicy is enabled for this cluster.
   *

   *
   * bool disabled = 1;
   */
  boolean getDisabled();
}


text:
package org.jsimpledb.parse.expr;

import org.jsimpledb.parse.ParseSession;

/**
 * Extension of the {@link Value} interface for instances that are capable of assignment.
 */
public interface LValue extends Value {

    /**
     * Make assignment to this instance.
     *
     * @param session parse session
     * @param value new value for this instance
     * @throws IllegalArgumentException if {@code value} is null or otherwise invalid
     */
    void set(ParseSession session, Value value);
}


text:
import unittest

from django.test import TestCase
from django.db import models
from djcommon.fields import HashField

class ExampleModel(models.Model):
    name = models.CharField(max_length=100)
    description = models.CharField(max_length=255)
    hash = HashField(field_names='name,description')

class TestHashField(TestCase):

    def setUp(self):
        pass

    def test_string(self):
        instance = ExampleModel(name="Cafe", description="Lorem ipsum")
        hash_field = instance._meta.get_field_by_name('hash')[0]
        hash = hash_field.calculate_hash(instance)
        self.assertEqual(hash, 'e1500c515a62b8d6b846d074ad8625296e2fa6ef')

    def test_unicode(self):
        instance = ExampleModel(name=u"Café", description="Lorem ipsum")
        hash_field = instance._meta.get_field_by_name('hash')[0]
        hash = hash_field.calculate_hash(instance)
        self.assertEqual(hash, 'e17e90a9d2f5b1886390fd60e04888160472b919')

    def test_integer(self):
        instance = ExampleModel(name=1, description="Lorem ipsum")
        hash_field = instance._meta.get_field_by_name('hash')[0]
        hash = hash_field.calculate_hash(instance)
        self.assertEqual(hash, 'd0b5f95036dd47053e640b7de3b3f3bad4211b13')

if __name__ == '__main__':
    unittest.main()


text:
/* vim: set expandtab ts=4 sw=4: */
/*
 * You may redistribute this program and/or modify it under the terms of
 * the GNU General Public License as published by the Free Software Foundation,
 * either version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
#include "admin/angel/Hermes.h"
#include "benc/String.h"
#include "benc/Dict.h"
#include "benc/List.h"
#include "benc/Int.h"
#include "benc/serialization/standard/BencMessageWriter.h"
#include "benc/serialization/standard/BencMessageReader.h"
#include "crypto/random/Random.h"
#include "exception/Jmp.h"
#include "interface/tuntap/TUNMessageType.h"
#include "memory/Allocator.h"
#include "tunnel/IpTunnel.h"
#include "crypto/AddressCalc.h"
#include "util/Checksum.h"
#include "util/AddrTools.h"
#include "util/events/EventBase.h"
#include "util/Identity.h"
#include "util/events/Timeout.h"
#include "wire/Error.h"
#include "wire/Headers.h"
#include "wire/Ethernet.h"

#include <stddef.h>

struct IpTunnel_pvt
{
    struct IpTunnel pub;

    struct Allocator* allocator;
    struct Log* logger;

    uint32_t connectionCapacity;

    /** An always incrementing number which represents the connections. */
    uint32_t nextConnectionNumber;

    /** The name of the TUN interface so that ip addresses can be added. */
    String* ifName;

    /**
     * Every 10 seconds check for connections which the other end has
     * not provided ip addresses and send more requests.
     */
    struct Timeout* timeout;
    struct Random* rand;

    /** The angel connector for setting IP addresses. */
    struct Hermes* hermes;

    /** For verifying the integrity of the structure. */
    Identity
};

static struct IpTunnel_Connection* newConnection(bool isOutgoing, struct IpTunnel_pvt* context)
{
    if (context->pub.connectionList.count == context->connectionCapacity) {
        uint32_t newSize = (context->connectionCapacity + 4) * sizeof(struct IpTunnel_Connection);
        context->pub.connectionList.connections =
            Allocator_realloc(context->allocator, context->pub.connectionList.connections, newSize);
        context->connectionCapacity += 4;
    }
    struct IpTunnel_Connection* conn =
        &context->pub.connectionList.connections[context->pub.connectionList.count];

    // If it's an incoming connection, it must be lower on the list than any outgoing connections.
    if (!isOutgoing) {
        for (int i = (int)context->pub.connectionList.count - 1; i >= 0; i--) {
            if (!context->pub.connectionList.connections[i].isOutgoing
                && conn != &context->pub.connectionList.connections[i + 1])
            {
                Bits_memcpyConst(conn,
                                 &context->pub.connectionList.connections[i + 1],
                                 sizeof(struct IpTunnel_Connection));
                conn = &context->pub.connectionList.connections[i + 1];
            }
        }
    }

    context->pub.connectionList.count++;

    Bits_memset(conn, 0, sizeof(struct IpTunnel_Connection));
    conn->number = context->nextConnectionNumber++;
    conn->isOutgoing = isOutgoing;

    // if there are 2 billion calls, die.
    Assert_true(context->nextConnectionNumber < (UINT32_MAX >> 1));

    return conn;
}

static struct IpTunnel_Connection* connectionByPubKey(uint8_t pubKey[32],
                                                      struct IpTunnel_pvt* context)
{
    for (int i = 0; i < (int)context->pub.connectionList.count; i++) {
        if (!Bits_memcmp(pubKey, context->pub.connectionList.connections[i].header.nodeKey, 32)) {
            return &context->pub.connectionList.connections[i];
        }
    }
    return NULL;
}

/**
 * Allow another node to tunnel IPv4 and/or ICANN IPv6 through this node.
 *
 * @param publicKeyOfAuthorizedNode the key for the node which will be allowed to connect.
 * @param ip6Addr the IPv6 address which the node will be issued or NULL.
 * @param ip4Addr the IPv4 address which the node will be issued or NULL.
 * @param tunnel the IpTunnel.
 * @return an connection number which is usable with IpTunnel_remove().
 */
int IpTunnel_allowConnection(uint8_t publicKeyOfAuthorizedNode[32],
                             struct Sockaddr* ip6Addr,
                             struct Sockaddr* ip4Addr,
                             struct IpTunnel* tunnel)
{
    struct IpTunnel_pvt* context = Identity_check((struct IpTunnel_pvt*)tunnel);

    uint8_t* ip6Address = NULL;
    uint8_t* ip4Address = NULL;
    if (ip6Addr) {
        Sockaddr_getAddress(ip6Addr, &ip6Address);
    }
    if (ip4Addr) {
        Sockaddr_getAddress(ip4Addr, &ip4Address);
    }

    struct IpTunnel_Connection* conn = newConnection(false, context);
    Bits_memcpyConst(conn->header.nodeKey, publicKeyOfAuthorizedNode, 32);
    AddressCalc_addressForPublicKey(conn->header.nodeIp6Addr, publicKeyOfAuthorizedNode);
    if (ip4Address) {
        Bits_memcpyConst(conn->connectionIp4, ip4Address, 4);
    }
    if (ip6Address) {
        Bits_memcpyConst(conn->connectionIp6, ip6Address, 16);
    }
    return conn->number;
}

static uint8_t sendToNode(struct Message* message,
                          struct IpTunnel_Connection* connection,
                          struct IpTunnel_pvt* context)
{
    Message_push(message, &connection->header, IpTunnel_PacketInfoHeader_SIZE, NULL);
    if (context->pub.nodeInterface.receiveMessage) {
        return context->pub.nodeInterface.receiveMessage(message, &context->pub.nodeInterface);
    }
    Log_info(context->logger, "Message undeliverable because IpTunnel is not registered");
    return Error_UNDELIVERABLE;
}

static uint8_t sendControlMessage(Dict* dict,
                                  struct IpTunnel_Connection* connection,
                                  struct Allocator* requestAlloc,
                                  struct IpTunnel_pvt* context)
{
    struct Message* msg = Message_new(0, 1024, requestAlloc);
    BencMessageWriter_write(dict, msg, NULL);

    int length = msg->length;

    // do UDP header.
    Message_shift(msg, Headers_UDPHeader_SIZE, NULL);
    struct Headers_UDPHeader* uh = (struct Headers_UDPHeader*) msg->bytes;
    uh->srcPort_be = 0;
    uh->destPort_be = 0;
    uh->length_be = Endian_hostToBigEndian16(length);
    uh->checksum_be = 0;

    uint16_t payloadLength = msg->length;

    Message_shift(msg, Headers_IP6Header_SIZE, NULL);
    struct Headers_IP6Header* header = (struct Headers_IP6Header*) msg->bytes;
    header->versionClassAndFlowLabel = 0;
    header->flowLabelLow_be = 0;
    header->nextHeader = 17;
    header->hopLimit = 0;
    header->payloadLength_be = Endian_hostToBigEndian16(payloadLength);
    Headers_setIpVersion(header);

    // zero the source and dest addresses.
    Bits_memset(header->sourceAddr, 0, 32);

    uh->checksum_be = Checksum_udpIp6(header->sourceAddr,
                                      (uint8_t*) uh,
                                      msg->length - Headers_IP6Header_SIZE);

    return sendToNode(msg, connection, context);
}

static uint8_t requestAddresses(struct IpTunnel_Connection* conn,
                                struct IpTunnel_pvt* context)
{
    #ifdef Log_DEBUG
        uint8_t addr[40];
        AddrTools_printIp(addr, conn->header.nodeIp6Addr);
        Log_debug(context->logger, "Requesting addresses from [%s] for connection [%d]",
                  addr, conn->number);
    #endif

    int number = conn->number;
    Dict d = Dict_CONST(
        String_CONST("q"), String_OBJ(String_CONST("IpTunnel_getAddresses")), Dict_CONST(
        String_CONST("txid"), String_OBJ((&(String){ .len = 4, .bytes = (char*)&number })),
        NULL
    ));
    struct Allocator* msgAlloc = Allocator_child(context->allocator);
    uint8_t ret = sendControlMessage(&d, conn, msgAlloc, context);
    Allocator_free(msgAlloc);
    return ret;
}

/**
 * Connect to another node and get IPv4 and/or IPv6 addresses from it.
 *
 * @param publicKeyOfNodeToConnectTo the key for the node to connect to.
 * @param tunnel the IpTunnel.
 * @return an connection number which is usable with IpTunnel_remove().
 */
int IpTunnel_connectTo(uint8_t publicKeyOfNodeToConnectTo[32], struct IpTunnel* tunnel)
{
    struct IpTunnel_pvt* context = Identity_check((struct IpTunnel_pvt*)tunnel);

    struct IpTunnel_Connection* conn = newConnection(true, context);
    Bits_memcpyConst(conn->header.nodeKey, publicKeyOfNodeToConnectTo, 32);
    AddressCalc_addressForPublicKey(conn->header.nodeIp6Addr, publicKeyOfNodeToConnectTo);

    #ifdef Log_DEBUG
        uint8_t addr[40];
        AddrTools_printIp(addr, conn->header.nodeIp6Addr);
        Log_debug(context->logger, "Trying to connect to [%s]", addr);
    #endif

    requestAddresses(conn, context);

    return conn->number;
}

/**
 * Disconnect from a node or remove authorization to connect.
 *
 * @param connection the connection to remove.
 * @param tunnel the IpTunnel.
 */
int IpTunnel_removeConnection(int connectionNumber, struct IpTunnel* tunnel)
{
    //struct IpTunnel_pvt* context = Identity_check((struct IpTunnel_pvt*)tunnel);

    return 0;
}

static uint8_t isControlMessageInvalid(struct Message* message, struct IpTunnel_pvt* context)
{
    struct Headers_IP6Header* header = (struct Headers_IP6Header*) message->bytes;
    uint16_t length = Endian_bigEndianToHost16(header->payloadLength_be);
    if (header->nextHeader != 17 || message->length < length + Headers_IP6Header_SIZE) {
        Log_warn(context->logger, "Invalid IPv6 packet (not UDP or length field too big)");
        return Error_INVALID;
    }

    Message_shift(message, -Headers_IP6Header_SIZE, NULL);
    struct Headers_UDPHeader* udp = (struct Headers_UDPHeader*) message->bytes;

    if (Checksum_udpIp6(header->sourceAddr, message->bytes, length)) {
        Log_warn(context->logger, "Checksum mismatch");
        return Error_INVALID;
    }

    length -= Headers_UDPHeader_SIZE;
    if (Endian_bigEndianToHost16(udp->length_be) != length
        || udp->srcPort_be != 0
        || udp->destPort_be != 0)
    {
        Log_warn(context->logger, "Invalid UDP packet (length mismatch or wrong ports)");
        return Error_INVALID;
    }

    Message_shift(message, -Headers_UDPHeader_SIZE, NULL);

    message->length = length;
    return 0;
}

static uint8_t requestForAddresses(Dict* request,
                                   struct IpTunnel_Connection* conn,
                                   struct Allocator* requestAlloc,
                                   struct IpTunnel_pvt* context)
{
    #ifdef Log_DEBUG
        uint8_t addr[40];
        AddrTools_printIp(addr, conn->header.nodeIp6Addr);
        Log_debug(context->logger, "Got request for addresses from [%s]", addr);
    #endif

    if (conn->isOutgoing) {
        Log_warn(context->logger, "got request for addresses from outgoing connection");
        return Error_INVALID;
    }
    Dict* addresses = Dict_new(requestAlloc);
    bool noAddresses = true;
    if (!Bits_isZero(conn->connectionIp6, 16)) {
        Dict_putString(addresses,
                       String_CONST("ip6"),
                       String_newBinary((char*)conn->connectionIp6, 16, requestAlloc),
                       requestAlloc);
        noAddresses = false;
    }
    if (!Bits_isZero(conn->connectionIp4, 4)) {
        Dict_putString(addresses,
                       String_CONST("ip4"),
                       String_newBinary((char*)conn->connectionIp4, 4, requestAlloc),
                       requestAlloc);
        noAddresses = false;
    }
    if (noAddresses) {
        Log_warn(context->logger, "no addresses to provide");
        return 0;
    }

    Dict* msg = Dict_new(requestAlloc);
    Dict_putDict(msg, String_CONST("addresses"), addresses, requestAlloc);

    String* txid = Dict_getString(request, String_CONST("txid"));
    if (txid) {
        Dict_putString(msg, String_CONST("txid"), txid, requestAlloc);
    }

    return sendControlMessage(msg, conn, requestAlloc, context);
}

static void addAddressCallback(Dict* responseMessage, void* vcontext)
{
    struct IpTunnel_pvt* ctx = Identity_check((struct IpTunnel_pvt*) vcontext);
    char* err = "invalid response";
    String* error = Dict_getString(responseMessage, String_CONST("error"));
    if (error) {
        err = error->bytes;
    }
    if (!error || !String_equals(error, String_CONST("none"))) {
        Log_error(ctx->logger, "Error setting ip address on TUN [%s]", err);

        #ifndef Log_ERROR
            // this whole function does essentially nothing but log an error so unused vars.
            err = err;
            ctx = ctx;
        #endif
    }
}

static void addAddress(char* printedAddr, struct IpTunnel_pvt* ctx)
{
#ifdef Darwin
    int prefixLen = 3;
#else
    int prefixLen = 0;
#endif
// Apple doesn't handle prefix length of 0 properly. 3 covers all IPv6 unicast space.
    if (!ctx->ifName) {
        Log_error(ctx->logger, "Failed to set IP address because TUN interface is not setup");
        return;
    }
    struct Jmp j;
    Jmp_try(j) {
        Dict args = Dict_CONST(
            String_CONST("address"), String_OBJ(String_CONST(printedAddr)), Dict_CONST(
            String_CONST("interfaceName"), String_OBJ(ctx->ifName), Dict_CONST(
            String_CONST("prefixLen"), Int_OBJ(prefixLen), NULL
        )));
        Dict msg = Dict_CONST(
            String_CONST("args"), Dict_OBJ(&args), Dict_CONST(
            String_CONST("q"), String_OBJ(String_CONST("Angel_addIp")), NULL
        ));
        Hermes_callAngel(&msg, addAddressCallback, ctx, ctx->allocator, &j.handler, ctx->hermes);
    } Jmp_catch {
        Log_error(ctx->logger, "Error setting ip address on TUN [%s]", j.message);
    }
}

static int incomingAddresses(Dict* d,
                             struct IpTunnel_Connection* conn,
                             struct Allocator* alloc,
                             struct IpTunnel_pvt* context)
{
    if (!conn->isOutgoing) {
        Log_warn(context->logger, "got offer of addresses from incoming connection");
        return Error_INVALID;
    }

    String* txid = Dict_getString(d, String_CONST("txid"));
    if (!txid || txid->len != 4) {
        Log_info(context->logger, "missing or wrong length txid");
        return Error_INVALID;
    }

    int number;
    Bits_memcpyConst(&number, txid->bytes, 4);
    if (number < 0 || number >= (int)context->nextConnectionNumber) {
        Log_info(context->logger, "txid out of range");
        return Error_INVALID;
    }

    if (number != conn->number) {
        for (int i = 0; i < (int)context->pub.connectionList.count; i++) {
            if (context->pub.connectionList.connections[i].number == number) {
                if (Bits_memcmp(conn->header.nodeKey,
                                context->pub.connectionList.connections[i].header.nodeKey,
                                32))
                {
                    Log_info(context->logger, "txid doesn't match origin");
                    return Error_INVALID;
                } else {
                    conn = &context->pub.connectionList.connections[i];
                }
            }
        }
    }

    Dict* addresses = Dict_getDict(d, String_CONST("addresses"));

    String* ip4 = Dict_getString(addresses, String_CONST("ip4"));
    if (ip4 && ip4->len == 4) {
        Bits_memcpyConst(conn->connectionIp4, ip4->bytes, 4);

        struct Sockaddr* sa = Sockaddr_clone(Sockaddr_LOOPBACK, alloc);
        uint8_t* addrBytes = NULL;
        Sockaddr_getAddress(sa, &addrBytes);
        Bits_memcpy(addrBytes, ip4->bytes, 4);
        char* printedAddr = Sockaddr_print(sa, alloc);

        Log_info(context->logger, "Got issued address [%s] for connection [%d]",
                 printedAddr, conn->number);

        addAddress(printedAddr, context);
    }

    String* ip6 = Dict_getString(addresses, String_CONST("ip6"));
    if (ip6 && ip6->len == 16) {
        Bits_memcpyConst(conn->connectionIp6, ip6->bytes, 16);

        struct Sockaddr* sa = Sockaddr_clone(Sockaddr_LOOPBACK6, alloc);
        uint8_t* addrBytes = NULL;
        Sockaddr_getAddress(sa, &addrBytes);
        Bits_memcpy(addrBytes, ip6->bytes, 16);
        char* printedAddr = Sockaddr_print(sa, alloc);

        Log_info(context->logger, "Got issued address [%s] for connection [%d]",
                 printedAddr, conn->number);

        addAddress(printedAddr, context);
    }
    return 0;
}

static uint8_t incomingControlMessage(struct Message* message,
                                      struct IpTunnel_Connection* conn,
                                      struct IpTunnel_pvt* context)
{
    #ifdef Log_DEBUG
        uint8_t addr[40];
        AddrTools_printIp(addr, conn->header.nodeIp6Addr);
        Log_debug(context->logger, "Got incoming message from [%s]", addr);
    #endif

    // This aligns the message on the content.
    if (isControlMessageInvalid(message, context)) {
        return Error_INVALID;
    }

    #ifdef Log_DEBUG
        uint8_t lastChar = message->bytes[message->length - 1];
        message->bytes[message->length - 1] = '\0';
        Log_debug(context->logger, "Message content [%s%c]", message->bytes, lastChar);
        message->bytes[message->length - 1] = lastChar;
    #endif

    struct Allocator* alloc = Allocator_child(message->alloc);

    Dict* d = NULL;
    char* err = BencMessageReader_readNoExcept(message, alloc, &d);
    if (err) {
        Log_info(context->logger, "Failed to parse message [%s]", err);
        return Error_INVALID;
    }

    if (Dict_getDict(d, String_CONST("addresses"))) {
        return incomingAddresses(d, conn, alloc, context);
    }
    if (String_equals(String_CONST("IpTunnel_getAddresses"),
                      Dict_getString(d, String_CONST("q"))))
    {
        return requestForAddresses(d, conn, alloc, context);
    }
    Log_warn(context->logger, "Message which is unhandled");
    return Error_INVALID;
}

/**
 * If there are multiple connections to the same server,
 * the ip address on the packet might belong to the wrong one.
 * In that case we get the right connection.
 * If the other party has sent a packet from an address which is not
 * valid, this will return NULL and their packet can be dropped.
 *
 * @param conn the connection which matches the other node's key.
 * @param sourceAndDestIp6 the source and destination IPv6 addresses,
 *                         must be NULL if sourceAndDestIp4 is specified.
 * @param sourceAndDestIp4 the source and destination IPv4 addresses.
 *                         must be NULL if sourceAndDestIp6 is specified.
 * @param context
 * @return the real connection or null if the packet is invalid.
 */
static struct IpTunnel_Connection* getConnection(struct IpTunnel_Connection* conn,
                                                 uint8_t sourceAndDestIp6[32],
                                                 uint8_t sourceAndDestIp4[8],
                                                 bool isFromTun,
                                                 struct IpTunnel_pvt* context)
{
    uint8_t* source = (sourceAndDestIp6) ? sourceAndDestIp6 : sourceAndDestIp4;
    uint32_t length = (sourceAndDestIp6) ? 16 : 4;
    uint8_t* destination = source + length;

    if (sourceAndDestIp6) {
        // never allowed
        if (source[0] == 0xfc || destination[0] == 0xfc) {
            return NULL;
        }
    }

    struct IpTunnel_Connection* lastConnection =
        &context->pub.connectionList.connections[context->pub.connectionList.count];

    do {
        // If this is an incoming message from the w0rld, and we're the client, we want
        // to make sure it's addressed to us (destination), if we're the server we want to make
        // sure our clients are using the addresses we gave them (source).
        //
        // If this is an outgoing message from the TUN, we just want to find a sutable server to
        // handle it. The behavior of this function relies on the fact that all incoming
        // connections are first on the list.
        //
        uint8_t* compareAddr = (isFromTun)
            ? ((conn->isOutgoing) ? source : destination)
            : ((conn->isOutgoing) ? destination : source);

        uint8_t* connectionAddr = (sourceAndDestIp6) ? conn->connectionIp6 : conn->connectionIp4;
        if (!Bits_memcmp(compareAddr, connectionAddr, length)) {
            return conn;
        }
        conn++;
    } while (conn <= lastConnection);

    return NULL;
}

static uint8_t incomingFromTun(struct Message* message, struct Interface* tunIf)
{
    struct IpTunnel_pvt* context = Identity_check((struct IpTunnel_pvt*)tunIf);

    if (message->length < 20) {
        Log_debug(context->logger, "Dropping runt.");
    }

    struct IpTunnel_Connection* conn = NULL;
    if (!context->pub.connectionList.connections) {
        // No connections authorized, fall through to "unrecognized address"
    } else if (message->length > 40 && Headers_getIpVersion(message->bytes) == 6) {
        struct Headers_IP6Header* header = (struct Headers_IP6Header*) message->bytes;
        conn = getConnection(context->pub.connectionList.connections,
                             header->sourceAddr,
                             NULL,
                             true,
                             context);
    } else if (message->length > 20 && Headers_getIpVersion(message->bytes) == 4) {
        struct Headers_IP4Header* header = (struct Headers_IP4Header*) message->bytes;
        conn = getConnection(context->pub.connectionList.connections,
                             NULL,
                             header->sourceAddr,
                             true,
                             context);
    } else {
        Log_info(context->logger, "Message of unknown type from TUN");
        return Error_INVALID;
    }

    if (!conn) {
        Log_info(context->logger, "Message with unrecognized address from TUN");
        return Error_INVALID;
    }

    return sendToNode(message, conn, context);
}

static uint8_t ip6FromNode(struct Message* message,
                           struct IpTunnel_Connection* conn,
                           struct IpTunnel_pvt* context)
{
    struct Headers_IP6Header* header = (struct Headers_IP6Header*) message->bytes;
    if (Bits_isZero(header->sourceAddr, 16) || Bits_isZero(header->destinationAddr, 16)) {
        if (Bits_isZero(header->sourceAddr, 32)) {
            return incomingControlMessage(message, conn, context);
        }
        Log_debug(context->logger, "Got message with zero address");
        return Error_INVALID;
    }
    if (!getConnection(conn, header->sourceAddr, NULL, false, context)) {
        Log_debug(context->logger, "Got message with wrong address for connection");
        return Error_INVALID;
    }

    TUNMessageType_push(message, Ethernet_TYPE_IP6, NULL);

    struct Interface* tunIf = &context->pub.tunInterface;
    if (tunIf->receiveMessage) {
        tunIf->receiveMessage(message, tunIf);
    }
    return 0;
}

static uint8_t ip4FromNode(struct Message* message,
                           struct IpTunnel_Connection* conn,
                           struct IpTunnel_pvt* context)
{
    struct Headers_IP4Header* header = (struct Headers_IP4Header*) message->bytes;
    if (Bits_isZero(header->sourceAddr, 4) || Bits_isZero(header->destAddr, 4)) {
        Log_debug(context->logger, "Got message with zero address");
        return Error_INVALID;
    }
    if (!getConnection(conn, NULL, header->sourceAddr, false, context)) {
        Log_debug(context->logger, "Got message with wrong address for connection");
        return Error_INVALID;
    }

    TUNMessageType_push(message, Ethernet_TYPE_IP4, NULL);

    struct Interface* tunIf = &context->pub.tunInterface;
    if (tunIf->receiveMessage) {
        return tunIf->receiveMessage(message, tunIf);
    }
    return 0;
}

static uint8_t incomingFromNode(struct Message* message, struct Interface* nodeIf)
{
    struct IpTunnel_pvt* context =
        (struct IpTunnel_pvt*)(((char*)nodeIf) - offsetof(struct IpTunnel, nodeInterface));
    Identity_check(context);

    //Log_debug(context->logger, "Got incoming message");

    Assert_true(message->length >= IpTunnel_PacketInfoHeader_SIZE);
    struct IpTunnel_PacketInfoHeader* header = (struct IpTunnel_PacketInfoHeader*) message->bytes;
    struct IpTunnel_Connection* conn = connectionByPubKey(header->nodeKey, context);
    if (!conn) {
        #ifdef Log_DEBUG
            uint8_t addr[40];
            AddrTools_printIp(addr, header->nodeIp6Addr);
            Log_debug(context->logger, "Got message from unrecognized node [%s]", addr);
        #endif
        return 0;
    }

    Message_shift(message, -IpTunnel_PacketInfoHeader_SIZE, NULL);

    if (message->length > 40 && Headers_getIpVersion(message->bytes) == 6) {
        return ip6FromNode(message, conn, context);
    }
    if (message->length > 20 && Headers_getIpVersion(message->bytes) == 4) {
        return ip4FromNode(message, conn, context);
    }

    #ifdef Log_DEBUG
        uint8_t addr[40];
        AddrTools_printIp(addr, header->nodeIp6Addr);
        Log_debug(context->logger,
                  "Got message of unknown type, length: [%d], IP version [%d] from [%s]",
                  message->length,
                  (message->length > 1) ? Headers_getIpVersion(message->bytes) : 0,
                  addr);
    #endif
    return 0;
}

static void timeout(void* vcontext)
{
    struct IpTunnel_pvt* context = vcontext;
    if (!context->pub.connectionList.count) {
        return;
    }
    Log_debug(context->logger, "Checking for connections to poll. Total connections [%u]",
                                context->pub.connectionList.count);
    uint32_t beginning = Random_uint32(context->rand) % context->pub.connectionList.count;
    uint32_t i = beginning;
    do {
        Assert_true(i < context->pub.connectionList.count);
        struct IpTunnel_Connection* conn = &context->pub.connectionList.connections[i];
        if (conn->isOutgoing
            && Bits_isZero(conn->connectionIp6, 16)
            && Bits_isZero(conn->connectionIp4, 4))
        {
            requestAddresses(conn, context);
            break;
        }
        i = (i + 1) % context->pub.connectionList.count;
    } while (i != beginning);
}

void IpTunnel_setTunName(char* interfaceName, struct IpTunnel* ipTun)
{
    struct IpTunnel_pvt* ctx = Identity_check((struct IpTunnel_pvt*) ipTun);
    ctx->ifName = String_new(interfaceName, ctx->allocator);
}

struct IpTunnel* IpTunnel_new(struct Log* logger,
                              struct EventBase* eventBase,
                              struct Allocator* alloc,
                              struct Random* rand,
                              struct Hermes* hermes)
{
    struct IpTunnel_pvt* context = Allocator_clone(alloc, (&(struct IpTunnel_pvt) {
        .pub = {
            .tunInterface = { .sendMessage = incomingFromTun },
            .nodeInterface = { .sendMessage = incomingFromNode }
        },
        .allocator = alloc,
        .logger = logger,
        .rand = rand,
        .hermes = hermes
    }));
    context->timeout = Timeout_setInterval(timeout, context, 10000, eventBase, alloc);
    Identity_set(context);

    return &context->pub;
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>/home/wilbert/github/backgrid-advanced-filter/src/filter-dropdown.js</title>
    <link rel="stylesheet" href="http://yui.yahooapis.com/3.9.1/build/cssgrids/cssgrids-min.css">
    <link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css">
    <link rel="stylesheet" href="../assets/css/main.css" id="site_styles">
    <link rel="shortcut icon" type="image/png" href="../assets/favicon.png">

            API Docs for:

APIs

Classes

Modules

            <input type="search" id="api-filter" placeholder="Type to filter APIs">

AdvancedFilter.AttributeFilterCollection

AdvancedFilter.AttributeFilterModel

AdvancedFilter.Editor

AdvancedFilter.FilterCollection

AdvancedFilter.FilterModel

AdvancedFilter.Main

AdvancedFilter.Saver

AdvancedFilter.Selector

AdvancedFilter.Subcomponents.FilterDropdown

AdvancedFilter.Subcomponents.FilterDropdownContainer

AdvancedFilter.Subcomponents.FilterDropdownItemview

AdvancedFilter.SubComponents.LabelView

ColumnFilterView

FilterStateModel

FilterView

MatcherContainerView

MatcherSelectorView

MongoParser

NewFilterButtonView

RemoveFilterButtonView

AdvancedFilter

AdvancedFilter.Editor

AdvancedFilter.FilterCollection

AdvancedFilter.FilterOptions

AdvancedFilter.FilterParsers

AdvancedFilter.FilterStateModel

AdvancedFilter.Saver

AdvancedFilter.Selector

AdvancedFilter.Subcomponents

        Show:

            <input type="checkbox" id="api-show-inherited" checked>
            Inherited

            <input type="checkbox" id="api-show-protected">
            Protected

            <input type="checkbox" id="api-show-private">
            Private

            <input type="checkbox" id="api-show-deprecated">
            Deprecated

File: /home/wilbert/github/backgrid-advanced-filter/src/filter-dropdown.js

"use strict";
/**
 * Dropdown subcomponent
 *
 * @module AdvancedFilter.Subcomponents
 */

// Dependencies
var _ = require("underscore");
var Backbone = require("backbone");
var Backgrid = require("backgrid");

/**
 * A dropdown item view
 *
 * @class AdvancedFilter.Subcomponents.FilterDropdownItemview
 * @extends Backbone.View
 */
Backgrid.Extension.AdvancedFilter.SubComponents.FilterDropdownItemview = Backbone.View.extend({
  className: "advancedfilter-dropdown-item",
  template: _.template("<span class='indicator'></span><span class='filter-name'><%= name %></span>"),
  tagName: "li",
  events: {
    "click": "setActiveFilter"
  },

  /**
   * @method initialize
   * @param {object} opts
   * @param {Backgrid.Extension.ColumnManager} opts.columnManager ColumnManager instance.
   * @param {Backgrid.Column} opts.column A backgrid column.
   */
  initialize: function (opts) {
    var self = this;

    self.filterStateModel = opts.parentView.filterStateModel;
    self.filter = opts.filter;

    _.bindAll(self, "render", "setActiveFilter");
    self.listenTo(self.filter, "change:name", self.render, self);
  },

  /**
   * Activates current filer
   *
   * @method setActiveFilter
   * @param {object} e
   */
  setActiveFilter: function (e) {
    var self = this;
    if (e) {
      self.stopPropagation(e);
    }

    // Get current filter
    var currentFilter = self.filterStateModel.getActiveFilter();
    if (currentFilter !== self.filter) {
      self.filterStateModel.setActiveFilter(self.filter);
      self.filterStateModel.trigger("filter:loaded");
    }
  },

  /**
   * @method render
   * @return {DropDownItemView}
   */
  render: function () {
    var self = this;

    self.$el.empty();

    self.$el.append(self.template({
      name: self.filter.get("name")
    }));

    if (self.filterStateModel.get("activeFilterId") === self.filter.cid) {
      self.$el.addClass("active");
    }
    else {
      self.$el.removeClass("active");
    }

    return self;
  },

  /**
   * Convenience function to stop event propagation.
   *
   * @method stopPropagation
   * @param {object} e
   * @private
   */
  stopPropagation: function (e) {
    e.stopPropagation();
    e.stopImmediatePropagation();
    e.preventDefault();
  }
});

/**
 * Filter dropdown view container.
 *
 * @class AdvancedFilter.Subcomponents.FilterDropdownContainer
 * @extends Backbone.view
 */
Backgrid.Extension.AdvancedFilter.SubComponents.FilterDropdownContainer = Backbone.View.extend({
  className: "filter-dropdown-container",
  defaults: {
    DropdownItemView: Backgrid.Extension.AdvancedFilter.SubComponents.FilterDropdownItemview
  },

  initialize: function (options) {
    var self = this;
    self.options = _.extend({}, self.defaults, options || {});

    // Input argument checking
    self.parentView = self.options.parentView;

    // Bind events
    self.listenTo(self.parentView.filterStateModel.get("filterCollection"), "add remove", self.render);
    self.listenTo(self.parentView.filterStateModel, "change:activeFilterId", self.render);
  },

  /**
   * @method render
   * @return {DropDownView}
   */
  render: function () {
    var self = this;
    self.$el.empty();

    // List all filters
    self.parentView.filterStateModel.get("filterCollection").each(function (filter) {
      self.$el.append(new self.options.DropdownItemView({
        filter: filter,
        parentView: self.parentView
      }).render().$el);
    });

    return self;
  },

  /**
   * Opens the dropdown.
   *
   * @method open
   */
  open: function () {
    var self = this;

    self.$el.addClass("open");

    // Get button
    var $button = self.parentView.$dropdownButton;

    // Align
    var align;
    if (self.options.align === "auto") {
      // Determine what alignment fits
      var viewPortWidth = document.body.clientWidth || document.body.clientWidth;
      align = (($button.offset().left + self.$el.outerWidth()) > viewPortWidth) ? "left" : "right";
    }
    else {
      align = (self.options.align === "left" || self.options.align === "right") ?
        (self.options.align === "right" ? "right" : "left") : "right";
    }

    var offset;
    if (align === "left") {
      // Align right by default
      offset = $button.offset().left + $button.outerWidth() - self.$el.outerWidth();
      self.$el.css("left", offset + "px");
    }
    else {
      offset = $button.offset().left;
      self.$el.css("left", offset + "px");
    }

    // Height position
    var offsetHeight = $button.offset().top + $button.outerHeight();
    self.$el.css("top", offsetHeight + "px");
  },

  /**
   * Closes the dropdown.
   *
   * @method close
   */
  close: function () {
    this.$el.removeClass("open");
  }
});

/**
 * @class AdvancedFilter.Subcomponents.FilterDropdown
 * @extends Backbone.View
 */
Backgrid.Extension.AdvancedFilter.SubComponents.FilterDropdown = Backbone.View.extend({
  tagName: "div",
  defaultEvents: {
    "click": "stopPropagation"
  },
  defaults: {
    width: null,
    closeOnEsc: true,
    closeOnClick: true,
    openOnInit: false,

    // Button
    buttonTemplate: _.template("<button class='dropdown-button <%-buttonClass%>'><%=buttonText%></button>"),
    buttonClass: "",
    buttonText: "Filter &#9660;",

    // Container
    DropdownView: Backgrid.Extension.AdvancedFilter.SubComponents.FilterDropdownContainer,
    dropdownAlign: "auto"
  },

  /**
   * @method initialize
   * @param {Object} opts
   * @param {Backgrid.Extension.AdvancedFilter.FilterStateModel} opts.filterStateModel
   */
  initialize: function (opts) {
    var self = this;
    self.options = _.extend({}, self.defaults, opts || {});
    self.events = _.extend({}, self.defaultEvents, self.events || {});

    // Option checking
    if (!self.options.filterStateModel ||
      !self.options.filterStateModel instanceof Backbone.Model) {
      throw new Error("No (valid) filter state model provided");
    }
    self.filterStateModel = self.options.filterStateModel;

    // Bind scope to events
    _.bindAll(self, "deferClose", "stopDeferClose", "closeOnEsc", "toggle", "render", "open", "close");

    // UI events
    document.body.addEventListener("click", self.deferClose, true);
    if (self.options.closeOnEsc) {
      document.body.addEventListener("keyup", self.closeOnEsc, false);
    }
    self.$el.on("click", self.stopDeferClose);

    // Create elements
    self.setup();

    // Listen for dropdown view events indicating to open and/or close
    self.listenTo(self.filterStateModel.get("filterCollection"), "add remove", self.checkDisabled);
  },

  /**
   * @method delayStart
   * @private
   */
  delayStart: function () {
    clearTimeout(this.closeTimeout);
    this.delayTimeout = setTimeout(this.open, this.options.delay);
  },

  /**
   * @method delayEnd
   * @private
   */
  delayEnd: function () {
    clearTimeout(this.delayTimeout);
    this.closeTimeout = setTimeout(this.close, 300);
  },

  /**
   * @method setup
   * @private
   */
  setup: function () {
    var self = this;

    // Override element width
    if (self.options.width) {
      self.$el.width(self.options.width + "px");
    }

    // Create button element
    self.$dropdownButton = Backbone.$(self.options.buttonTemplate({
      buttonClass: self.options.buttonClass,
      buttonText: self.options.buttonText
    })).click(self.toggle);

    // Create dropdown container
    self.dropdownContainerView = new self.options.DropdownView({
      filterStateModel: self.filterStateModel,
      align: self.options.dropdownAlign,
      parentView: self
    }).render();

    // Render inner view
    document.body.appendChild(self.dropdownContainerView.el);
  },

  /**
   * @method setup
   */
  render: function () {
    var self = this;
    self.$el.empty();

    // Render button
    self.$el.html(self.$dropdownButton);

    // Verify disabled mode
    self.checkDisabled();

    return self;
  },

  /**
   * @method checkDisabled
   */
  checkDisabled: function() {
    var self = this;
    if (self.filterStateModel.get("filterCollection").length > 0) {
      self.$dropdownButton.removeAttr("disabled");
    }
    else {
      self.$dropdownButton.attr("disabled", "disabled");
    }
  },

  /**
   * Convenience function to stop event propagation
   *
   * @method stopPropagation
   * @param {object} e
   * @private
   */
  stopPropagation: function (e) {
    e.stopPropagation();
    e.stopImmediatePropagation();
    e.preventDefault();
  },

  /**
   * Toggle the dropdown visibility
   *
   * @method toggle
   * @param {object} [e]
   */
  toggle: function (e) {
    var self = this;
    if (self.isOpen !== true) {
      self.open(e);
    }
    else {
      self.close(e);
    }
  },

  /**
   * Open the dropdown
   *
   * @method open
   * @param {object} [e]
   */
  open: function (e) {
    var self = this;

    clearTimeout(self.closeTimeout);
    clearTimeout(self.deferCloseTimeout);

    if (e) {
      if (e.stopPropagation) {
        e.stopPropagation();
      }
      if (e.preventDefault) {
        e.preventDefault();
      }
      e.cancelBubble = true;
    }

    // Don't do anything if already open
    if (self.isOpen) {
      return;
    }

    self.isOpen = true;
    self.$el.addClass("open");

    // Notify child view
    self.dropdownContainerView.open();
  },

  /**
   * Close the dropdown
   *
   * @method close
   * @param {object} [e]
   */
  close: function (e) {
    var self = this;

    // Don't do anything if already closed
    if (!self.isOpen) {
      return;
    }

    self.isOpen = false;
    self.$el.removeClass("open");

    // Notify child view
    self.dropdownContainerView.close();
  },

  /**
   * Close the dropdown on esc
   *
   * @method closeOnEsc
   * @param {object} e
   * @private
   */
  closeOnEsc: function (e) {
    if (e.which === 27) {
      this.deferClose();
    }
  },

  /**
   * @method deferClose
   * @private
   */
  deferClose: function () {
    this.deferCloseTimeout = setTimeout(this.close, 0);
  },

  /**
   * @method stopDeferClose
   * @private
   */
  stopDeferClose: function (e) {
    clearTimeout(this.deferCloseTimeout);
  },

  /**
   * Clean up this control
   *
   * @method remove
   * @chainable
   */
  remove: function () {
    var self = this;

    // Remove child
    self.dropdownContainerView.remove();

    // Remove event listeners
    document.body.removeEventListener("click", self.deferClose);
    if (self.options.closeOnEsc) {
      document.body.removeEventListener("keyup", self.closeOnEsc);
    }
    self.$el.off("click", self.stopDeferClose);
    self.$dropdownButton.off("click", self.toggle);

    // Invoke original backbone methods
    return Backbone.View.prototype.remove.apply(self, arguments);
  }
});


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/mainlayout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:paddingLeft="120dp"
        android:text="@string/gravity"
        android:textSize="18sp"
        android:textStyle="bold" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/left" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="left"
        android:background="#bbdefb"
        android:gravity="center_horizontal"
        android:paddingLeft="20dp"
        android:layout_marginLeftt="20dp"
        android:text="@string/center_horizontal" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="@string/right" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:background="#bbdefb"
        android:gravity="center_vertical"
        android:paddingLeft="20dp"
        android:text="@string/center" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="@string/layout_gravity"
        android:textSize="18sp"
        android:textStyle="bold" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="left"
        android:text="@string/left" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:background="#bbdefb"
        android:text="@string/center_horizontal" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:paddingRight="120dp"
        android:text="@string/right" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:background="#bbdefb"
        android:text="@string/center" />

</LinearLayout>


text:
"""
Testing that we work in the downstream packages
"""
import pytest
import numpy as np  # noqa
from pandas import DataFrame
from pandas.compat import PY36
from pandas.util import testing as tm
import importlib

def import_module(name):
    # we *only* want to skip if the module is truly not available
    # and NOT just an actual import error because of pandas changes

    if PY36:
        try:
            return importlib.import_module(name)
        except ModuleNotFoundError:  # noqa
            pytest.skip("skipping as {} not available".format(name))

    else:
        try:
            return importlib.import_module(name)
        except ImportError as e:
            if "No module named" in str(e) and name in str(e):
                pytest.skip("skipping as {} not available".format(name))
            raise

@pytest.fixture
def df():
    return DataFrame({'A': [1, 2, 3]})

def test_dask(df):

    toolz = import_module('toolz')  # noqa
    dask = import_module('dask')  # noqa

    import dask.dataframe as dd

    ddf = dd.from_pandas(df, npartitions=3)
    assert ddf.A is not None
    assert ddf.compute() is not None

def test_xarray(df):

    xarray = import_module('xarray')  # noqa

    assert df.to_xarray() is not None

def test_statsmodels():

    statsmodels = import_module('statsmodels')  # noqa
    import statsmodels.api as sm
    import statsmodels.formula.api as smf
    df = sm.datasets.get_rdataset("Guerry", "HistData").data
    smf.ols('Lottery ~ Literacy + np.log(Pop1831)', data=df).fit()

def test_scikit_learn(df):

    sklearn = import_module('sklearn')  # noqa
    from sklearn import svm, datasets

    digits = datasets.load_digits()
    clf = svm.SVC(gamma=0.001, C=100.)
    clf.fit(digits.data[:-1], digits.target[:-1])
    clf.predict(digits.data[-1:])

def test_seaborn():

    seaborn = import_module('seaborn')
    tips = seaborn.load_dataset("tips")
    seaborn.stripplot(x="day", y="total_bill", data=tips)

def test_pandas_gbq(df):

    pandas_gbq = import_module('pandas_gbq')  # noqa

def test_pandas_datareader():

    pandas_datareader = import_module('pandas_datareader')  # noqa
    pandas_datareader.get_data_google('AAPL')

def test_geopandas():

    geopandas = import_module('geopandas')  # noqa
    fp = geopandas.datasets.get_path('naturalearth_lowres')
    assert geopandas.read_file(fp) is not None

def test_pyarrow(df):

    pyarrow = import_module('pyarrow')  # noqa
    table = pyarrow.Table.from_pandas(df)
    result = table.to_pandas()
    tm.assert_frame_equal(result, df)


text:
package com.vmware.vim25;

/**
* @author Steve Jin (http://www.doublecloud.org)
* @version 5.1
*/

@SuppressWarnings("all")
public class DvsHostBackInSyncEvent extends DvsEvent {
  public HostEventArgument hostBackInSync;

  public HostEventArgument getHostBackInSync() {
    return this.hostBackInSync;
  }

  public void setHostBackInSync(HostEventArgument hostBackInSync) {
    this.hostBackInSync=hostBackInSync;
  }
}


text:
from django.core.management.base import BaseCommand#, CommandError
from bootstrapit.models import BootstrapVersion
#from django.db.models import Q

class Command(BaseCommand):

    def handle(self, *args, **options):
        for u in BootstrapVersion.objects.all():
            print ('récupérations des fichiers pour %s récupérés' % u)
            u.save()
            print ('fichiers pour %s récupérés' % u)
        print ("tous les fichiers on été récupérés")


text:
package process

import (
	"io/ioutil"
	"log"
	"os"
	"path"
	"path/filepath"
	"strconv"
	"strings"
	"syscall"
	system "system"
	//logger "godard_logger"
	"time"
)

var Logger *log.Logger
var JournalBaseDir string

func SetLogger(new_logger *log.Logger) {
	if Logger == nil {
		Logger = new_logger
	}
}

func SetBaseDir(base_dir string) {

	if len(JournalBaseDir) == 0 {
		JournalBaseDir = path.Join(base_dir, "journals")
	}
	exists, _ := system.FileExists(JournalBaseDir)
	if !exists {
		err := os.MkdirAll(JournalBaseDir, 0777)
		if err != nil {
			Logger.Println("ERROR CREATING PIDS DIR", err)
		}
	}

	os.Chmod(JournalBaseDir, 0777)
}

func isSkipPid(pid int) bool {
	//!pid.is_a?(Integer) || pid <= 1
	return pid <= 1
}

func isSkipPgid(pid int) bool {
	//!pgid.is_a?(Integer) || pgid <= 1
	return pid <= 1
}

func AcquireAtomicFsLock(name string) {
	times := 0
	name += ".lock"
	err := os.MkdirAll(name, 0700)
	//Logger.Println("Acquired lock #{name}")
	//yield
	if err != nil {
		Logger.Println("ERROR CREATING PIDS DIR", err)
	}

	times += 1
	Logger.Println("Waiting for lock", name)
	time.Sleep(1 * time.Second)
	if !(times >= 10) {
		// retry
	} else {
		Logger.Println("Timeout waiting for lock", name)
		//raise "Timeout waiting for lock #{name}"
	}
	//ensure
	ClearAtomicFsLock(name)
}

func ClearAllAtomicFsLocks() {
	files, _ := filepath.Glob(".*.lock")
	for _, file := range files {
		if system.IsDirectory(file) {
			system.DeleteIfExists(file)
		}
	}
}

func PidJournalFilename(journal_name string) string {
	return path.Join(JournalBaseDir, ".godard_pids_journal."+journal_name)
}

func PgidJournalFilename(journal_name string) string {
	return path.Join(JournalBaseDir, ".godard_pgids_journal."+journal_name)
}

func PidJournal(filename string) []int {
	Logger.Println("pid journal file:", filename)

	var arr []int
	exists, _ := system.FileExists(filename)
	if exists {
		os.Open(filename)
	} else {
		return arr
	}

	dat := system.ReadLines(filename)

	for _, d := range dat {
		i, _ := strconv.Atoi(d)
		arr = append(arr, i)
	}
	for i, pid := range arr {
		if isSkipPid(pid) {
			arr = append(arr[:i], arr[i+1:]...)
		}
	}
	Logger.Println("pid journal =", arr)
	//rescue Errno::ENOENT
	//[]
	return arr
}

func PgidJournal(filename string) []int {
	//Logger.Println("pgid journal file: #{filename}")
	var arr []int
	exists, _ := system.FileExists(filename)
	if exists {
		os.Open(filename)
	} else {
		return arr
	}

	dat := system.ReadLines(filename)
	for _, d := range dat {
		i, _ := strconv.Atoi(d)
		arr = append(arr, i)
	}
	for i, pgid := range arr {
		if isSkipPgid(pgid) {
			arr = append(arr[:i], arr[i+1:]...)
		}
	}
	Logger.Println("pgid journal =", arr)
	//rescue Errno::ENOENT
	//[]
	return arr
}

func ClearAtomicFsLock(name string) {
	if system.IsDirectory(name) {
		os.Remove(name)
		Logger.Println("Cleared lock", name)
	}
}

func KillAllFromAllJournals() {
	filelocation := path.Join(JournalBaseDir, ".godard_pids_journal.")
	files, _ := filepath.Glob(filelocation + "*")
	var filenames []string
	var names []string
	for _, file := range files {
		filenames = append(filenames, strings.Replace(file, filelocation, "", 1))
	}
	for _, name := range filenames {
		if !strings.Contains(name, ".lock") {
			names = append(names, name)
		}
	}
	//log.Println("FILES TO KILL", names)
	for _, journal_name := range names {
		KillAllFromJournal(journal_name)
	}
}

func KillAllFromJournal(journal_name string) {
	KillAllPidsFromJournal(journal_name)
	KillAllPgidsFromJournal(journal_name)
}

func KillAllPgidsFromJournal(journal_name string) {

	filename := PgidJournalFilename(journal_name)

	j := PgidJournal(filename)

	if len(j) > 0 {
		//AcquireAtomicFsLock(filename) do ??
		for _, pgid := range j {
			err := syscall.Kill(-pgid, syscall.SIGTERM)
			Logger.Println("Termed old process group", pgid)
			if err != nil {
				Logger.Println("Unable to term missing process group", pgid)
			}
		}
		arr := make([]int, 0)
		for _, pgid := range j {
			if system.IsPidAlive(pgid) {
				arr = append(arr, pgid)
			}
		}
		if len(arr) > 1 {
			time.Sleep(1 * time.Second)
			for _, pgid := range j {
				err := syscall.Kill(-pgid, syscall.SIGTERM)
				Logger.Println("Killed old process group", pgid)
				if err != nil {
					Logger.Println("Unable to kill missing process group", pgid)
				}
			}

		}
		system.DeleteIfExists(filename) // reset journal
		Logger.Println("Journal cleanup completed")
		//end
	} else {
		Logger.Println("No previous process journal - Skipping cleanup")
	}
}

func KillAllPidsFromJournal(journal_name string) {
	filename := PidJournalFilename(journal_name)
	j := PgidJournal(filename)
	if len(j) > 0 {
		//acquire_atomic_fs_lock(filename) do
		for _, pid := range j {
			err := syscall.Kill(pid, syscall.SIGTERM)
			Logger.Println("Termed old process group", pid)
			if err != nil {
				Logger.Println("Unable to term missing process group", pid)
			}
		}

		arr := make([]int, 0)
		for _, pid := range j {
			if system.IsPidAlive(pid) {
				arr = append(arr, pid)
			}
		}
		if len(arr) > 1 {
			time.Sleep(1 * time.Second)
			for _, pid := range j {
				err := syscall.Kill(pid, syscall.SIGTERM)
				Logger.Println("Killed old process group", pid)
				if err != nil {
					Logger.Println("Unable to kill missing process group", pid)
				}
			}

		}
		system.DeleteIfExists(filename) // reset journal
		Logger.Println("Journal cleanup completed")
		//end
	} else {
		Logger.Println("No previous process journal - Skipping cleanup")
	}
}

func AppendPgidToJournal(journal_name string, pgid int) {

	if isSkipPgid(pgid) {
		Logger.Println("Skipping invalid pgid", pgid)
		//return
	} else {
		filename := PgidJournalFilename(journal_name)
		//acquire_atomic_fs_lock(filename) do
		count := 0
		for _, p := range PgidJournal(filename) {
			if p == pgid {
				count += 1
			}
		}
		if count == 0 {
			Logger.Println("Saving pgid", pgid, " to process journal", journal_name, filename)
			d1 := strconv.Itoa(pgid)

			f, err := os.OpenFile(filename, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
			f.WriteString(d1 + "\n")
			f.Close()

			//err := ioutil.WriteFile(filename, d1, 0600)
			if err == nil {
				Logger.Println("Saved pgid", pgid, " to journal", journal_name)
				dat, _ := ioutil.ReadFile(filename)
				Logger.Println("Journal now =", string(dat))
			}

		} else {
			//Logger.Println("Skipping duplicate pgid" , pgid , " already in journal", journal_name )
		}
	}

}

func AppendPidToJournal(journal_name string, pid int) {

	if isSkipPid(pid) {
		//Logger.Println("Skipping invalid pid #{pid} (class #{pid.class})")
		return
	}
	pgid, err := syscall.Getpgid(pid)
	if err != nil {

	} else {
		//Logger.Println("PGID IS:", pgid, "FROM", pid)
		AppendPgidToJournal(journal_name, pgid)
	}

	filename := PidJournalFilename(journal_name)
	//Logger.Println("FILENAME JOURNAL", filename)

	//acquire_atomic_fs_lock(filename) do
	count := 0
	for _, p := range PidJournal(filename) {
		if p == pgid {
			count += 1
		}
	}
	if count == 0 {
		Logger.Println("Saving pid", pid, " to process journal", journal_name)
		d1 := strconv.Itoa(pid)
		//err := ioutil.WriteFile(filename, d1, 0600)

		f, err := os.OpenFile(filename, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
		f.WriteString(d1 + "\n")
		f.Close()

		if err == nil {
			Logger.Println("Saved pid", pid, " to journal ", journal_name)
			dat, _ := ioutil.ReadFile(filename)
			Logger.Println("Journal now =", string(dat))
		}

	} else {
		//Logger.Println("Skipping duplicate pid", pid, " already in journal", journal_name )
	}
}


text:
import { expect, use } from 'chai'
import { RenderError } from '../../../src/util/error'
import { Liquid } from '../../../src/liquid'
import * as path from 'path'
import { mock, restore } from '../../stub/mockfs'
import * as chaiAsPromised from 'chai-as-promised'

use(chaiAsPromised)

let engine = new Liquid()
const strictEngine = new Liquid({
  strictVariables: true,
  strictFilters: true
})

describe('error', function () {
  afterEach(restore)

  describe('TokenizationError', function () {
    it('should throw TokenizationError when tag illegal', async function () {
      const err = await expect(engine.parseAndRender('{% . a %}', {})).be.rejected
      expect(err.name).to.equal('TokenizationError')
      expect(err.message).to.contain('illegal tag syntax')
    })
    it('should contain template content in err.message', async function () {
      const html = ['1st', '2nd', 'X{% . a %} Y', '4th']
      const message = [
        '   1| 1st',
        '   2| 2nd',
        '>> 3| X{% . a %} Y',
        '   4| 4th',
        'TokenizationError'
      ]
      const err = await expect(engine.parseAndRender(html.join('\n'))).be.rejected
      expect(err.message).to.equal('illegal tag syntax, line:3, col:2')
      expect(err.stack).to.contain(message.join('\n'))
      expect(err.name).to.equal('TokenizationError')
    })
    it('should contain the whole template content in err.token.input', async function () {
      const html = 'bar\nfoo{% . a %}\nfoo'
      const err = await expect(engine.parseAndRender(html)).be.rejected
      expect(err.token.input).to.equal(html)
    })
    it('should contain stack in err.stack', async function () {
      const err = await expect(engine.parseAndRender('{% . a %}')).be.rejected
      expect(err.message).to.contain('illegal tag syntax')
      expect(err.stack).to.contain('at Liquid.parse')
    })
    describe('captureStackTrace compatibility', function () {
      it('should be empty when captureStackTrace undefined', async function () {
        const err = await expect(engine.parseAndRender('{% . a %}')).be.rejected
        expect(err.stack).to.contain('illegal tag syntax')
        expect(err.stack).to.not.contain('at Object.parse')
      })
    })
    it('should throw error with [line, col] if tag unmatched', async function () {
      const err = await expect(engine.parseAndRender('1\n2\nfoo{% assign a = 4 }\n4')).be.rejected
      console.log(err.stack)
      expect(err.name).to.equal('TokenizationError')
      expect(err.message).to.equal('tag "{% assign a =..." not closed, line:3, col:4')
    })
  })

  describe('RenderError', function () {
    beforeEach(function () {
      engine = new Liquid({
        root: '/'
      })
      engine.registerTag('throwingTag', {
        render: function () {
          throw new Error('intended render error')
        }
      })
      engine.registerTag('rejectingTag', {
        render: async function () {
          throw new Error('intended render reject')
        }
      })
      engine.registerFilter('throwingFilter', () => {
        throw new Error('throwed by filter')
      })
    })
    it('should throw RenderError when tag throws', async function () {
      const src = '{%throwingTag%}'
      const err = await expect(engine.parseAndRender(src)).be.rejected
      expect(err.name).to.equal('RenderError')
      expect(err.message).to.contain('intended render error')
    })
    it('should throw RenderError when tag rejects', async function () {
      const src = '{%rejectingTag%}'
      const err = await expect(engine.parseAndRender(src)).be.rejected
      expect(err.name).to.equal('RenderError')
      expect(err.message).to.contain('intended render reject')
    })
    it('should throw RenderError when filter throws', async function () {
      const src = '{{1|throwingFilter}}'
      const err = await expect(engine.parseAndRender(src)).be.rejected
      expect(err.name).to.equal('RenderError')
      expect(err.message).to.contain('throwed by filter')
    })
    it('should not throw when variable undefined by default', async function () {
      const html = await engine.parseAndRender('X{{a}}Y')
      return expect(html).to.equal('XY')
    })
    it('should throw RenderError when variable not defined', async function () {
      const err = await expect(strictEngine.parseAndRender('{{a}}')).be.rejected
      expect(err).to.have.property('name', 'RenderError')
      expect(err.message).to.contain('undefined variable: a')
    })
    it('should contain template context in err.stack', async function () {
      const html = ['1st', '2nd', '3rd', 'X{%throwingTag%} Y', '5th', '6th', '7th']
      const message = [
        '   2| 2nd',
        '   3| 3rd',
        '>> 4| X{%throwingTag%} Y',
        '   5| 5th',
        '   6| 6th',
        '   7| 7th',
        'RenderError'
      ]
      const err = await expect(engine.parseAndRender(html.join('\n'))).be.rejected
      expect(err.message).to.equal('intended render error, line:4, col:2')
      expect(err.stack).to.contain(message.join('\n'))
      expect(err.name).to.equal('RenderError')
    })
    it('should contain original error info for {% layout %}', async function () {
      mock({
        '/throwing-tag.html': [
          '1st',
          '2nd',
          '3rd',
          'X{%throwingTag%} Y',
          '5th',
          '{%block%}{%endblock%}',
          '7th'
        ].join('\n')
      })
      const html = '{%layout "throwing-tag.html"%}'
      const message = [
        '   2| 2nd',
        '   3| 3rd',
        '>> 4| X{%throwingTag%} Y',
        '   5| 5th',
        '   6| {%block%}{%endblock%}',
        '   7| 7th',
        'RenderError'
      ]
      const err = await expect(engine.parseAndRender(html)).be.rejected
      expect(err.message).to.equal(`intended render error, file:${path.resolve('/throwing-tag.html')}, line:4, col:2`)
      expect(err.stack).to.contain(message.join('\n'))
      expect(err.name).to.equal('RenderError')
    })
    it('should contain original error info for {% include %}', async function () {
      const origin = ['1st', '2nd', '3rd', 'X{%throwingTag%} Y', '5th', '6th', '7th']
      mock({
        '/throwing-tag.html': origin.join('\n')
      })
      const html = '{%include "throwing-tag.html"%}'
      const message = [
        '   2| 2nd',
        '   3| 3rd',
        '>> 4| X{%throwingTag%} Y',
        '   5| 5th',
        '   6| 6th',
        '   7| 7th',
        'RenderError'
      ]
      const err = await expect(engine.parseAndRender(html)).be.rejected
      expect(err.message).to.equal(`intended render error, file:${path.resolve('/throwing-tag.html')}, line:4, col:2`)
      expect(err.stack).to.contain(message.join('\n'))
      expect(err.name).to.equal('RenderError')
    })
    it('should contain stack in err.stack', async function () {
      const err = await expect(engine.parseAndRender('{%rejectingTag%}')).be.rejected
      expect(err.message).to.contain('intended render reject')
      expect(err.stack).to.match(/at .*:\d+:\d+/)
    })
  })

  describe('ParseError', function () {
    beforeEach(function () {
      engine = new Liquid()
      engine.registerTag('throwsOnParse', {
        parse: function () {
          throw new Error('intended parse error')
        },
        render: () => ''
      })
    })
    it('should throw ParseError when filter not defined', async function () {
      const err = await expect(strictEngine.parseAndRender('{{1 | a}}')).be.rejected
      expect(err).to.have.property('name', 'ParseError')
      expect(err.message).to.contain('undefined filter: a')
    })
    it('should throw ParseError when tag not closed', async function () {
      const err = await expect(engine.parseAndRender('{% if %}')).be.rejected
      expect(err.name).to.equal('ParseError')
      expect(err.message).to.contain('tag {% if %} not closed')
    })
    it('should throw ParseError when tag parse throws', async function () {
      const err = await expect(engine.parseAndRender('{%throwsOnParse%}')).be.rejected
      expect(err.name).to.equal('ParseError')
      expect(err.message).to.contain('intended parse error')
    })
    it('should throw ParseError when tag not found', async function () {
      const src = '{%if true%}\naaa{%endif%}\n{% -a %}\n3'
      const err = await expect(engine.parseAndRender(src)).be.rejected
      expect(err.name).to.equal('ParseError')
      expect(err.message).to.contain('tag "-a" not found')
    })
    it('should throw ParseError when tag not exist', async function () {
      const err = await expect(engine.parseAndRender('{% a %}')).be.rejected
      expect(err.name).to.equal('ParseError')
      expect(err.message).to.contain('tag "a" not found')
    })

    it('should contain template context in err.stack', async function () {
      const html = ['1st', '2nd', '3rd', 'X{% a %} {% enda %} Y', '5th', '6th', '7th']
      const message = [
        '   2| 2nd',
        '   3| 3rd',
        '>> 4| X{% a %} {% enda %} Y',
        '   5| 5th',
        '   6| 6th',
        '   7| 7th',
        'ParseError: tag "a" not found'
      ]
      const err = await expect(engine.parseAndRender(html.join('\n'))).be.rejected
      expect(err.message).to.equal('tag "a" not found, line:4, col:2')
      expect(err.stack).to.contain(message.join('\n'))
      expect(err.name).to.equal('ParseError')
    })

    it('should handle err.message when context not enough', async function () {
      const html = ['1st', 'X{% a %} {% enda %} Y', '3rd', '4th']
      const message = [
        '   1| 1st',
        '>> 2| X{% a %} {% enda %} Y',
        '   3| 3rd',
        '   4| 4th',
        'ParseError: tag "a" not found'
      ]
      const err = await expect(engine.parseAndRender(html.join('\n'))).be.rejected
      expect(err.message).to.equal('tag "a" not found, line:2, col:2')
      expect(err.stack).to.contain(message.join('\n'))
    })

    it('should contain stack in err.stack', async function () {
      const err = await expect(engine.parseAndRender('{% -a %}')).be.rejected
      expect(err.stack).to.contain('ParseError: tag "-a" not found')
      expect(err.stack).to.match(/at .*:\d+:\d+\)/)
    })
  })
  describe('sync support', function () {
    let engine: Liquid
    beforeEach(function () {
      engine = new Liquid({
        root: '/'
      })
      engine.registerTag('throwingTag', {
        render: function () {
          throw new Error('intended render error')
        }
      })
    })
    it('should throw RenderError when tag throws', function () {
      const src = '{%throwingTag%}'
      expect(() => engine.parseAndRenderSync(src))
        .to.throw(RenderError, /intended render error/)
    })
    it('should contain original error info for {% include %}', function () {
      mock({
        '/throwing-tag.html': ['1st', '2nd', '3rd', 'X{%throwingTag%} Y', '5th', '6th', '7th'].join('\n')
      })
      const html = '{%include "throwing-tag.html"%}'
      const message = [
        '   2| 2nd',
        '   3| 3rd',
        '>> 4| X{%throwingTag%} Y',
        '   5| 5th',
        '   6| 6th',
        '   7| 7th',
        'RenderError'
      ]
      try {
        engine.parseAndRenderSync(html)
        throw new Error('expected throw')
      } catch (err) {
        expect(err.message).to.equal(`intended render error, file:${path.resolve('/throwing-tag.html')}, line:4, col:2`)
        expect(err.stack).to.contain(message.join('\n'))
        expect(err.name).to.equal('RenderError')
      }
    })
  })
})


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Debugger.Interop;
using System.Diagnostics;
using System.Threading;

namespace Cosmos.Debug.VSDebugEngine
{
    // this class represents a module loaded in the debuggee process to the debugger.
    public class AD7Module : IDebugModule2, IDebugModule3 {
        //public readonly DebuggedModule DebuggedModule;

        public AD7Module() { //DebuggedModule debuggedModule)
            //this.DebuggedModule = debuggedModule;
        }

        // Gets the MODULE_INFO that describes this module.
        // This is how the debugger obtains most of the information about the module.
        int IDebugModule2.GetInfo(enum_MODULE_INFO_FIELDS dwFields, MODULE_INFO[] infoArray)
        {
            try
            {
                MODULE_INFO info = new MODULE_INFO();

                if (dwFields.HasFlag(enum_MODULE_INFO_FIELDS.MIF_NAME))
                {
                    //info.m_bstrName = System.IO.Path.GetFileName(this.DebuggedModule.Name);
                    info.m_bstrName = "DEADBEEF";
                    info.dwValidFields |= enum_MODULE_INFO_FIELDS.MIF_NAME;
                }
                if (dwFields.HasFlag(enum_MODULE_INFO_FIELDS.MIF_URL))
                {
                    //info.m_bstrUrl = this.DebuggedModule.Name;
                    info.m_bstrUrl = "DEADBEEF";
                    info.dwValidFields |= enum_MODULE_INFO_FIELDS.MIF_URL;
                }
                if (dwFields.HasFlag(enum_MODULE_INFO_FIELDS.MIF_LOADADDRESS))
                {
                    //info.m_addrLoadAddress = (ulong)this.DebuggedModule.BaseAddress;
                    info.dwValidFields |= enum_MODULE_INFO_FIELDS.MIF_LOADADDRESS;
                }
                if (dwFields.HasFlag(enum_MODULE_INFO_FIELDS.MIF_PREFFEREDADDRESS))
                {
                    // A debugger that actually supports showing the preferred base should crack the PE header and get
                    // that field. This debugger does not do that, so assume the module loaded where it was suppose to.
                    //info.m_addrPreferredLoadAddress = (ulong)this.DebuggedModule.BaseAddress;
                    info.dwValidFields |= enum_MODULE_INFO_FIELDS.MIF_PREFFEREDADDRESS;
                }
                if (dwFields.HasFlag(enum_MODULE_INFO_FIELDS.MIF_SIZE))
                {
                    //info.m_dwSize = this.DebuggedModule.Size;
                    info.dwValidFields |= enum_MODULE_INFO_FIELDS.MIF_SIZE;
                }
                if (dwFields.HasFlag(enum_MODULE_INFO_FIELDS.MIF_LOADORDER))
                {
                    //info.m_dwLoadOrder = this.DebuggedModule.GetLoadOrder();
                    info.dwValidFields |= enum_MODULE_INFO_FIELDS.MIF_LOADORDER;
                }
                if (dwFields.HasFlag(enum_MODULE_INFO_FIELDS.MIF_URLSYMBOLLOCATION))
                {
                    //if (this.DebuggedModule.SymbolsLoaded)
                    {
                        //info.m_bstrUrlSymbolLocation = this.DebuggedModule.SymbolPath;
                        info.dwValidFields |= enum_MODULE_INFO_FIELDS.MIF_URLSYMBOLLOCATION;
                    }
                }
                if (dwFields.HasFlag(enum_MODULE_INFO_FIELDS.MIF_FLAGS))
                {
                    info.m_dwModuleFlags = 0;
                    //if (this.DebuggedModule.SymbolsLoaded)
                    {
                        info.m_dwModuleFlags |= (enum_MODULE_FLAGS.MODULE_FLAG_SYMBOLS);
                    }
                    info.dwValidFields |= enum_MODULE_INFO_FIELDS.MIF_FLAGS;
                }

                infoArray[0] = info;

                return VSConstants.S_OK;
            }
            //catch (ComponentException e)
            //{
            //    return e.HResult;
            //}
            catch (Exception e)
            {
                return EngineUtils.UnexpectedException(e);
            }
        }

        #region Deprecated interface methods
        // These methods are not called by the Visual Studio debugger, so they don't need to be implemented
        int IDebugModule2.ReloadSymbols_Deprecated(string urlToSymbols, out string debugMessage) {
            debugMessage = null;
            System.Diagnostics.Debug.Fail("This function is not called by the debugger.");
            return VSConstants.E_NOTIMPL;
        }

        int IDebugModule3.ReloadSymbols_Deprecated(string pszUrlToSymbols, out string pbstrDebugMessage) {
            throw new NotImplementedException();
        }
        #endregion

        // IDebugModule3 represents a module that supports alternate locations of symbols and JustMyCode states.
        // The sample does not support alternate symbol locations or JustMyCode, but it does not display symbol load information

        // Gets the MODULE_INFO that describes this module.
        // This is how the debugger obtains most of the information about the module.
        int IDebugModule3.GetInfo(enum_MODULE_INFO_FIELDS dwFields, MODULE_INFO[] pinfo)
        {
            return ((IDebugModule2)this).GetInfo(dwFields, pinfo);
        }

        // Returns a list of paths searched for symbols and the results of searching each path.
        int IDebugModule3.GetSymbolInfo(enum_SYMBOL_SEARCH_INFO_FIELDS dwFields, MODULE_SYMBOL_SEARCH_INFO[] pinfo)
        {
            // This engine only supports loading symbols at the location specified in the binary's symbol path location in the PE file and
            // does so only for the primary exe of the debuggee.
            // Therefore, it only displays if the symbols were loaded or not. If symbols were loaded, that path is added.
            pinfo[0] = new MODULE_SYMBOL_SEARCH_INFO();
            pinfo[0].dwValidFields = 1; // SSIF_VERBOSE_SEARCH_INFO;

            //if (this.DebuggedModule.SymbolsLoaded)
            {
                //string symbolPath = "Symbols Loaded - " + this.DebuggedModule.SymbolPath;
                //pinfo[0].bstrVerboseSearchInfo = symbolPath;
            }
            //else
            {
                string symbolsNotLoaded = "Symbols not loaded";
                pinfo[0].bstrVerboseSearchInfo = symbolsNotLoaded;
            }
            return VSConstants.S_OK;
        }

        // Used to support the JustMyCode features of the debugger.
        // the sample debug engine does not support JustMyCode and therefore all modules
        // are considered "My Code"
        int IDebugModule3.IsUserCode(out int pfUser)
        {
            pfUser = 1;
            return VSConstants.S_OK;
        }

        // Loads and initializes symbols for the current module when the user explicitly asks for them to load.
        // The sample engine only supports loading symbols from the location pointed to by the PE file which will load
        // when the module is loaded.
        int IDebugModule3.LoadSymbols()
        {
            throw new NotImplementedException();
        }

        // Used to support the JustMyCode features of the debugger.
        // The sample engine does not support JustMyCode so this is not implemented
        int IDebugModule3.SetJustMyCodeState(int fIsUserCode)
        {
            throw new NotImplementedException();
        }

    }
}


text:
<?php defined('SYSPATH') OR die('No direct access allowed.');

class Kohana_Model_Quill_Reply extends ORM {

	// Table specification
	protected $_table_name = 'quill_replies';

	protected $_table_columns = array(
		'id' => null,
		'user_id' => null,
		'topic_id' => null,
		'content' => null,
		'created_at' => null,
		'status' => null
	);

	// Relationships
	protected $_belongs_to = array(
		'topic' => array('model' => 'Quill_Topic', 'foreign_key' => 'topic_id'),
		'user' => array('model' => 'User', 'foreign_key' => 'user_id')
	);

	protected $_load_with = array('user');

	// Auto-update time column
	protected $_created_column = array('column' => 'created_at', 'format' => true);

	public function rules()
	{
		return array(
			'content' => array(
				array('not_empty')
			),
			'status' => array(
				array('in_array', array(':value', array('active', 'deleted'))),
			),
			'user_id' => array(
				array('not_empty')
			),
			'topic_id' => array(
				array('not_empty')
			),
		);
	}

	/**
	 * Automatically 'touch' the related topic if needed.
	 *
	 * @param Validation $validation
	 * @param bool $touch_topic
	 * @return ORM
	 */
	public function save(Validation $validation=null, $touch_topic=false)
	{
		if($touch_topic == true)
		{
			$this->topic->updated_at = time();
			$this->topic->save();
		}

		return parent::save($validation);
	}

	/**
	 * When deleting a reply, check if topic reply_count should be recalculated.
	 * @return ORM
	 */
	public function delete()
	{
		if($this->topic->category->location->count_replies == 1)
		{
			$this->topic->reply_count = DB::select(array(DB::expr('COUNT(*)'), 'replies'))
				->from('quill_replies')
				->where('topic_id', '=', $this->topic_id)
				->where('status', '=', 'active')
				->execute()
				->get('replies') - 1;

			$this->topic->save();
		}

		//check if the last posted user is still correct
		if($this->topic->category->location->record_last_post == 1)
		{
			$last_post = $this->topic->replies->where('quill_reply.id', '!=', $this->id)->order_by('created_at', 'DESC')->find();

			if($last_post->user_id != $this->topic->last_post_user_id)
			{
				$this->topic->last_post_user_id = $last_post->user_id;
				$this->topic->save(null, false);
			}

		}

		return parent::delete();
	}

	public function get($col)
	{
		if($col == $this->_created_column['column'])
		{
			return date(Kohana::$config->load('quill.time_format'), parent::get($col));
		}

		return parent::get($col);
	}
} // End Quill reply model


text:
package voldemort.store.metadata;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import junit.framework.TestCase;
import voldemort.ServerTestUtils;
import voldemort.client.rebalance.RebalancePartitionsInfo;
import voldemort.server.rebalance.RebalancerState;
import voldemort.store.metadata.MetadataStore.VoldemortState;
import voldemort.utils.ByteArray;
import voldemort.utils.ByteUtils;
import voldemort.versioning.ObsoleteVersionException;
import voldemort.versioning.VectorClock;
import voldemort.versioning.Versioned;
import voldemort.xml.ClusterMapper;
import voldemort.xml.StoreDefinitionsMapper;

import com.google.common.collect.Maps;

public class MetadataStoreTest extends TestCase {

    private static int TEST_RUNS = 100;

    private MetadataStore metadataStore;
    private List<String> TEST_KEYS = Arrays.asList(MetadataStore.CLUSTER_KEY,
                                                   MetadataStore.STORES_KEY,
                                                   MetadataStore.REBALANCING_STEAL_INFO,
                                                   MetadataStore.SERVER_STATE_KEY);

    @Override
    public void setUp() throws Exception {
        super.setUp();
        metadataStore = ServerTestUtils.createMetadataStore(ServerTestUtils.getLocalCluster(1),
                                                            ServerTestUtils.getStoreDefs(1));
    }

    public ByteArray getValidKey() {
        int i = (int) (Math.random() * TEST_KEYS.size());
        String key = TEST_KEYS.get(i);
        return new ByteArray(ByteUtils.getBytes(key, "UTF-8"));
    }

    public byte[] getValidValue(ByteArray key) {
        String keyString = ByteUtils.getString(key.get(), "UTF-8");
        if(MetadataStore.CLUSTER_KEY.equals(keyString)) {
            return ByteUtils.getBytes(new ClusterMapper().writeCluster(ServerTestUtils.getLocalCluster(1)),
                                      "UTF-8");
        } else if(MetadataStore.STORES_KEY.equals(keyString)) {
            return ByteUtils.getBytes(new StoreDefinitionsMapper().writeStoreList(ServerTestUtils.getStoreDefs(1)),
                                      "UTF-8");

        } else if(MetadataStore.SERVER_STATE_KEY.equals(keyString)) {
            int i = (int) (Math.random() * VoldemortState.values().length);
            return ByteUtils.getBytes(VoldemortState.values()[i].toString(), "UTF-8");
        } else if(MetadataStore.REBALANCING_STEAL_INFO.equals(keyString)) {
            int size = (int) (Math.random() * 10) + 1;
            List<Integer> partition = new ArrayList<Integer>();
            for(int i = 0; i < size; i++) {
                partition.add((int) Math.random() * 10);
            }

            HashMap<Integer, List<Integer>> replicaToPartition = Maps.newHashMap();
            replicaToPartition.put(0, partition);

            HashMap<String, HashMap<Integer, List<Integer>>> storeToReplicaToPartitionList = Maps.newHashMap();
            storeToReplicaToPartitionList.put("test", replicaToPartition);

            return ByteUtils.getBytes(new RebalancerState(Arrays.asList(new RebalancePartitionsInfo(0,
                                                                                (int) Math.random() * 5,
                                                                                storeToReplicaToPartitionList,
                                                                                storeToReplicaToPartitionList,
                                                                                ServerTestUtils.getLocalCluster(1),
                                                                                (int) Math.random() * 3))).toJsonString(),
                                      "UTF-8");
        }

        throw new RuntimeException("Unhandled key:" + keyString + " passed");
    }

    public void testSimpleGetAndPut() {
        for(int i = 0; i <= TEST_RUNS; i++) {
            ByteArray key = getValidKey();
            VectorClock clock = (VectorClock) metadataStore.get(key, null).get(0).getVersion();
            Versioned<byte[]> value = new Versioned<byte[]>(getValidValue(key),
                                                            clock.incremented(0, 1));

            metadataStore.put(key, value, null);
            checkValues(value, metadataStore.get(key, null), key);
        }
    }

    public void testRepeatedPuts() {
        for(int i = 0; i <= TEST_RUNS; i++) {
            for(int j = 0; j <= 5; j++) {
                ByteArray key = getValidKey();

                VectorClock clock = (VectorClock) metadataStore.get(key, null).get(0).getVersion();
                Versioned<byte[]> value = new Versioned<byte[]>(getValidValue(key),
                                                                clock.incremented(0, 1));

                metadataStore.put(key, value, null);
                checkValues(value, metadataStore.get(key, null), key);
            }
        }
    }

    public void testObsoletePut() {
        for(int i = 0; i <= TEST_RUNS; i++) {
            ByteArray key = getValidKey();
            VectorClock clock = (VectorClock) metadataStore.get(key, null).get(0).getVersion();
            Versioned<byte[]> value = new Versioned<byte[]>(getValidValue(key),
                                                            clock.incremented(0, 1));

            try {
                metadataStore.put(key, value, null);
                assertTrue(true);
                metadataStore.put(key, value, null);
                fail();
            } catch(ObsoleteVersionException e) {
                // expected ObsoleteVersionException
            }
        }
    }

    public void testSynchronousPut() {
        for(int i = 0; i <= TEST_RUNS; i++) {
            ByteArray key = getValidKey();
            VectorClock clock = (VectorClock) metadataStore.get(key, null).get(0).getVersion();

            Versioned<byte[]> value1 = new Versioned<byte[]>(getValidValue(key),
                                                             clock.incremented(1, 1));
            Versioned<byte[]> value2 = new Versioned<byte[]>(getValidValue(key),
                                                             clock.incremented(2, 1));

            metadataStore.put(key, value1, null);
            metadataStore.put(key, value2, null);

            assertEquals("Only one metadata value should return", 1, metadataStore.get(key, null)
                                                                                .size());
            checkValues(value2, metadataStore.get(key, null), key);
        }
    }

    public void testCleanAllStates() {
        // put state entries.
        incrementVersionAndPut(metadataStore,
                               MetadataStore.SERVER_STATE_KEY,
                               MetadataStore.VoldemortState.REBALANCING_MASTER_SERVER);

        assertEquals("Values should match.",
                     metadataStore.getServerState(),
                     VoldemortState.REBALANCING_MASTER_SERVER);

        // do clean
        metadataStore.cleanAllRebalancingState();

        // check all values revert back to default.
        assertEquals("Values should match.",
                     metadataStore.getServerState(),
                     VoldemortState.NORMAL_SERVER);
    }

    private void checkValues(Versioned<byte[]> value, List<Versioned<byte[]>> list, ByteArray key) {
        assertEquals("should return exactly one value ", 1, list.size());

        assertEquals("should return the last saved version", value.getVersion(), list.get(0)
                                                                                .getVersion());
        assertEquals("should return the last saved value (key:"
                             + ByteUtils.getString(key.get(), "UTF-8") + ")",
                     new String(value.getValue()),
                     new String(list.get(0).getValue()));
    }

    /**
     * helper function to auto update version and put()
     *
     * @param key
     * @param value
     */
    private void incrementVersionAndPut(MetadataStore metadataStore, String keyString, Object value) {
        ByteArray key = new ByteArray(ByteUtils.getBytes(keyString, "UTF-8"));
        VectorClock current = (VectorClock) metadataStore.getVersions(key).get(0);

        metadataStore.put(keyString,
                          new Versioned<Object>(value,
                                                current.incremented(0, System.currentTimeMillis())));
    }
}