text:
package input

import (
	glfw "github.com/go-gl/glfw3"
)

//Joystick corresponds to a joystick.
type Joystick glfw.Joystick

//Joystick IDs
const (
	Joystick1    = Joystick(glfw.Joystick1)
	Joystick2    = Joystick(glfw.Joystick2)
	Joystick3    = Joystick(glfw.Joystick3)
	Joystick4    = Joystick(glfw.Joystick4)
	Joystick5    = Joystick(glfw.Joystick5)
	Joystick6    = Joystick(glfw.Joystick6)
	Joystick7    = Joystick(glfw.Joystick7)
	Joystick8    = Joystick(glfw.Joystick8)
	Joystick9    = Joystick(glfw.Joystick9)
	Joystick10   = Joystick(glfw.Joystick10)
	Joystick11   = Joystick(glfw.Joystick11)
	Joystick12   = Joystick(glfw.Joystick12)
	Joystick13   = Joystick(glfw.Joystick13)
	Joystick14   = Joystick(glfw.Joystick14)
	Joystick15   = Joystick(glfw.Joystick15)
	Joystick16   = Joystick(glfw.Joystick16)
	JoystickLast = Joystick(glfw.JoystickLast)
)

//Key corresponds to a keyboard key.
type Key glfw.Key

//These key codes are inspired by the USB HID Usage Tables v1.12 (p. 53-60),
//but re-arranged to map to 7-bit ASCII for printable keys (function keys are
//put in the 256+ range).
const (
	KeyUnknown      = Key(glfw.KeyUnknown)
	KeySpace        = Key(glfw.KeySpace)
	KeyApostrophe   = Key(glfw.KeyApostrophe)
	KeyComma        = Key(glfw.KeyComma)
	KeyMinus        = Key(glfw.KeyMinus)
	KeyPeriod       = Key(glfw.KeyPeriod)
	KeySlash        = Key(glfw.KeySlash)
	Key0            = Key(glfw.Key0)
	Key1            = Key(glfw.Key1)
	Key2            = Key(glfw.Key2)
	Key3            = Key(glfw.Key3)
	Key4            = Key(glfw.Key4)
	Key5            = Key(glfw.Key5)
	Key6            = Key(glfw.Key6)
	Key7            = Key(glfw.Key7)
	Key8            = Key(glfw.Key8)
	Key9            = Key(glfw.Key9)
	KeySemicolon    = Key(glfw.KeySemicolon)
	KeyEqual        = Key(glfw.KeyEqual)
	KeyA            = Key(glfw.KeyA)
	KeyB            = Key(glfw.KeyB)
	KeyC            = Key(glfw.KeyC)
	KeyD            = Key(glfw.KeyD)
	KeyE            = Key(glfw.KeyE)
	KeyF            = Key(glfw.KeyF)
	KeyG            = Key(glfw.KeyG)
	KeyH            = Key(glfw.KeyH)
	KeyI            = Key(glfw.KeyI)
	KeyJ            = Key(glfw.KeyJ)
	KeyK            = Key(glfw.KeyK)
	KeyL            = Key(glfw.KeyL)
	KeyM            = Key(glfw.KeyM)
	KeyN            = Key(glfw.KeyN)
	KeyO            = Key(glfw.KeyO)
	KeyP            = Key(glfw.KeyP)
	KeyQ            = Key(glfw.KeyQ)
	KeyR            = Key(glfw.KeyR)
	KeyS            = Key(glfw.KeyS)
	KeyT            = Key(glfw.KeyT)
	KeyU            = Key(glfw.KeyU)
	KeyV            = Key(glfw.KeyV)
	KeyW            = Key(glfw.KeyW)
	KeyX            = Key(glfw.KeyX)
	KeyY            = Key(glfw.KeyY)
	KeyZ            = Key(glfw.KeyZ)
	KeyLeftBracket  = Key(glfw.KeyLeftBracket)
	KeyBackslash    = Key(glfw.KeyBackslash)
	KeyBracket      = Key(glfw.KeyBracket)
	KeyRightBracket = Key(glfw.KeyRightBracket)
	KeyGraveAccent  = Key(glfw.KeyGraveAccent)
	KeyWorld1       = Key(glfw.KeyWorld1)
	KeyWorld2       = Key(glfw.KeyWorld2)
	KeyEscape       = Key(glfw.KeyEscape)
	KeyEnter        = Key(glfw.KeyEnter)
	KeyTab          = Key(glfw.KeyTab)
	KeyBackspace    = Key(glfw.KeyBackspace)
	KeyInsert       = Key(glfw.KeyInsert)
	KeyDelete       = Key(glfw.KeyDelete)
	KeyRight        = Key(glfw.KeyRight)
	KeyLeft         = Key(glfw.KeyLeft)
	KeyDown         = Key(glfw.KeyDown)
	KeyUp           = Key(glfw.KeyUp)
	KeyPageUp       = Key(glfw.KeyPageUp)
	KeyPageDown     = Key(glfw.KeyPageDown)
	KeyHome         = Key(glfw.KeyHome)
	KeyEnd          = Key(glfw.KeyEnd)
	KeyCapsLock     = Key(glfw.KeyCapsLock)
	KeyScrollLock   = Key(glfw.KeyScrollLock)
	KeyNumLock      = Key(glfw.KeyNumLock)
	KeyPrintScreen  = Key(glfw.KeyPrintScreen)
	KeyPause        = Key(glfw.KeyPause)
	KeyF1           = Key(glfw.KeyF1)
	KeyF2           = Key(glfw.KeyF2)
	KeyF3           = Key(glfw.KeyF3)
	KeyF4           = Key(glfw.KeyF4)
	KeyF5           = Key(glfw.KeyF5)
	KeyF6           = Key(glfw.KeyF6)
	KeyF7           = Key(glfw.KeyF7)
	KeyF8           = Key(glfw.KeyF8)
	KeyF9           = Key(glfw.KeyF9)
	KeyF10          = Key(glfw.KeyF10)
	KeyF11          = Key(glfw.KeyF11)
	KeyF12          = Key(glfw.KeyF12)
	KeyF13          = Key(glfw.KeyF13)
	KeyF14          = Key(glfw.KeyF14)
	KeyF15          = Key(glfw.KeyF15)
	KeyF16          = Key(glfw.KeyF16)
	KeyF17          = Key(glfw.KeyF17)
	KeyF18          = Key(glfw.KeyF18)
	KeyF19          = Key(glfw.KeyF19)
	KeyF20          = Key(glfw.KeyF20)
	KeyF21          = Key(glfw.KeyF21)
	KeyF22          = Key(glfw.KeyF22)
	KeyF23          = Key(glfw.KeyF23)
	KeyF24          = Key(glfw.KeyF24)
	KeyF25          = Key(glfw.KeyF25)
	KeyKp0          = Key(glfw.KeyKp0)
	KeyKp1          = Key(glfw.KeyKp1)
	KeyKp2          = Key(glfw.KeyKp2)
	KeyKp3          = Key(glfw.KeyKp3)
	KeyKp4          = Key(glfw.KeyKp4)
	KeyKp5          = Key(glfw.KeyKp5)
	KeyKp6          = Key(glfw.KeyKp6)
	KeyKp7          = Key(glfw.KeyKp7)
	KeyKp8          = Key(glfw.KeyKp8)
	KeyKp9          = Key(glfw.KeyKp9)
	KeyKpDecimal    = Key(glfw.KeyKpDecimal)
	KeyKpDivide     = Key(glfw.KeyKpDivide)
	KeyKpMultiply   = Key(glfw.KeyKpMultiply)
	KeyKpSubtract   = Key(glfw.KeyKpSubtract)
	KeyKpAdd        = Key(glfw.KeyKpAdd)
	KeyKpEnter      = Key(glfw.KeyKpEnter)
	KeyKpEqual      = Key(glfw.KeyKpEqual)
	KeyLeftShift    = Key(glfw.KeyLeftShift)
	KeyLeftControl  = Key(glfw.KeyLeftControl)
	KeyLeftAlt      = Key(glfw.KeyLeftAlt)
	KeyLeftSuper    = Key(glfw.KeyLeftSuper)
	KeyRightShift   = Key(glfw.KeyRightShift)
	KeyRightControl = Key(glfw.KeyRightControl)
	KeyRightAlt     = Key(glfw.KeyRightAlt)
	KeyRightSuper   = Key(glfw.KeyRightSuper)
	KeyMenu         = Key(glfw.KeyMenu)
	KeyLast         = Key(glfw.KeyLast)
)

//ModifierKey corresponds to a modifier key.
type ModifierKey glfw.ModifierKey

//Modifier keys
const (
	ModShift   = ModifierKey(glfw.ModShift)
	ModControl = ModifierKey(glfw.ModControl)
	ModAlt     = ModifierKey(glfw.ModAlt)
	ModSuper   = ModifierKey(glfw.ModSuper)
)

//MouseButton corresponds to a mouse button.
type MouseButton glfw.MouseButton

//Mouse buttons
const (
	MouseButton1      = MouseButton(glfw.MouseButton1)
	MouseButton2      = MouseButton(glfw.MouseButton2)
	MouseButton3      = MouseButton(glfw.MouseButton3)
	MouseButton4      = MouseButton(glfw.MouseButton4)
	MouseButton5      = MouseButton(glfw.MouseButton5)
	MouseButton6      = MouseButton(glfw.MouseButton6)
	MouseButton7      = MouseButton(glfw.MouseButton7)
	MouseButton8      = MouseButton(glfw.MouseButton8)
	MouseButtonLast   = MouseButton(glfw.MouseButtonLast)
	MouseButtonLeft   = MouseButton(glfw.MouseButtonLeft)
	MouseButtonRight  = MouseButton(glfw.MouseButtonRight)
	MouseButtonMiddle = MouseButton(glfw.MouseButtonMiddle)
)

//Action corresponds to a key or button action.
type Action glfw.Action

const (
	Release = Action(glfw.Release)
	Press   = Action(glfw.Press)
	Repeat  = Action(glfw.Repeat)
)

//InputMode corresponds to an input mode.
type InputMode glfw.InputMode

//Input modes
const (
	Cursor             = InputMode(glfw.Cursor)
	StickyKeys         = InputMode(glfw.StickyKeys)
	StickyMouseButtons = InputMode(glfw.StickyMouseButtons)
)

//Cursor mode values
const (
	CursorNormal   int = glfw.CursorNormal
	CursorHidden   int = glfw.CursorHidden
	CursorDisabled int = glfw.CursorDisabled
)


text:
package com.novoda.sexp.marshaller;

public class IntegerBodyMarshaller implements BodyMarshaller<Integer> {
    @Override
    public Integer marshall(String input) {
        return Integer.valueOf(input);
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.infinispan.distribution.rehash;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.infinispan.commands.remote.CacheRpcCommand;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.container.DataContainer;
import org.infinispan.container.entries.InternalCacheEntry;
import org.infinispan.distribution.MagicKey;
import org.infinispan.manager.CacheContainer;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.remoting.InboundInvocationHandler;
import org.infinispan.remoting.rpc.RpcManager;
import org.infinispan.remoting.transport.Address;
import org.infinispan.remoting.transport.Transport;
import org.infinispan.remoting.transport.jgroups.CommandAwareRpcDispatcher;
import org.infinispan.statetransfer.StateChunk;
import org.infinispan.statetransfer.StateRequestCommand;
import org.infinispan.statetransfer.StateResponseCommand;
import org.infinispan.statetransfer.StateTransferManager;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.fwk.CheckPoint;
import org.infinispan.test.fwk.CleanupAfterMethod;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.infinispan.tx.dld.ControlledRpcManager;
import org.jgroups.blocks.Response;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.testng.annotations.Test;

import static java.util.concurrent.TimeUnit.SECONDS;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.*;
import static org.testng.Assert.assertTrue;

/**
 * Start two rebalance operations by stopping two members of a cluster in sequence.
 * Test that a delayed StateResponseCommand doesn't break state transfer.
 * See https://issues.jboss.org/browse/ISPN-3120
 *
 * @author Dan Berindei
 */
@CleanupAfterMethod
@Test(groups = "functional", testName = "distribution.rehash.StateResponseOrderingTest")
public class StateResponseOrderingTest extends MultipleCacheManagersTest {
   @Override
   protected void createCacheManagers() throws Throwable {
      ConfigurationBuilder builder = TestCacheManagerFactory.getDefaultCacheConfiguration(true);
      builder.clustering().cacheMode(CacheMode.DIST_SYNC).hash().numOwners(3);
      createCluster(builder, 4);
      waitForClusterToForm();
   }

   public void testOldStateResponse() throws Throwable {
      MagicKey k1 = new MagicKey("k1", cache(1));
      MagicKey k2 = new MagicKey("k2", cache(2));
      MagicKey k3 = new MagicKey("k3", cache(3));
      cache(1).put(k1, "v1");
      cache(2).put(k2, "v2");
      cache(3).put(k3, "v3");

      final StateTransferManager stm = cache(0).getAdvancedCache().getComponentRegistry().getStateTransferManager();
      int initialTopologyId = stm.getCacheTopology().getTopologyId();

      RpcManager rm = TestingUtil.extractComponent(cache(0), RpcManager.class);
      ControlledRpcManager crm = new ControlledRpcManager(rm);
      crm.blockBefore(StateRequestCommand.class);
      TestingUtil.replaceComponent(cache(0), RpcManager.class, crm, true);

      cache(3).stop();

      eventually(new Condition() {
         @Override
         public boolean isSatisfied() throws Exception {
            // Wait for the rebalance cache topology to be installed
            return stm.getCacheTopology().getPendingCH() != null;
         }
      });

      // Cache 0 didn't manage to send any StateRequestCommand yet.
      // We'll pretend it got a StateResponseCommand with an older topology id.
      InboundInvocationHandler iih = TestingUtil.extractGlobalComponent(manager(0), InboundInvocationHandler.class);
      StateChunk stateChunk = new StateChunk(0, Collections.<InternalCacheEntry>emptyList(), true);
      StateResponseCommand stateResponseCommand = new StateResponseCommand(CacheContainer.DEFAULT_CACHE_NAME,
            address(3), initialTopologyId, Arrays.asList(stateChunk));
      iih.handle(stateResponseCommand, address(3), null);

      crm.stopBlocking();

      TestingUtil.waitForRehashToComplete(cache(0), cache(1), cache(2));

      DataContainer dataContainer = TestingUtil.extractComponent(cache(0), DataContainer.class);
      assertTrue(dataContainer.containsKey(k1, null));
      assertTrue(dataContainer.containsKey(k2, null));
      assertTrue(dataContainer.containsKey(k3, null));
   }

   public void testStateResponseWhileRestartingBrokenTransfers() throws Throwable {
      MagicKey k1 = new MagicKey("k1", cache(1), cache(2), cache(3));
      cache(0).put(k1, "v1");

      final StateTransferManager stm = cache(0).getAdvancedCache().getComponentRegistry().getStateTransferManager();
      final int initialTopologyId = stm.getCacheTopology().getTopologyId();

      final CheckPoint checkPoint = new CheckPoint();
      replaceInvocationHandler(checkPoint, manager(0), StateResponseCommand.class);
      replaceInvocationHandler(checkPoint, manager(1), StateRequestCommand.class);
      replaceInvocationHandler(checkPoint, manager(2), StateRequestCommand.class);

      log.debugf("Killing node %s", address(3));
      cache(3).stop();

      eventually(new Condition() {
         @Override
         public boolean isSatisfied() throws Exception {
            // Wait for the rebalance cache topology to be installed
            return stm.getCacheTopology().getTopologyId() == initialTopologyId + 2;
         }
      });

      // Allow cache 0 to request transactions from caches 1 and 2 (in any order)
      checkPoint.trigger("OUT_GET_TRANSACTIONS_" + address(1));
      checkPoint.trigger("OUT_GET_TRANSACTIONS_" + address(2));
      checkPoint.awaitStrict("IN_GET_TRANSACTIONS_" + address(1), 10, SECONDS);
      checkPoint.awaitStrict("IN_GET_TRANSACTIONS_" + address(2), 10, SECONDS);

      // See which cache receives the START_STATE_TRANSFER command first. We'll kill the other.
      String event = checkPoint.peek(5, TimeUnit.SECONDS, "IN_START_STATE_TRANSFER_" + address(1),
            "IN_START_STATE_TRANSFER_" + address(2));
      int liveNode = event.endsWith(address(1).toString()) ? 1 : 2;
      int nodeToKill = liveNode == 1 ? 2 : 1;
      List<Address> keyOwners = cache(0).getAdvancedCache().getDistributionManager().locate(k1);
      log.debugf("Killing node %s. Key %s is located on %s", address(nodeToKill), k1, keyOwners);
      log.debugf("Data on node %s: %s", address(1), cache(1).keySet());
      log.debugf("Data on node %s: %s", address(2), cache(2).keySet());

      // Now that we know which node to kill, allow the START_STATE_TRANSFER command to proceed.
      // The corresponding StateResponseCommand will be blocked on cache 0
      checkPoint.await("IN_START_STATE_TRANSFER_" + address(liveNode), 1, SECONDS);
      checkPoint.trigger("OUT_START_STATE_TRANSFER_" + address(liveNode));

      // Kill cache cacheToStop to force a topology update.
      // The topology update will remove the transfers from cache(nodeToKill).
      cache(nodeToKill).stop();

      // Now allow cache 0 to process the state from cache(liveNode)
      checkPoint.awaitStrict("IN_RESPONSE_" + address(liveNode), 10, SECONDS);
      checkPoint.trigger("OUT_RESPONSE_" + address(liveNode));

      log.debugf("Received segments?");
      Thread.sleep(1000);

      // Wait for cache 0 to request the transactions for the failed segments from cache 1
      checkPoint.awaitStrict("IN_GET_TRANSACTIONS_" + address(liveNode), 10, SECONDS);
      checkPoint.trigger("OUT_GET_TRANSACTIONS_" + address(liveNode));

      // ISPN-3120: Now cache 0 should think it finished receiving state. Allow all the commands to proceed.
      checkPoint.awaitStrict("IN_START_STATE_TRANSFER_" + address(liveNode), 10, SECONDS);
      checkPoint.trigger("OUT_START_STATE_TRANSFER_" + address(liveNode));

      checkPoint.awaitStrict("IN_RESPONSE_" + address(liveNode), 10, SECONDS);
      checkPoint.trigger("OUT_RESPONSE_" + address(liveNode));

      TestingUtil.waitForRehashToComplete(cache(0), cache(liveNode));

      log.debugf("Final checkpoint status: %s", checkPoint);
      DataContainer dataContainer = TestingUtil.extractComponent(cache(0), DataContainer.class);
      assertTrue(dataContainer.containsKey(k1, null));
   }

   private void replaceInvocationHandler(final CheckPoint checkPoint, final EmbeddedCacheManager manager,
                                         Class<? extends CacheRpcCommand> commandClass)
         throws Throwable {
      final InboundInvocationHandler handler = TestingUtil.extractGlobalComponent(manager,
            InboundInvocationHandler.class);
      InboundInvocationHandler mockHandler = mock(InboundInvocationHandler.class);
      doAnswer(new Answer<Object>() {
         @Override
         public Object answer(InvocationOnMock invocation) throws Throwable {
            CacheRpcCommand command = (CacheRpcCommand) invocation.getArguments()[0];
            Address source = (Address) invocation.getArguments()[1];
            Response response = (Response) invocation.getArguments()[2];
            if (command instanceof StateRequestCommand && source.equals(address(0))) {
               StateRequestCommand stateRequestCommand = (StateRequestCommand) command;
               checkPoint.trigger("IN_" + stateRequestCommand.getType() + '_' + manager.getAddress());
               checkPoint.awaitStrict("OUT_" + stateRequestCommand.getType() + '_' + manager.getAddress(), 5,
                                      SECONDS);
            } else if (command instanceof StateResponseCommand && manager.getAddress().equals(address(0))) {
               checkPoint.trigger("IN_RESPONSE_" + source);
               checkPoint.awaitStrict("OUT_RESPONSE_" + source, 5, SECONDS);
            }
            handler.handle(command, source, response);
            return null;
         }
      }).when(mockHandler).handle(any(commandClass), any(Address.class), any(Response.class));
      TestingUtil.replaceComponent(manager, InboundInvocationHandler.class, mockHandler, true);
      Transport transport = TestingUtil.extractGlobalComponent(manager, Transport.class);
      CommandAwareRpcDispatcher dispatcher = (CommandAwareRpcDispatcher) TestingUtil.extractField(transport, "dispatcher");
      TestingUtil.replaceField(mockHandler, "inboundInvocationHandler", dispatcher, CommandAwareRpcDispatcher.class);
   }
}


text:
import argparse
import sys
import time

from bcc import BPF

BPF_SRC = """
#include <linux/ip.h>
#include <linux/ipv6.h>
#include <linux/tcp.h>
#include <linux/netfilter.h>
#include <net/ip.h>
#include <uapi/linux/bpf.h>

static struct tcphdr *skb_to_tcphdr(const struct sk_buff *skb)
{
    // unstable API. verify logic in tcp_hdr() -> skb_transport_header().
    return (struct tcphdr *)(skb->head + skb->transport_header);
}

static inline struct iphdr *skb_to_iphdr(const struct sk_buff *skb)
{
    // unstable API. verify logic in ip_hdr() -> skb_network_header().
    return (struct iphdr *)(skb->head + skb->network_header);
}

static inline struct ipv6hdr *skb_to_ip6hdr(const struct sk_buff *skb)
{
    // unstable API. verify logic in ip_hdr() -> skb_network_header().
    return (struct ipv6hdr *)(skb->head + skb->network_header);
}

// for correlating between kprobe and kretprobe
struct start_data {
    u8 hook;
    u8 pf; // netfilter protocol
    u8 tcp_state;
    u64 ts;
};
BPF_PERCPU_ARRAY(sts, struct start_data, 1);

// the histogram keys
typedef struct nf_lat_key {
    u8 proto; // see netfilter.h
    u8 hook;
    u8 tcp_state;
} nf_lat_key_t;

typedef struct hist_key {
    nf_lat_key_t key;
    u64 slot;
} hist_key_t;
BPF_HISTOGRAM(dist, hist_key_t);

int kprobe__nf_hook_slow(struct pt_regs *ctx, struct sk_buff *skb, struct nf_hook_state *state) {
    struct start_data data = {};
    data.ts = bpf_ktime_get_ns();
    data.hook = state->hook;
    data.pf = state->pf;

    COND

    u8 ip_proto;
    if (skb->protocol == htons(ETH_P_IP)) {
        struct iphdr *ip = skb_to_iphdr(skb);
        ip_proto = ip->protocol;

    } else if (skb->protocol == htons(ETH_P_IPV6)) {
        struct ipv6hdr *ip = skb_to_ip6hdr(skb);
        ip_proto = ip->nexthdr;
    }

    data.tcp_state = 0;
    if (ip_proto == 0x06) { //tcp
        struct tcphdr *tcp = skb_to_tcphdr(skb);
        u8 tcpflags = ((u_int8_t *)tcp)[13];

        // FIN or RST
        if (((tcpflags & 1) + (tcpflags & 4)) > 0) {
            data.tcp_state = 3;
        }
        // SYN / SACK
        else if ((tcpflags & 0x02) > 0) {
            data.tcp_state = 1;
            if ((tcpflags & 16) > 0) { // ACK
                data.tcp_state = 2;
            }
        }
    }

    u32 idx = 0;
    sts.update(&idx, &data);
    return 0;
}

int kretprobe__nf_hook_slow(struct pt_regs *ctx) {
    u32 idx = 0;
    struct start_data *s;
    s = sts.lookup(&idx);
    if (!s || s->ts == 0) {
        return 0;
    }

    s->ts = bpf_ktime_get_ns() - s->ts;

    hist_key_t key = {};
    key.key.hook = s->hook;
    key.key.proto = s->pf;
    key.key.tcp_state = s->tcp_state;
    key.slot = bpf_log2l(s->ts / FACTOR );
    dist.increment(key);

    s->ts = 0;
    sts.update(&idx, s);

    return 0;
}
"""

# constants from netfilter.h
NF_HOOKS = {
    0: "PRE_ROUTING",
    1: "LOCAL_IN",
    2: "FORWARD",
    3: "LOCAL_OUT",
    4: "POST_ROUTING",
}

NF_PROTOS = {
    0: "UNSPEC",
    1: "INET",
    2: "IPV4",
    3: "ARP",
    5: "NETDEV",
    7: "BRIDGE",
    10: "IPV6",
    12: "DECNET",
}

TCP_FLAGS = {
    0: "other",
    1: "SYN",
    2: "SACK",
    3: "FIN",
}

EXAMPLES = """examples:
    nflatency                   # print netfilter latency histograms, 1 second refresh
    nflatency -p IPV4 -p IPV6   # print only for ipv4 and ipv6
    nflatency -k PRE_ROUTING    # only record the PRE_ROUTING hook
    nflatency -i 5 -d 10        # run for 10 seconds, printing every 5
"""

parser = argparse.ArgumentParser(
    description="Track latency added by netfilter hooks. Where possible, interesting TCP flags are included",
    formatter_class=argparse.RawDescriptionHelpFormatter,
    epilog=EXAMPLES)
parser.add_argument("-p", "--proto",
                    action='append',
                    help="record this protocol only (multiple parameters allowed)",
                    choices=NF_PROTOS.values())
parser.add_argument("-k", "--hook",
                    action='append',
                    help="record this netfilter hook only (multiple parameters allowed)",
                    choices=NF_HOOKS.values())
parser.add_argument("-i", "--interval", type=int,
                    help="summary interval, in seconds. Default is 10, unless --duration is supplied")
parser.add_argument("-d", "--duration", type=int,
                    help="total duration of trace, in seconds")
parser.add_argument("--nano", action="store_true",
                    help="bucket by nanoseconds instead of milliseconds")

def main():
    args = parser.parse_args()

    src = build_src(args)
    b = BPF(text=src)
    dist = b.get_table("dist")

    seconds = 0
    interval = 0
    if not args.interval:
        interval = 1
        if args.duration:
            interval = args.duration
    else:
        interval = args.interval

    sys.stderr.write("Tracing netfilter hooks... Hit Ctrl-C to end.\n")
    while 1:
        try:
            dist.print_log2_hist(
                section_header="Bucket",
                bucket_fn=lambda k: (k.proto, k.hook, k.tcp_state),
                section_print_fn=bucket_desc)
            if args.duration and seconds >= args.duration:
                sys.exit(0)
            seconds += interval
            time.sleep(interval)
        except KeyboardInterrupt:
            sys.exit(1)

def build_src(args):
    cond_src = ""
    if args.proto:
        predicate = " || ".join(map(lambda x: "data.pf == NFPROTO_%s" % x, args.proto))
        cond_src = "if (!(%s)) { return 0; }\n" % predicate
    if args.hook:
        predicate = " || ".join(map(lambda x: "data.hook == NF_INET_%s" % x, args.hook))
        cond_src = "%s    if (!(%s)) { return 0;}\n" % (cond_src, predicate)

    factor = "1000"
    if args.nano:
        factor = "1"

    return BPF_SRC.replace('COND', cond_src).replace('FACTOR', factor)

def bucket_desc(bucket):
    return "%s %s (tcp %s)" % (
        NF_PROTOS[bucket[0]],
        NF_HOOKS[bucket[1]],
        TCP_FLAGS[bucket[2]])

if __name__ == "__main__":
    main()


text:
This directory contains that code behind that yawast.org web site. This site is hosted on Github Pages, and is built using Jekyll.

Prior to making any changes, please make sure you take a look at our [CONTRIBUTING](https://github.com/adamcaudill/yawast/blob/master/CONTRIBUTING.md) document.

You can easily run the site locally using following command (after using `bundle install` to fetch the needed dependencies).

```
bundle exec jekyll serve
```


text:
package com.google.cloud.dialogflow.v2beta1.samples;

// [START dialogflow_v2beta1_generated_intentsclient_getintent_sync]
import com.google.cloud.dialogflow.v2beta1.GetIntentRequest;
import com.google.cloud.dialogflow.v2beta1.Intent;
import com.google.cloud.dialogflow.v2beta1.IntentName;
import com.google.cloud.dialogflow.v2beta1.IntentView;
import com.google.cloud.dialogflow.v2beta1.IntentsClient;

public class SyncGetIntent {

  public static void main(String[] args) throws Exception {
    syncGetIntent();
  }

  public static void syncGetIntent() throws Exception {
    // This snippet has been automatically generated and should be regarded as a code template only.
    // It will require modifications to work:
    // - It may require correct/in-range values for request initialization.
    // - It may require specifying regional endpoints when creating the service client as shown in
    // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
    try (IntentsClient intentsClient = IntentsClient.create()) {
      GetIntentRequest request =
          GetIntentRequest.newBuilder()
              .setName(IntentName.ofProjectIntentName("[PROJECT]", "[INTENT]").toString())
              .setLanguageCode("languageCode-2092349083")
              .setIntentView(IntentView.forNumber(0))
              .build();
      Intent response = intentsClient.getIntent(request);
    }
  }
}
// [END dialogflow_v2beta1_generated_intentsclient_getintent_sync]


text:
<?php
namespace WS\Mitglieder\Controller;

/*
 * This file is part of the WS.Mitglieder package.
 */

use Neos\Flow\Annotations as Flow;
use Neos\Flow\Mvc\Controller\ActionController;

use Neos\Error\Messages\Error;
use Neos\Error\Messages\Message;

use WS\Organisation\Domain\Model\ElectoralOffice;

class WahlamtstraegerController extends ActionController {

	/**
	 * @Flow\Inject
	 * @var \WS\Organisation\Domain\Repository\ElectoralOfficeRepository
	 */
	protected $electoralOfficeRepository;

	/**
	 * @Flow\Inject
	 * @var \WS\Organisation\Domain\Repository\ElectoralOfficeTypeRepository
	 */
	protected $electoralOfficeTypeRepository;

	/**
	 * @Flow\Inject
	 * @var \WS\Mitglieder\Domain\Repository\MemberRepository
	 */
	protected $memberRepository;

	/**
	 * @Flow\Inject
	 * @var \WS\Organisation\Domain\Repository\UnitRepository
	 */
	protected $unitRepository;

	/**
	 * @return void
	 */
	public function indexAction() {
		$this->view->assign('electoralOffices', $this->electoralOfficeRepository->findAll());
	}

	/**
	 * @param ElectoralOffice $electoralOffice
	 * @return void
	 */
	public function detailsAction(ElectoralOffice $electoralOffice) {
		$this->view->assign('electoralOffice', $electoralOffice);
	}

	/**
	 * @return void
	 */
	public function neuAction() {

		if($this->electoralOfficeTypeRepository->countAll() == 0) {
			$this->addFlashMessage('Noch keine Wahlämter angelegt.', 'Hinweis:', Message::SEVERITY_NOTICE);
			$this->redirect('index', 'Wahlaemter', 'WS.Organisation');
		}

		$this->view->assign('electoralOfficeTypes', $this->electoralOfficeTypeRepository->findAll());
		$this->view->assign('members', $this->memberRepository->findActive());
		$this->view->assign('units', $this->unitRepository->findAll());

	}

	/**
	 * @return void
	 */
	public function initializeEintragenAction() {
		$this->arguments['newElectoralOffice']
			->getPropertyMappingConfiguration()
			->forProperty('entryDate')
			->setTypeConverterOption(
				'Neos\Flow\Property\TypeConverter\DateTimeConverter',
				\Neos\Flow\Property\TypeConverter\DateTimeConverter::CONFIGURATION_DATE_FORMAT,
				'd.m.Y'
			);
		$this->arguments['newElectoralOffice']
			->getPropertyMappingConfiguration()
			->forProperty('resignationDate')
			->setTypeConverterOption(
				'Neos\Flow\Property\TypeConverter\DateTimeConverter',
				\Neos\Flow\Property\TypeConverter\DateTimeConverter::CONFIGURATION_DATE_FORMAT,
				'd.m.Y'
			);
	}

	/**
	 * @param ElectoralOffice $newElectoralOffice
	 * @return void
	 */
	public function eintragenAction(ElectoralOffice $newElectoralOffice) {

		$entryDate = $newElectoralOffice->getEntryDate();
		$entryDate->setTime(0, 0, 0);
		$newElectoralOffice->setEntryDate($entryDate);

		$resignationDate = $newElectoralOffice->getResignationDate();
		if($resignationDate !== null) {
			$resignationDate->setTime(0, 0, 0);
			$newElectoralOffice->setResignationDate($resignationDate);
		}

		$this->electoralOfficeRepository->add($newElectoralOffice);

		$this->addFlashMessage('Wahlamtsträger'.($newElectoralOffice->getMember()->getGender() == 2 ? 'in' : '').' angelegt.');
		$this->redirect('index');

	}

	/**
	 * @param ElectoralOffice $electoralOffice
	 * @return void
	 */
	public function bearbeitenAction(ElectoralOffice $electoralOffice) {
		$this->view->assign('electoralOfficeTypes', $this->electoralOfficeTypeRepository->findAll());
		$this->view->assign('electoralOffice', $electoralOffice);
		$this->view->assign('members', $this->memberRepository->findActive());
		$this->view->assign('units', $this->unitRepository->findAll());
	}

	/**
	 * @return void
	 */
	public function initializeAktualisierenAction() {
		$this->arguments['electoralOffice']
			->getPropertyMappingConfiguration()
			->forProperty('entryDate')
			->setTypeConverterOption(
				'Neos\Flow\Property\TypeConverter\DateTimeConverter',
				\Neos\Flow\Property\TypeConverter\DateTimeConverter::CONFIGURATION_DATE_FORMAT,
				'd.m.Y'
			);
		$this->arguments['electoralOffice']
			->getPropertyMappingConfiguration()
			->forProperty('resignationDate')
			->setTypeConverterOption(
				'Neos\Flow\Property\TypeConverter\DateTimeConverter',
				\Neos\Flow\Property\TypeConverter\DateTimeConverter::CONFIGURATION_DATE_FORMAT,
				'd.m.Y'
			);
	}

	/**
	 * @param ElectoralOffice $electoralOffice
	 * @return void
	 */
	public function aktualisierenAction(ElectoralOffice $electoralOffice) {

		$entryDate = $electoralOffice->getEntryDate();
		$entryDate->setTime(0, 0, 0);
		$electoralOffice->setEntryDate($entryDate);

		$resignationDate = $electoralOffice->getResignationDate();
		if($resignationDate !== null) {
			$resignationDate->setTime(0, 0, 0);
			$electoralOffice->setResignationDate($resignationDate);
		}

		$this->electoralOfficeRepository->update($electoralOffice);

		$this->addFlashMessage('Wahlamtsträger'.($electoralOffice->getMember()->getGender() == 2 ? 'in' : '').' aktualisiert.');
		$this->redirect('index');

	}

	/**
	 * @param ElectoralOffice $electoralOffice
	 * @return void
	 */
	public function loeschenAction(ElectoralOffice $electoralOffice) {
		$this->electoralOfficeRepository->remove($electoralOffice);
		$this->addFlashMessage('Wahlamtsträger'.($newElectoralOffice->getMember()->getGender() == 2 ? 'in' : '').' gelöscht.');
		$this->redirect('index');
	}

	/**
	 * @return Error
	 */
	protected function getErrorFlashMessage() {
		switch ($this->actionMethodName) {
			case 'eintragenAction' :
				return new Error('Wahlamtsträger*in konnte nicht angelegt werden, bitte markierte Felder überprüfen!', NULL, array(), 'Fehler:');
			case 'aktualisierenAction' :
				return new Error('Wahlamtsträger*in konnte nicht aktualisiert werden, bitte markierte Felder überprüfen!', NULL, array(), 'Fehler:');
			default:
				return parent::getErrorFlashMessage();
		}
	}

}


text:
<?php
namespace Cakephp3Bulker\Model\Entity;

use Cake\ORM\Entity;

/**
 * Dummy Entity
 *
 * @property int $id
 * @property string $name
 * @property \Cake\I18n\FrozenTime $created
 * @property \Cake\I18n\FrozenTime $modified
 */
class Dummy extends Entity
{

    /**
     * Fields that can be mass assigned using newEntity() or patchEntity().
     *
     * Note that when '*' is set to true, this allows all unspecified fields to
     * be mass assigned. For security purposes, it is advised to set '*' to false
     * (or remove it), and explicitly make individual fields accessible as needed.
     *
     * @var array
     */
    protected $_accessible = [
        '*' => true,
        'id' => false
    ];
}


text:
module.exports = {
    controller: require('./controller.js'),
    view: require('./view.js')
};


text:
import U from './u.js';
import Sprite from './sprite.js';

// direction, rate, spread, sprite options
var SpriteEmitter = function( controller, options ) {
  this.controller = controller;
  this.last_emit = this.controller.ticks;

  this.x = U.default_param( options.x, 0 );
  this.y = U.default_param( options.y, 0 );

  this.rate = U.default_param( options.rate, 60 ); // 60fps, 1s.
  this.concurrency = U.default_param( options.concurrency, 1 ); // one at a time

  this.tags = U.default_param( options.tags, [] );

  this.max = U.default_param( options.max, 10 );
  this.count = 0;

  this.angle = U.default_param( options.angle, -90 );
  this.speed = U.default_param( options.speed, 20 );

  this.splay = U.default_param( options.splay, 0 ) ;
  this.speed_splay = U.default_param( options.speed_splay, 0 );

  this.life = U.default_param( options.life, 3000 );

  this.elementClass = U.default_param( options.elementClass, 'dick' );
};

SpriteEmitter.prototype.setMessageBus = function( new_message_bus ) {
  // TODO: unsubscribe from existing message bus

  this.message_bus = new_message_bus;
  this.message_bus.subscribe( 'step_frame', this.signal.bind(this) );
}

SpriteEmitter.prototype.signal = function() {

  // console.log( { c: this.controller.ticks, le: this.last_emit, r: this.rate} )

  if ( this.controller.ticks > (this.last_emit + this.rate) ) {
    this.emit();
  }
}

SpriteEmitter.prototype.emit = function() {
  if ( this.count >= this.max ) {
    return;
  }

  var i = 0;
  for ( i = 0; i < this.concurrency; i++ ) {
    var element = document.createElement('div');
    element.setAttribute('class', this.elementClass);
    // this.controller.element.appendChild( element );

    var sprite = new Sprite( element, { x:this.x, y:this.y, use_rotation:true, tags: this.tags } );

    var splay_angle = this.angle + ( Math.random() * this.splay ) - ( this.splay / 2 );
    var splay_speed = this.speed + ( Math.random() * this.speed_splay ) - ( this.speed_splay / 2 );

    sprite.setAngle( splay_angle, splay_speed );
    sprite.life = this.life;

    this.controller.addSprite( sprite );

    this.count++;
  }

  this.last_emit = this.controller.ticks;
}

export default SpriteEmitter;


text:
import AuthenticatedRoute from 'ghost-admin/routes/authenticated';
import {inject as service} from '@ember/service';

export default AuthenticatedRoute.extend({
    mediaQueries: service(),

    beforeModel() {
        let firstTag = this.modelFor('settings.tags').get('firstObject');

        this._super(...arguments);

        if (firstTag && !this.get('mediaQueries.maxWidth600')) {
            this.transitionTo('settings.tags.tag', firstTag);
        }
    }
});


text:
#include "config.h"
#include "BaseClickableWithKeyInputType.h"

#include "HTMLInputElement.h"
#include "KeyboardEvent.h"

namespace WebCore {

using namespace HTMLNames;

void BaseClickableWithKeyInputType::handleKeydownEvent(HTMLInputElement& element, KeyboardEvent& event)
{
    const String& key = event.keyIdentifier();
    if (key == "U+0020") {
        element.setActive(true, true);
        // No setDefaultHandled(), because IE dispatches a keypress in this case
        // and the caller will only dispatch a keypress if we don't call setDefaultHandled().
    }
}

void BaseClickableWithKeyInputType::handleKeypressEvent(HTMLInputElement& element, KeyboardEvent& event)
{
    int charCode = event.charCode();
    if (charCode == '\r') {
        element.dispatchSimulatedClick(&event);
        event.setDefaultHandled();
        return;
    }
    if (charCode == ' ') {
        // Prevent scrolling down the page.
        event.setDefaultHandled();
    }
}

void BaseClickableWithKeyInputType::handleKeyupEvent(InputType& inputType, KeyboardEvent& event)
{
    const String& key = event.keyIdentifier();
    if (key != "U+0020")
        return;
    // Simulate mouse click for spacebar for button types.
    inputType.dispatchSimulatedClickIfActive(event);
}

// FIXME: Could share this with BaseCheckableInputType and RangeInputType if we had a common base class.
void BaseClickableWithKeyInputType::accessKeyAction(HTMLInputElement& element, bool sendMouseEvents)
{
    element.dispatchSimulatedClick(0, sendMouseEvents ? SendMouseUpDownEvents : SendNoEvents);
}

void BaseClickableWithKeyInputType::handleKeydownEvent(KeyboardEvent& event)
{
    handleKeydownEvent(element(), event);
}

void BaseClickableWithKeyInputType::handleKeypressEvent(KeyboardEvent& event)
{
    handleKeypressEvent(element(), event);
}

void BaseClickableWithKeyInputType::handleKeyupEvent(KeyboardEvent& event)
{
    handleKeyupEvent(*this, event);
}

void BaseClickableWithKeyInputType::accessKeyAction(bool sendMouseEvents)
{
    InputType::accessKeyAction(sendMouseEvents);
    accessKeyAction(element(), sendMouseEvents);
}

} // namespace WebCore


text:
  Ville-la-Grand est
      une ville située dans le département de Haute-Savoie en Rhône-Alpes. Elle comptait 6 955 habitants en 2008.

À Ville-la-Grand le salaire médian mensuel par individu se situe à approximativement 1 927 €  net. C'est au dessous de la moyenne du pays.

Le parc de logements, à Ville-la-Grand, était réparti en 2011 en 2 419 appartements et 1 441 maisons soit
une légère domination des appartements .

La ville offre quelques  aménagements, elle propose entre autres un terrain de tennis et un terrain de sport.

À Ville-la-Grand, la valorisation moyenne à la vente d'un appartement se situe à 4 060 € du m² en vente. La valeur moyenne d'une maison à l'achat se situe à 4 062 € du m². À la location le prix moyen se situe à 14,9 € du m² mensuel.

À coté de Ville-la-Grand sont situées les villes de
Arthaz-Pont-Notre-Dame à 4 km, 1 240 habitants,
Annemasse localisée à 1 km, 28 572 habitants,
Ambilly localisée à 2 km, 5 728 habitants,
Étrembières située à 3 km, 1 639 habitants,
Vétraz-Monthoux située à 3 km, 6 141 habitants,
Cranves-Sales à 3 km, 4 973 habitants,
 entre autres. De plus, Ville-la-Grand est située à seulement 25 km de Thonon-les-Bains.

La localité dispose s'agissant de des études de deux collèges et un lycée.
Concernant les très jeunes, la ville est pourvue pour le bien être de sa population de deux maternelles et trois écoles primaires.
Ville-la-Grand est équipée des  installations permettant une vie locale facilitée.
Lors d'un projet d'acheter un appartement ou une maison à Ville-la-Grand, il est important évaluer la qualité des équipements éducatifs


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycotaxon 12(2): 341 (1981)

#### Original name
Helotium fuscobrunneum Pat. & Gaillard

### Remarks
null


text:
@interface JMCShapeView : UIView <UIGestureRecognizerDelegate> {
    CGContextRef ctx;
    NSMutableArray *history;
}

@property (nonatomic, retain) NSMutableArray *shapes;
@property (nonatomic, retain) NSMutableArray *history;

- (void)clear;
- (void)undo;
- (void)redo;

@end


text:
---
uid: Lucene.Net.Codecs.Compressing
summary: *content
---

<!--
 Licensed to the Apache Software Foundation (ASF) under one or more
 contributor license agreements.  See the NOTICE file distributed with
 this work for additional information regarding copyright ownership.
 The ASF licenses this file to You under the Apache License, Version 2.0
 (the "License"); you may not use this file except in compliance with
 the License.  You may obtain a copy of the License at

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

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

StoredFieldsFormat that allows cross-document and cross-field compression of stored fields.


text:
/**
* Class for aggregating WebpageScrapers and
* parsing web content as a whole.
* In addition, provides broader settings functionality.
*
* Parser initially fetches the index page and gradually
* travels to all the pages on the website, for which the
* Webpage Parser is provided and its url is successfully tested
* by the regular expression, attached to Webpage Parser.
*
* @class
*/

const SHAMELESS_ANCHOR_TAG_PARSER_PREFIX = '__SHAMELESS_ANCHOR_TAG__'

/*
* Element Parser used to decorate supplied user parsers for crawling purposes.
* This parser determines how Shameless should get list of links from a page in
* order to continue the crawling process.
*/
const anchorElementParser = {
  selector: ['a'],
  parserFunc: (elem, info) => ({
    __name__: SHAMELESS_ANCHOR_TAG_PARSER_PREFIX,
    value: elem.attr('href').trim()
  })
}

class WebsiteScraper {
  constructor( name = 'default' ) {
    this.name = name
    this.__pageScrapers__ = {}
    this.__pageRegx__ = {}
    this.__anchorElementParser__ = anchorElementParser

    // TODO: not sure if this is a good idea, probably not :D
    this.__visited__ = []
    this.__tmp_result__ = []
    this.__scrape_count__ = 0
  }

  clearCache() {
    this.__visited__ = []
    this.__tmp_result__ = []
    this.__scrape_count__ = 0
  }

  async scrape ( url, options = {}, depth = 0 ) {
    console.log('Scrape: depth:', depth, 'pages: ', this.__scrape_count__, options, url)
    const {
      maxPages = Number.POSITIVE_INFINITY,
      maxDepthLevel = Number.POSITIVE_INFINITY
    } = options

    let tmpScraper, scraper

    // index page is being parsed, i.e parsing just started
    if ( depth === 0 ) this.clearCache()

    scraper = this.getPageScraper(url)
    if ( !scraper ) {
      console.log(`[${this.name}] No Scraper for page ${url} found`)
      return
    }

    const scrapeResult = await scraper.scrape(url)
    this.__tmp_result__.push(scrapeResult)
    depth++, this.__scrape_count__++

    // check if we reached the scrape boundaries
    if ( depth >= maxDepthLevel || this.__scrape_count__ >= maxPages ) return

    // recursively start scraping other pages
    const links = WebsiteScraper.extractCrawlLinks(scrapeResult)
    const nextLevelData = []
    console.log('Links: ', links)
    for ( let i = 0; i < links.length; i += 1 ) {
      if ( this.__scrape_count__ + i < maxPages ) {
        nextLevelData.push(this.scrape(links[i], options, depth))
      }
      else break
    }
    return await Promise.all(nextLevelData)
  }

  addWebpageScraper( regx, scraper, anchorElementParser = null ) {
    // augment index parser with anchor tags parser in order to
    // continue parsing the website
    WebsiteScraper.decorateWithAnchorParser(
      scraper, anchorElementParser || this.__anchorElementParser__
    )

    this.__pageScrapers__[scraper.name] = scraper
    this.__pageRegx__[scraper.name] = regx

    return this
  }

  getPageScraper( url ) {
    const regxNames = Object.keys(this.__pageRegx__)

    for ( let i = 0; i < regxNames.length; i += 1 )
      if ( this.__pageRegx__[regxNames[i]].test(url) )
        return this.__pageScrapers__[regxNames[i]]

    return null
  }

  static extractCrawlLinks({ content = null }) {
    // TODO: should this be an error?
    if ( !content )
      throw new Error(`[WebsiteScraper] No 'content' field in scraped result`)

    return content
      .filter(c => c.__name__ === SHAMELESS_ANCHOR_TAG_PARSER_PREFIX)
      .map(c => c.value)
  }

  // add Anchor Element parser to every supplied parser object
  static decorateWithAnchorParser( parser, { selector, parserFunc } ) {
    parser.addElementParser(selector, parserFunc)
  }

  static create( name, pageScrapers ) {
    return new WebsiteScraper(name, pageScrapers)
  }
}

// convenience alias
WebsiteScraper.prototype.fetch = WebsiteScraper.prototype.scrape
WebsiteScraper.ANCHOR_TAG_PARSER_PREFIX = SHAMELESS_ANCHOR_TAG_PARSER_PREFIX

module.exports = WebsiteScraper


text:
---
uid: SolidEdgePart.FaceMove.OffsetAlongOrReverseVector
summary:
remarks:
---


text:
![image_squidhome@2x.png](http://i.imgur.com/RIvu9.png)

# sails-raven

Provides easy access to RavenDB from Sails.js & Waterline. Currently a work in progress, see the #Status section below for more detail.

This module is a Waterline/Sails adapter, an early implementation of a rapidly-developing, tool-agnostic data standard.  Its goal is to provide a set of declarative interfaces, conventions, and best-practices for integrating with all sorts of data sources.  Not just databases-- external APIs, proprietary web services, or even hardware.

Strict adherence to an adapter specification enables the (re)use of built-in generic test suites, standardized documentation, reasonable expectations around the API for your users, and overall, a more pleasant development experience for everyone.

### Installation

To install this adapter, run in your sails project root folder:

```sh
$ npm install sails-raven
```

### Usage

```sh
$ node _cleanup.js && npm test
```

```javascript
// Config sample: connections.js
module.exports.connections = {
  ravenDbServer: {
    adapter: 'sails-raven',
    host: 'http://raven.example.com',
    database: 'SomeProjectDatabase',
    port: 8080
  }
};
```

### Development Status
- **WIP** - Completing the base adapter implementation for common CRUD operations
- **TODO** - Create the queryable interface
- **TODO** - Map the queryable interface against lucene/RavenDB HTTP API
- **TODO** - Implement more features of the `Models.Attributes` Waterline API
- **TODO** - Create RavenDB indexes based on the Model Schema

### License

**[MIT](./LICENSE)**

[Sails](http://sailsjs.org) is free and open-source under the [MIT License](http://sails.mit-license.org/).

[RavenDB](http://ravendb.org)


text:
CREATE TABLE [dbo].[Airports] (
    [AirportId]          UNIQUEIDENTIFIER CONSTRAINT [DF_Airports_AirportId] DEFAULT (newid()) NOT NULL,
    [ImportedId]         BIGINT           NOT NULL,
    [Name]               NVARCHAR (255)   NOT NULL,
    [City]               NVARCHAR (255)   NOT NULL,
    [Country]            NVARCHAR (255)   NOT NULL,
    [IataFaa]            NVARCHAR (50)    NOT NULL,
    [ICAO]               NVARCHAR (10)    NOT NULL,
    [Latitude]           NVARCHAR (20)    NOT NULL,
    [Longitude]          NVARCHAR (20)    NOT NULL,
    [Altitude]           NVARCHAR (10)    NOT NULL,
    [Timezone]           NVARCHAR (10)    NOT NULL,
    [DST]                NVARCHAR (255)   NOT NULL,
    [TzDatabaseTimeZone] NVARCHAR (255)   NOT NULL,
    CONSTRAINT [PK_Airports] PRIMARY KEY CLUSTERED ([AirportId] ASC)
);

GO
CREATE UNIQUE NONCLUSTERED INDEX [IX_Airports_1]
    ON [dbo].[Airports]([ImportedId] ASC);


text:
using namespace anysdk::framework;

#define  LOG_TAG    "Ads"
#define  LOGD(...)  __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG,__VA_ARGS__);
extern "C"{
void Java_com_anysdk_sample_wrapper_nativeShowAds(JNIEnv*  env, jobject thiz, jint type, jint index)
{
	Ads::getInstance()->showAds(type, index);
}
void Java_com_anysdk_sample_wrapper_nativeHideAds(JNIEnv*  env, jobject thiz, jint type, jint index)
{
	Ads::getInstance()->hideAds(type, index);
}

void Java_com_anysdk_sample_wrapper_nativePreloadAds(JNIEnv*  env, jobject thiz, jint type, jint index)
{
	Ads::getInstance()->preloadAds(type, index);
}

void Java_com_anysdk_sample_wrapper_nativeSpendPoints(JNIEnv*  env, jobject thiz)
{
	Ads::getInstance()->spendPoints();
}

jfloat Java_com_anysdk_sample_wrapper_nativeQueryPoints(JNIEnv*  env, jobject thiz)
{
	return (jfloat)Ads::getInstance()->queryPoints();
}
}

Ads* Ads::_pInstance = NULL;

Ads::Ads()
{
	_pAds = AgentManager::getInstance()->getAdsPlugin();
	if(!_pAds) return;

	_pAds->setAdsListener(this);
}

Ads::~Ads()
{

}

Ads* Ads::getInstance()
{
    if (_pInstance == NULL) {
        _pInstance = new Ads();
    }
    return _pInstance;
}

void Ads::purge()
{
    if (_pInstance)
    {
        delete _pInstance;
        _pInstance = NULL;
    }
}

void Ads::onAdsResult(AdsResultCode code, const char* msg)
{
	LOGD("adsCallback %d,%s",code, msg);
	switch(code)
	{
	case kAdsReceived://广告接受成功回调

		break;
	case kAdsShown://广告展示回调

		break;
	case kAdsDismissed://广告消失回调

		break;
	case kPointsSpendSucceed://积分设置成功回调

		break;
	case kPointsSpendFailed://积分设置失败回调

		break;
	case kNetworkError://网络错误回调

		break;
	case kUnknownError://未知错误回调

		break;
	case kOfferWallOnPointsChanged://积分改变回调

		break;
	default:
		break;
	}

}

void Ads::showAds(int type,int index)
{
	LOGD("showAds");
	if(!_pAds || !(_pAds->isAdTypeSupported((AdsType)type))) return;
	_pAds->showAds((AdsType)type, index);

}

void Ads::hideAds(int type,int index)
{
	if(!_pAds || !(_pAds->isAdTypeSupported((AdsType)type))) return;
	_pAds->hideAds((AdsType)type, index);
}
void Ads::preloadAds(int type,int index)
{
	if(!_pAds || !(_pAds->isAdTypeSupported((AdsType)type))) return;
	_pAds->preloadAds((AdsType)type, index);
}

void Ads::spendPoints()
{
	if(!_pAds) return;
	_pAds->spendPoints(100);
}

float Ads::queryPoints()
{
	if(!_pAds) return -1.0;
	return _pAds->queryPoints();
}


text:
from __future__ import print_function

__metaclass__ = type

import os
import sys

from effect import (
    ComposedDispatcher,
    Effect,
    TypeDispatcher,
    base_dispatcher,
    sync_perform,
    sync_performer,
    )
import testtools

class Print:
    def __init__(self, line):
        self.line = line

@sync_performer
def real_print(dispatcher, print_):
    print(print_.line)
    sys.stdout.flush()

real_interpreter = ComposedDispatcher([
    TypeDispatcher({
        Print: real_print,
        }),
    base_dispatcher])

def program():
    return Effect(Print('What... is your quest?'))

if __name__ == '__main__':
    sync_perform(real_interpreter, program())

class Tests(testtools.TestCase):

    def test_print(self):
        outputs = []
        @sync_performer
        def perform_print(dispatcher, print_):
            outputs.append(print_.line)

        test_interpreter = ComposedDispatcher([
            TypeDispatcher({
                Print: perform_print,
                }),
            base_dispatcher])

        dispatcher = test_interpreter
        sync_perform(dispatcher, program())
        self.assertEqual(["What... is your quest?"], outputs)


text:
package test.dataprovider;

import org.testng.annotations.Test;

public class InnexistentDataProviderSample {

  @Test(dataProvider = "doesnotexist")
  public void testMethod(String s) {}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<example name="cmt" category="driver_examples" board_ref="FRDM_K66F" version="1.0.0" format_version="2.1">
  <source path="CMSIS/Include" target_path="CMSIS/Include" type="c_include">
    <files mask="arm_common_tables.h"/>
    <files mask="arm_const_structs.h"/>
    <files mask="arm_math.h"/>
    <files mask="cmsis_armcc.h"/>
    <files mask="cmsis_armcc_V6.h"/>
    <files mask="cmsis_gcc.h"/>
    <files mask="core_cm0.h"/>
    <files mask="core_cm0plus.h"/>
    <files mask="core_cm3.h"/>
    <files mask="core_cm4.h"/>
    <files mask="core_cm7.h"/>
    <files mask="core_cmFunc.h"/>
    <files mask="core_cmInstr.h"/>
    <files mask="core_cmSimd.h"/>
    <files mask="core_sc000.h"/>
    <files mask="core_sc300.h"/>
  </source>
  <source path="boards/frdmk66f/driver_examples/cmt" target_path="sources" type="c_include">
    <files mask="board.h"/>
    <files mask="clock_config.h"/>
    <files mask="pin_mux.h"/>
  </source>
  <source path="boards/frdmk66f/driver_examples/cmt" target_path="doc" type="doc">
    <files mask="readme.txt"/>
  </source>
  <source path="boards/frdmk66f/driver_examples/cmt" target_path="sources" type="src">
    <files mask="board.c"/>
    <files mask="clock_config.c"/>
    <files mask="cmt.c"/>
    <files mask="pin_mux.c"/>
  </source>
  <source path="devices/MK66F18/arm" target_path="devices/arm" type="asm_include" compiler="arm">
    <files mask="startup_MK66F18.s"/>
  </source>
  <source path="devices/MK66F18/drivers" target_path="drivers" type="c_include">
    <files mask="fsl_clock.h"/>
    <files mask="fsl_cmt.h"/>
    <files mask="fsl_common.h"/>
    <files mask="fsl_flash.h"/>
    <files mask="fsl_gpio.h"/>
    <files mask="fsl_lpuart.h"/>
    <files mask="fsl_port.h"/>
    <files mask="fsl_smc.h"/>
    <files mask="fsl_uart.h"/>
  </source>
  <source path="devices/MK66F18/drivers" target_path="drivers" type="src">
    <files mask="fsl_clock.c"/>
    <files mask="fsl_cmt.c"/>
    <files mask="fsl_common.c"/>
    <files mask="fsl_flash.c"/>
    <files mask="fsl_gpio.c"/>
    <files mask="fsl_lpuart.c"/>
    <files mask="fsl_smc.c"/>
    <files mask="fsl_uart.c"/>
  </source>
  <source path="devices/MK66F18/gcc" target_path="devices/gcc" type="asm_include" compiler="gcc">
    <files mask="startup_MK66F18.S"/>
  </source>
  <source path="devices/MK66F18/iar" target_path="devices/iar" type="asm_include" compiler="iar">
    <files mask="startup_MK66F18.s"/>
  </source>
  <source path="devices/MK66F18/utilities" target_path="utilities" type="c_include">
    <files mask="fsl_debug_console.h"/>
  </source>
  <source path="devices/MK66F18/utilities" target_path="utilities" type="src">
    <files mask="fsl_debug_console.c"/>
  </source>
  <source path="devices/MK66F18" target_path="devices" type="c_include">
    <files mask="MK66F18.h"/>
    <files mask="MK66F18_features.h"/>
    <files mask="fsl_device_registers.h"/>
    <files mask="system_MK66F18.h"/>
  </source>
  <source path="devices/MK66F18" target_path="devices" type="src">
    <files mask="system_MK66F18.c"/>
  </source>
  <include_paths>
    <include path="CMSIS/Include"/>
    <include path="devices/arm" compiler="arm"/>
    <include path="devices/gcc" compiler="gcc"/>
    <include path="devices/iar" compiler="iar"/>
    <include path="devices"/>
    <include path="drivers"/>
    <include path="sources"/>
    <include path="utilities"/>
  </include_paths>
</example>


text:
package org.apache.nifi.jasn1.convert.converters;

import com.beanit.asn1bean.ber.types.BerBoolean;
import com.beanit.asn1bean.ber.types.BerType;
import org.apache.nifi.jasn1.convert.JASN1Converter;
import org.apache.nifi.jasn1.convert.JASN1TypeAndValueConverter;
import org.apache.nifi.serialization.record.DataType;
import org.apache.nifi.serialization.record.RecordFieldType;

public class BerBooleanConverter implements JASN1TypeAndValueConverter {
    @Override
    public boolean supportsType(Class<?> berType) {
        return BerBoolean.class.isAssignableFrom(berType);
    }

    @Override
    public DataType convertType(Class<?> berType, JASN1Converter converter) {
        return RecordFieldType.BOOLEAN.getDataType();
    }

    @Override
    public boolean supportsValue(BerType value, DataType dataType) {
        return value instanceof BerBoolean;
    }

    @Override
    public Object convertValue(BerType value, DataType dataType, JASN1Converter converter) {
        final BerBoolean berValue = (BerBoolean) value;

        return berValue.value;
    }
}


text:
@interface ConditionString : Condition

- (instancetype)initWithFieldName:(NSString *)fieldName equalToString:(NSString *)string;
- (instancetype)initWithFieldName:(NSString *)fieldName likeToPattern:(NSString *)pattern;

@end


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout android:layout_width="fill_parent" android:layout_height="fill_parent"
  xmlns:android="http://schemas.android.com/apk/res/android">
    <LinearLayout android:layout_gravity="center" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="wrap_content"
      xmlns:android="http://schemas.android.com/apk/res/android">
        <ImageView android:layout_gravity="center" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_article_error" />
        <TextView android:textSize="@dimen/play_large_size" android:layout_gravity="center" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/play_article_view_error_message" style="@style/PlayPlainText" />
    </LinearLayout>
</FrameLayout>


text:
.multiple-choice-option-container {
  padding: 4px 0;
}

.multiple-choice-option {
  background: none;
  border: none;
  color: #0d48a1;
  direction: ltr;
  text-align: left;
}

.multiple-choice-radio-button-container {
  display: table-cell;
}

.multiple-choice-content-container {
  display: table-cell;
  padding-left: 12px;
  padding-right: 12px;
  vertical-align: top;
}

.multiple-choice-outer-radio-button {
  border: 2px solid #0d48a1;
  border-radius: 50%;
  display: inline-block;
  height: 16px;
  margin-bottom: -1px;
  width: 16px;
}

.multiple-choice-option.selected .multiple-choice-inner-radio-button {
  background-color: #115fd4;
  border-radius: 50%;
  display: block;
  height: 8px;
  margin: 2px;
  width: 8px;
}

.multiple-choice-option:focus .multiple-choice-outer-radio-button {
  border-color: #115fd4;
}

/* Hover pseudo-class should only be used in desktops because it
 * breaks functionality on mobile.
 */
@media screen and (min-width: 800px) {
  .multiple-choice-option:hover {
    color: #115fd4;
  }

  .multiple-choice-option:hover .multiple-choice-inner-radio-button {
    background-color: #115fd4;
    border-radius: 50%;
    display: block;
    height: 8px;
    margin: 2px;
    width: 8px;
  }

  .multiple-choice-option:hover .multiple-choice-outer-radio-button {
    border-color: #115fd4;
  }
}


text:
#ifndef API_TEST_FAKE_MEDIA_TRANSPORT_H_
#define API_TEST_FAKE_MEDIA_TRANSPORT_H_

#include <memory>
#include <string>
#include <utility>
#include <vector>

#include "absl/algorithm/container.h"
#include "api/test/fake_datagram_transport.h"
#include "api/transport/media/media_transport_interface.h"

namespace webrtc {

// Fake media transport factory creates fake media transport.
// Also creates fake datagram transport, since both media and datagram
// transports are created by |MediaTransportFactory|.
class FakeMediaTransportFactory : public MediaTransportFactory {
 public:
  explicit FakeMediaTransportFactory(
      const absl::optional<std::string>& transport_offer = "")
      : transport_offer_(transport_offer) {}
  ~FakeMediaTransportFactory() = default;

  std::string GetTransportName() const override { return "fake"; }

  RTCErrorOr<std::unique_ptr<MediaTransportInterface>> CreateMediaTransport(
      rtc::PacketTransportInternal* packet_transport,
      rtc::Thread* network_thread,
      const MediaTransportSettings& settings) override {
    return RTCError(RTCErrorType::UNSUPPORTED_OPERATION);
  }

  RTCErrorOr<std::unique_ptr<MediaTransportInterface>> CreateMediaTransport(
      rtc::Thread* network_thread,
      const MediaTransportSettings& settings) override {
    return RTCError(RTCErrorType::UNSUPPORTED_OPERATION);
  }

  RTCErrorOr<std::unique_ptr<DatagramTransportInterface>>
  CreateDatagramTransport(rtc::Thread* network_thread,
                          const MediaTransportSettings& settings) override {
    return std::unique_ptr<DatagramTransportInterface>(
        new FakeDatagramTransport(settings, transport_offer_.value_or(""),
                                  transport_parameters_comparison_));
  }

  void set_transport_parameters_comparison(
      std::function<bool(absl::string_view, absl::string_view)> comparison) {
    transport_parameters_comparison_ = std::move(comparison);
  }

 private:
  const absl::optional<std::string> transport_offer_;
  std::function<bool(absl::string_view, absl::string_view)>
      transport_parameters_comparison_ =
          [](absl::string_view local, absl::string_view remote) {
            return local == remote;
          };
};

}  // namespace webrtc

#endif  // API_TEST_FAKE_MEDIA_TRANSPORT_H_


text: module Fae::UserConcern; end


text:
require 'erb'
require 'tilt'

# Template wrapper around the Tilt Template Abstraction Library.
class Souffle::Template

  # Creates a new template.
  #
  # @param [ String ] template The name of the template to render.
  def initialize(template)
    @template = Tilt.new(
      File.expand_path("#{Souffle::Template.template_path}/#{template}"))
  end

  # Renders the template with the given binding.
  #
  # @param [ Object ] binding The binding object for the template.
  #
  # @return [ String ] The rendered template.
  def render(binding)
    @template.render(binding)
  end

  # Helper pointing to the default templates path.
  #
  # @return [ String ] The path to the Souffle templates.
  def self.template_path
    File.expand_path(File.join(File.dirname(__FILE__), 'templates'))
  end
end


text:
package uk.gov.gds.ier.transaction.overseas.passport

import uk.gov.gds.ier.transaction.overseas.OverseasControllers
import com.google.inject.{Inject, Singleton}
import uk.gov.gds.ier.serialiser.JsonSerialiser
import uk.gov.gds.ier.config.Config
import uk.gov.gds.ier.security.EncryptionService
import uk.gov.gds.ier.model.{DOB}
import uk.gov.gds.ier.step.{Routes, OverseaStep}
import uk.gov.gds.ier.validation.ErrorTransformForm
import org.joda.time.LocalDate
import uk.gov.gds.ier.validation.constants.DateOfBirthConstants
import uk.gov.gds.ier.transaction.overseas.InprogressOverseas
import uk.gov.gds.ier.assets.RemoteAssets

@Singleton
class PassportCheckStep @Inject ()(
    val serialiser: JsonSerialiser,
    val config: Config,
    val encryptionService : EncryptionService,
    val remoteAssets: RemoteAssets,
    val overseas: OverseasControllers
) extends OverseaStep
  with PassportHelperConstants
  with PassportForms
  with PassportCheckMustache {

  val validation = passportCheckForm

  val routing = Routes(
    get = routes.PassportCheckStep.get,
    post = routes.PassportCheckStep.post,
    editGet = routes.PassportCheckStep.editGet,
    editPost = routes.PassportCheckStep.editPost
  )

  def nextStep(currentState: InprogressOverseas) = {

    val before1983 = currentState.dob map { case DOB(year, month, day) =>
      val dateOfBirth = new LocalDate()
        .withYear(year)
        .withMonthOfYear(month)
        .withDayOfMonth(day)
      dateOfBirth.isBefore(DateOfBirthConstants.jan1st1983)
    }

    val passport = currentState.passport map { passport => passport.hasPassport }

    val bornInUk = currentState.passport flatMap { passport => passport.bornInsideUk }

    (passport, bornInUk, before1983) match {
      case (`hasPassport`, _, _) => overseas.PassportDetailsStep
      case (`noPassport`, `notBornInUk`, _) => overseas.CitizenDetailsStep
      case (`noPassport`, `wasBornInUk`, `notBornBefore1983`) => overseas.CitizenDetailsStep
      case (`noPassport`, `wasBornInUk`, `wasBornBefore1983`) => overseas.NameStep
      case _ => this
    }
  }
}

private[passport] trait PassportHelperConstants {

  //Constants needed for the nextStep method
  private[passport] val hasPassport = Some(true)
  private[passport] val noPassport = Some(false)
  private[passport] val wasBornInUk = Some(true)
  private[passport] val notBornInUk = Some(false)
  private[passport] val wasBornBefore1983 = Some(true)
  private[passport] val notBornBefore1983 = Some(false)
}


text:
#include "QmitkXnatTreeBrowserView.h"

// Qmitk
#include "QmitkXnatObjectEditorInput.h"
#include "QmitkXnatEditor.h"
#include "org_mitk_gui_qt_xnatinterface_Activator.h"

// Blueberry
#include <berryIWorkbenchPage.h>

// CTK XNAT Core
#include "ctkXnatFile.h"

const std::string QmitkXnatTreeBrowserView::VIEW_ID = "org.mitk.views.xnat.treebrowser";

QmitkXnatTreeBrowserView::QmitkXnatTreeBrowserView():
  m_Session(0),
  m_TreeModel(new ctkXnatTreeModel())
{
}

QmitkXnatTreeBrowserView::~QmitkXnatTreeBrowserView()
{
  delete m_TreeModel;
}

void QmitkXnatTreeBrowserView::SetFocus()
{
}

void QmitkXnatTreeBrowserView::CreateQtPartControl( QWidget *parent )
{
  // Create GUI widgets from the Qt Designer's .ui file
  m_Controls.setupUi( parent );
  m_Controls.treeView->setModel(m_TreeModel);
  m_Controls.treeView->header()->hide();

  m_SelectionProvider = new berry::QtSelectionProvider();
  m_SelectionProvider->SetItemSelectionModel(m_Controls.treeView->selectionModel());
  this->SetSelectionProvider();
  m_Controls.treeView->setSelectionMode(QAbstractItemView::SingleSelection);

  connect( m_Controls.treeView, SIGNAL(activated(const QModelIndex&)), this, SLOT(OnActivatedNode(const QModelIndex&)) );

  // Get the XNAT Session from Activator
  m_Session = mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatConnectionManager()->GetXnatConnection();

  if(m_Session == 0) return;

  // Fill model and show in the GUI
  m_TreeModel->addDataModel(m_Session->dataModel());
  m_Controls.treeView->reset();
}

void QmitkXnatTreeBrowserView::OnActivatedNode(const QModelIndex& index)
{
  if (!index.isValid()) return;

  berry::IWorkbenchPage::Pointer page = GetSite()->GetPage();
  QmitkXnatObjectEditorInput::Pointer oPtr = QmitkXnatObjectEditorInput::New( index.data(Qt::UserRole).value<ctkXnatObject*>() );
  berry::IEditorInput::Pointer editorInput( oPtr );
  berry::IEditorPart::Pointer reuseEditor = page->FindEditor(editorInput);

  if(reuseEditor)
  {
    // Just set it activ
    page->Activate(reuseEditor);
  }
  else
  {
    std::vector<berry::IEditorReference::Pointer> editors =
      page->FindEditors(berry::IEditorInput::Pointer(0), QmitkXnatEditor::EDITOR_ID, berry::IWorkbenchPage::MATCH_ID);

    if (editors.empty())
    {
      // No XnatEditor is currently open, create a new one
      ctkXnatFile* file = dynamic_cast<ctkXnatFile*>(oPtr->GetXnatObject());
      if(file != NULL)
      {
        // If a file is activated take the parent and open a new editor
        QmitkXnatObjectEditorInput::Pointer oPtr2 = QmitkXnatObjectEditorInput::New( file->parent() );
        berry::IEditorInput::Pointer editorInput2( oPtr2 );
        page->OpenEditor(editorInput2, QmitkXnatEditor::EDITOR_ID);
      }
      else
      {
        page->OpenEditor(editorInput, QmitkXnatEditor::EDITOR_ID);
      }
    }
    else
    {
      // Reuse an existing editor
      reuseEditor = editors.front()->GetEditor(true);
      page->ReuseEditor(reuseEditor.Cast<berry::IReusableEditor>(), editorInput);
      page->Activate(reuseEditor);
    }
  }
}

void QmitkXnatTreeBrowserView::SetSelectionProvider()
{
  GetSite()->SetSelectionProvider(m_SelectionProvider);
}


text:
/**
 * @file
 **/

#pragma once

#include <algorithm>

#include "modules/common/proto/pnc_point.pb.h"

namespace apollo {
namespace planning {

class FeasibleRegion {
 public:
  explicit FeasibleRegion(const std::array<double, 3>& init_s);

  double SUpper(const double t) const;

  double SLower(const double t) const;

  double VUpper(const double t) const;

  double VLower(const double t) const;

  double TLower(const double s) const;

 private:
  std::array<double, 3> init_s_;

  double t_at_zero_speed_;

  double s_at_zero_speed_;
};

}  // namespace planning
}  // namespace apollo


text:
from pyalgotrade import strategy
from pyalgotrade import plotter
from pyalgotrade.tools import yahoofinance
from pyalgotrade.technical import bollinger
from pyalgotrade.stratanalyzer import sharpe

class BBands(strategy.BacktestingStrategy):
    def __init__(self, feed, instrument, bBandsPeriod):
        super(BBands, self).__init__(feed)
        self.__instrument = instrument
        self.__bbands = bollinger.BollingerBands(feed[instrument].getCloseDataSeries(), bBandsPeriod, 2)

    def getBollingerBands(self):
        return self.__bbands

    def onBars(self, bars):
        lower = self.__bbands.getLowerBand()[-1]
        upper = self.__bbands.getUpperBand()[-1]
        if lower is None:
            return

        shares = self.getBroker().getShares(self.__instrument)
        bar = bars[self.__instrument]
        if shares == 0 and bar.getClose() < lower:
            sharesToBuy = int(self.getBroker().getCash(False) / bar.getClose())
            self.marketOrder(self.__instrument, sharesToBuy)
        elif shares > 0 and bar.getClose() > upper:
            self.marketOrder(self.__instrument, -1*shares)

def main(plot):
    instrument = "yhoo"
    bBandsPeriod = 40

    # Download the bars.
    feed = yahoofinance.build_feed([instrument], 2011, 2012, ".")

    strat = BBands(feed, instrument, bBandsPeriod)
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    strat.attachAnalyzer(sharpeRatioAnalyzer)

    if plot:
        plt = plotter.StrategyPlotter(strat, True, True, True)
        plt.getInstrumentSubplot(instrument).addDataSeries("upper", strat.getBollingerBands().getUpperBand())
        plt.getInstrumentSubplot(instrument).addDataSeries("middle", strat.getBollingerBands().getMiddleBand())
        plt.getInstrumentSubplot(instrument).addDataSeries("lower", strat.getBollingerBands().getLowerBand())

    strat.run()
    print "Sharpe ratio: %.2f" % sharpeRatioAnalyzer.getSharpeRatio(0.05)

    if plot:
        plt.plot()

if __name__ == "__main__":
    main(True)


text:
from mock import Mock
from preggy import expect

from holmes.config import Config
from holmes.reviewer import Reviewer
from holmes.validators.meta_tags import MetaTagsValidator
from tests.unit.base import ValidatorTestCase
from tests.fixtures import PageFactory

class TestMetaTagsValidator(ValidatorTestCase):

    def test_can_validate_pages_with_metatags(self):
        page = PageFactory.create()
        reviewer = Reviewer(
            api_url='http://localhost:2368',
            page_uuid=page.uuid,
            page_url=page.url,
            page_score=0.0,
            config=Config(),
            validators=[]
        )
        validator = MetaTagsValidator(reviewer)
        validator.add_violation = Mock()
        validator.review.data['meta.tags'] = [
            {'content': 'utf-8', 'property': None, 'key': 'charset'},
            {'content': 'text/html;charset=UTF-8', 'property': 'http-equiv', 'key': 'Content-Type'},
        ]
        validator.validate()
        expect(validator.add_violation.called).to_be_false()

    def test_can_validate_page_without_meta_tags(self):
        page = PageFactory.create()
        reviewer = Reviewer(
            api_url='http://localhost:2368',
            page_uuid=page.uuid,
            page_url=page.url,
            page_score=0.0,
            config=Config(),
            validators=[]
        )
        validator = MetaTagsValidator(reviewer)
        validator.add_violation = Mock()
        validator.review.data['meta.tags'] = []
        validator.validate()

        validator.add_violation.assert_called_once_with(
            key='absent.metatags',
            value='No metatags.',
            points=100
        )

    def test_can_validate_page_with_metatag_description_too_long(self):
        page = PageFactory.create()
        reviewer = Reviewer(
            api_url='http://localhost:2368',
            page_uuid=page.uuid,
            page_url=page.url,
            page_score=0.0,
            config=Config(),
            validators=[],
            cache=self.sync_cache
        )

        reviewer.violation_definitions = {
            'page.metatags.description_too_big': {'default_value': 300},
        }

        validator = MetaTagsValidator(reviewer)

        validator.add_violation = Mock()
        validator.review.data['meta.tags'] = [
            {'content': 'X' * 301, 'property': 'name', 'key': 'description'},
        ]
        validator.validate()
        validator.add_violation.assert_called_once_with(
            key='page.metatags.description_too_big',
            value={'max_size': 300},
            points=20
        )

        validator.add_violation = Mock()
        validator.review.data['meta.tags'] = [
            {'content': 'X' * 300, 'property': 'name', 'key': 'description'},
        ]
        validator.validate()
        expect(validator.add_violation.called).to_be_false()

    def test_can_get_violation_definitions(self):
        reviewer = Mock()
        validator = MetaTagsValidator(reviewer)
        definitions = validator.get_violation_definitions()

        expect(definitions).to_length(2)
        expect('absent.metatags' in definitions).to_be_true()
        expect('page.metatags.description_too_big' in definitions).to_be_true()

    def test_can_get_default_violations_values(self):
        config = Config()
        config.METATAG_DESCRIPTION_MAX_SIZE = 300

        page = PageFactory.create()

        reviewer = Reviewer(
            api_url='http://localhost:2368',
            page_uuid=page.uuid,
            page_url=page.url,
            page_score=0.0,
            config=config,
            validators=[]
        )

        validator = MetaTagsValidator(reviewer)

        violations_values = validator.get_default_violations_values(config)

        expect(violations_values).to_include('page.metatags.description_too_big')

        expect(violations_values['page.metatags.description_too_big']).to_length(2)

        expect(violations_values['page.metatags.description_too_big']).to_be_like({
            'value': config.METATAG_DESCRIPTION_MAX_SIZE,
            'description': config.get_description('METATAG_DESCRIPTION_MAX_SIZE')
        })


text:
package uk.gov.hmrc.ct.computations

import uk.gov.hmrc.ct.box._
import uk.gov.hmrc.ct.computations.retriever.ComputationsBoxRetriever

case class CP128(value: Option[Boolean]) extends CtBoxIdentifier(name = "Did you receive any money from CJRS or JSS") with CtOptionalBoolean with Input with ValidatableBox[ComputationsBoxRetriever] {
  override def validate(boxRetriever: ComputationsBoxRetriever): Set[CtValidation] = {
    if(covidSupport.doesPeriodCoverCovid(boxRetriever.cp1().value, boxRetriever.cp2().value)){
      collectErrors(validateAsMandatory(this))
    }else Set.empty
  }
}


text:
2012
----

### December 21st

Brent Yorgey, PhD student at the University of Pennsylvania,
visits the FP group and talks about his diagrams package.

### December 10th

Andrew Farmer passed his
comprehensive PhD oral examination,
with dissertation title ''Mechanizing Worker/Wrapper for Domain Specific Optimizations''.
Congratulations Andrew!

### September 13th

Neil Sculthorpe gave a [talk](http://www.youtube.com/watch?v=x2QH3jJCJso)
about the internals of [HERMIT](/projects/hermit)
at the [Haskell Symposium](http://www.haskell.org/haskell-symposium/2012/)

### September 9th

Andrew Farmer gave a [talk](http://www.youtube.com/watch?v=ivMHHreMTvM)
about [HERMIT](/projects/hermit)'s web interface technology
at the [XLDI Workshop](http://workshops.inf.ed.ac.uk/xldi2012/)

### August 31st

Neil Sculthorpe gave a [talk](http://www.youtube.com/watch?v=fB6SjYPfye4)
about using [HERMIT](/projects/hermit)
at the [IFL 2012](http://www.cs.ox.ac.uk/conferences/IFL2012/)

### March 5th

Neil Sculthorpe joins the FP group. He will work as a PostDoc on
the HERMIT project. Welcome aboard Neil!

2011
----

### November 7th

We (finally!) release Kansas Lava, and Kansas Lava Cores. There are
available on [hackage](http://hackage.haskell.org). Our webpage for
Kansas Lava is
[http://ittc.ku.eduTools/KansasLava](http://ittc.ku.edu/csdl/fpg/Tools/KansasLava).

### September 8th

We are looking to[hire a PostDoc, to work
on the [HERMIT](/projects/hermit) project. Please apply!

### July 28th

The Functional Programming Group at KU have be awarded an NSF grant to
improving the applicability of Haskell-hosted semi-formal models to high
assurance development. Specifically, this involves building a refinement
toolkit inside GHC that uses a general form of the worker/wrapper
transformation.

### July 19th

Andy Gill presented gave an invited talk "Declarative FPGA Circuit
Synthesis using Kansas Lava", at ERSA'11, Las Vegas, NV.

### June 14th

Andy Gill presented "Functional Programming, Hardware Generation and
Functor Chains" at Chalmers University, Sweden.

### June 10th

Andy Gill presented "Functional Programming, Hardware Generation and
Functor Chains" at the University of Kent, England.

### June 7th

Andy Gill presented "Functional Programming, Hardware Generation and
Functor Chains" at the University of Oxford, England.

### May 24th

Andy Gill presented "Deriving an Efficient FPGA Implementation of a Low
Density Parity Check Forward Error Corrector" to WG2.1 in Reykjavik,
Iceland.

### May 2nd

Andy Gill presented "[Using Functional Programming to Generate an LDPC
Forward Error Corrector](/papers/Gill-11-GeneratingLDPC)" at the 19th Annual IEEE
International Symposium on Field-Programmable Custom Computing Machines.

### April 22nd

Tristan Bull successfully defended his MS.

### April 21st

Kevin Matlage successfully defended his MS.

### March 9th

Andrew Farmer was selected to receive an NSF GK-12 fellowship for the
2011-2012 academic year. The fellowship, which includes a \$30,000
stipend, supports partnerships between graduate students and middle
school teachers to improve Fellows' teaching and communication skills,
advance STEM education in middle schools, and provide role models for
younger students.

2010
----

### Dec 21st

Announcing the [2011 Symposium on Implementation and Application of
Functional Languages](http://www.ittc.ku.edu/ifl2011), to be hosted by
FPG at KU, October 3-5, 2011.

### Oct 1st

[Andrew Farmer](/users/andrewfarmer) gave a talk about type functions and
Kansas Lava at the [Haskell Implementors
Workshop](http://haskell.org/haskellwiki/HaskellImplementorsWorkshop/2010).
[Slides](http://www.scribd.com/doc/38559736/kansaslava-hiw10),
[Video](http://www.vimeo.com/15571220).

### Sep 27th and 28th

Simon Thompson visited FPG and CSDL, and gave two talks about Wrangler
and HaRe.

### Sep 23rd

Andy Gill gave a talk at ASEE, about post-processing video talks.

### Aug 28th

[Paper](/papers/Gill-10-ImprovingVideo) about using ChalkBoard
for video processing accepted and sent for publication at ASEE.

### July 19th-23rd

Andy Gill and Andrew Farmer spend week at Portland State University, in
Portland, Oregon.

### July 19th

Paper about using ChalkBoard for video processing
submitted.


text:
package com.drillster.api2;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;

import com.drillster.api2.general.Error;
import com.drillster.api2.general.Response;
import com.drillster.api2.message.json.jackson.JacksonMarshaller;

/**
 *	Provides the base class for the Drillster API SDK.  See http://drill.st/api
 *	for more information about the API.  Go to http://www.drillster.com for
 *	more information about Drillster.
 *
 *	@author Tom van den Berge
 *	@author Thomas Goossens
 *	Provided by Drillster BV, dual licensed under MIT and GPL.
 */
public class Api {

	public enum HttpMethod {
		GET, POST, PUT, DELETE;
	}

	private static final Logger LOG = Logger.getLogger(Api.class);
	private static final String FORM_CONTENT_TYPE = "application/x-www-form-urlencoded";

	private String oAuthToken;
	private String hostName = "www.drillster.com";
	private Integer port = 443;
	private String scheme = "https";
	private CloseableHttpClient httpClient;
	private HttpHost targetHost;
	private JacksonMarshaller jsonMarshaller;

	public String getHostName() {
		return this.hostName;
	}

	public Integer getPort() {
		return this.port;
	}

	public String getScheme() {
		return this.scheme;
	}

	public void setHostName(String hostName) {
		this.hostName = hostName;
	}

	public void setPort(Integer port) {
		this.port = port;
	}

	public void setScheme(String scheme) {
		this.scheme = scheme;
	}

	public void setOAuthToken(String oAuthToken) {
		this.oAuthToken = oAuthToken;
	}

	/**
	 * Overrides the default http client that is used to send the requests to
	 * Drillster.
	 */
	public void setHttpClient(CloseableHttpClient httpClient) {
		this.httpClient = httpClient;
	}

	private synchronized void init() {
		if (this.targetHost != null) {
			return;
		}
		if (this.httpClient == null) {
			this.httpClient = HttpClients.createDefault();
		}
		this.targetHost = new HttpHost(this.hostName, this.port, this.scheme);
		this.jsonMarshaller = new JacksonMarshaller();
	}

	/**
	 * Sends a POST request with url-encoded parameters in the body. The JSON
	 * response is parsed into the specified response type, and returned.
	 */
	public <T extends com.drillster.api2.general.Response> T sendPostRequest(String url, List<NameValuePair> parameters,
			Class<T> responseType) throws ApiException {
		return sendPostRequest(url, parameters, responseType, this.oAuthToken);

	}

	/**
	 * Sends a POST request with url-encoded parameters in the body. The JSON
	 * response is parsed into the specified response type, and returned.
	 *
	 * @param oAuthToken
	 *            the OAuth authentication token to include in the request, or
	 *            {@code null} to include no OAuth token.
	 */
	public <T extends com.drillster.api2.general.Response> T sendPostRequest(String url, List<NameValuePair> parameters,
			Class<T> responseType, String oAuthToken) throws ApiException {
		return sendPostRequest(url, parameters, responseType, Error.class, oAuthToken);
	}

	public <T extends com.drillster.api2.general.Response> T sendPostRequest(String url, List<NameValuePair> parameters,
			Class<T> responseType, Class<? extends Error> errorType) throws ApiException {
		return sendPostRequest(url, parameters, responseType, errorType, this.oAuthToken);
	}

	public <T extends com.drillster.api2.general.Response> T sendPostRequest(String url, List<NameValuePair> parameters,
			Class<T> responseType, Class<? extends Error> errorType, String oAuthToken) throws ApiException {
		init();
		return deserializeFromJson(sendRequestInternal(url, new UrlEncodedFormEntity(parameters, Consts.UTF_8), HttpMethod.POST, oAuthToken),
				responseType, errorType);
	}

	/**
	 * Sends a POST request with url-encoded parameters in the body. No response is expected.
	 */
	public void sendPostRequest(String url, List<NameValuePair> parameters) throws ApiException {
		sendPostRequest(url, parameters, this.oAuthToken);
	}

	/**
	 * Sends a POST request with url-encoded parameters in the body. No response
	 * is expected.
	 *
	 * @param oAuthToken
	 *            the OAuth authentication token to include in the request, or
	 *            {@code null} to include no OAuth token.
	 */
	public void sendPostRequest(String url, List<NameValuePair> parameters, String oAuthToken) throws ApiException {
		init();
		sendRequestInternal(url, new UrlEncodedFormEntity(parameters, Consts.UTF_8), HttpMethod.POST, oAuthToken);
	}

	/**
	 * Sends a PUT request with url-encoded parameters in the body.
	 */
	public <T extends com.drillster.api2.general.Response> T sendPutRequest(String url, List<NameValuePair> parameters, Class<T> responseType) throws ApiException {
		return sendPutRequest(url, parameters, responseType, this.oAuthToken);
	}

	/**
	 * Sends a PUT request with url-encoded parameters in the body.
	 *
	 * @param oAuthToken
	 *            the OAuth authentication token to include in the request, or
	 *            {@code null} to include no OAuth token.
	 */
	public <T extends com.drillster.api2.general.Response> T sendPutRequest(String url, List<NameValuePair> parameters, Class<T> responseType, String oAuthToken) throws ApiException {
		init();
		return deserializeFromJson(sendRequestInternal(url, new UrlEncodedFormEntity(parameters, Consts.UTF_8), HttpMethod.PUT, oAuthToken), responseType);
	}

	/**
	 * Sends a DELETE request.
	 */
	public <T extends com.drillster.api2.general.Response> T sendDeleteRequest(String url, Class<T> responseType) throws ApiException {
		return sendDeleteRequest(url, responseType, this.oAuthToken);
	}

	/**
	 * Sends a PUT request with url-encoded parameters in the body.
	 *
	 * @param oAuthToken
	 *            the OAuth authentication token to include in the request, or
	 *            {@code null} to include no OAuth token.
	 */
	public <T extends com.drillster.api2.general.Response> T sendDeleteRequest(String url, Class<T> responseType, String oAuthToken) throws ApiException {
		init();
		return deserializeFromJson(sendRequestInternal(url, (String)null, HttpMethod.DELETE, oAuthToken), responseType);
	}

	/**
	 * Sends a Get request to the specified url. The JSON response is parsed into the specified response type, and returned.
	 */
	public <T extends com.drillster.api2.general.Response> T sendGetRequest(String url, Class<T> responseType) throws ApiException {
		return sendGetRequest(url, responseType, this.oAuthToken);
	}

	/**
	 * Sends a Get request to the specified url. The JSON response is parsed
	 * into the specified response type, and returned.
	 *
	 * @param oAuthToken
	 *            the OAuth authentication token to include in the request, or
	 *            {@code null} to include no OAuth token.
	 */
	public <T extends com.drillster.api2.general.Response> T sendGetRequest(String url, Class<T> responseType, String oAuthToken) throws ApiException {
		init();
		return deserializeFromJson(sendRequestInternal(url, (String)null, HttpMethod.GET, oAuthToken), responseType);
	}

	// --------

	public <T> T deserializeFromJson(HttpResponse response, Class<T> responseType) throws ApiException {
		return deserializeFromJson(response, responseType, Error.class);
	}

	public <T> T deserializeFromJson(HttpResponse response, Class<T> responseType, Class<? extends Error> errorType) throws ApiException {
		try {
			String responseBody = EntityUtils.toString(response.getEntity());
			LOG.debug("Received:\n" + responseBody);

			if (response.getStatusLine().getStatusCode() != 200) {
				throw new UnsuccessfulRequestException(deserializeFromJson(responseBody, errorType));
			}
			return deserializeFromJson(responseBody, responseType);
		} catch (ParseException e) {
			throw new ApiException(e);
		} catch (IOException e) {
			throw new ApiException(e);
		}

	}

	@SuppressWarnings("unchecked")
	public <T> T deserializeFromJson(String json, Class<T> responseType) throws ApiException {
		init();
		try {
			if (responseType.equals(Response.class)) {
				return (T) this.jsonMarshaller.unmarshal(json);
			}
			return this.jsonMarshaller.unmarshal(json, responseType);
		} catch (JsonParseException jpx) {
			throw new ApiException(jpx);
		} catch (JsonMappingException jmx) {
			throw new ApiException(jmx);
		} catch (IOException iox) {
			throw new ApiException(iox);
		}
	}

	private HttpResponse sendRequestInternal(String url, String content, HttpMethod method, String oAuthToken) throws ApiException {
		LOG.debug("Sending request to " + url + ". Content:\n" + content);

		HttpRequest request;
		if (method == HttpMethod.GET) {
			request = new HttpGet(url);
		} else {
			try {
				if (method == HttpMethod.PUT) {
					HttpPut put = new HttpPut(url);
					put.setEntity(new StringEntity(content, FORM_CONTENT_TYPE, "UTF-8"));
					request = put;
				} else if (method == HttpMethod.POST) {
					HttpPost post = new HttpPost(url);
					if (content != null) {
						post.setEntity(new StringEntity(content, FORM_CONTENT_TYPE, "UTF-8"));
					}
					request = post;
				} else if (method == HttpMethod.DELETE) {
					HttpDelete delete = new HttpDelete(url);
					request = delete;
				} else {
					throw new IllegalArgumentException();
				}
			} catch (UnsupportedEncodingException e) {
				throw new ApiException(e);
			}
		}
		return sendRequestInternal(request, oAuthToken);
	}

	private HttpResponse sendRequestInternal(String url, HttpEntity content, HttpMethod method, String oAuthToken) throws ApiException {
		LOG.debug("Sending request to " + url + ". Content:\n" + content);

		HttpRequest request;
		if (method == HttpMethod.GET) {
			request = new HttpGet(url);
		} else {
			if (method == HttpMethod.PUT) {
				HttpPut put = new HttpPut(url);
				put.setEntity(content);
				request = put;
			} else if (method == HttpMethod.POST) {
				HttpPost post = new HttpPost(url);
				post.setEntity(content);
				request = post;
			} else {
				throw new IllegalArgumentException();
			}
		}
		return sendRequestInternal(request, oAuthToken);
	}

	private HttpResponse sendRequestInternal(HttpRequest httpRequest, String oAuthToken) throws ApiException {
		if (oAuthToken != null) {
			httpRequest.addHeader("Authorization", "OAuth " + oAuthToken);
		}
		try {
			return this.httpClient.execute(this.targetHost, httpRequest);
		} catch (ClientProtocolException e) {
			throw new ApiException(e);
		} catch (IOException e) {
			throw new ApiException(e);
		}
	}
}