text:
package com.facebook.thrift.rsocket;

import static org.junit.Assert.assertEquals;

import com.facebook.swift.service.ThriftServerConfig;
import com.facebook.thrift.client.RpcClientFactory;
import com.facebook.thrift.client.ThriftClientConfig;
import com.facebook.thrift.example.ping.CustomException;
import com.facebook.thrift.example.ping.PingRequest;
import com.facebook.thrift.example.ping.PingResponse;
import com.facebook.thrift.example.ping.PingService;
import com.facebook.thrift.example.ping.PingServiceRpcServerHandler;
import com.facebook.thrift.legacy.server.testservices.BlockingPingService;
import com.facebook.thrift.legacy.server.testservices.ReactivePingService;
import com.facebook.thrift.rsocket.server.RSocketServerTransport;
import com.facebook.thrift.rsocket.server.RSocketServerTransportFactory;
import com.facebook.thrift.server.RpcServerHandler;
import com.facebook.thrift.util.FutureUtil;
import com.google.common.util.concurrent.ListenableFuture;
import io.airlift.units.Duration;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.concurrent.TimeUnit;
import org.apache.thrift.ProtocolId;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import reactor.core.publisher.Flux;
import reactor.test.StepVerifier;

public class RSocketThriftClientTest {

  @Rule public ExpectedException expectedException = ExpectedException.none();

  @Test(expected = CustomException.class)
  public void testPingException() {
    System.out.println("create server handler");
    RpcServerHandler serverHandler =
        new PingServiceRpcServerHandler(new BlockingPingService(), Collections.emptyList());

    System.out.println("starting server");
    RSocketServerTransportFactory transportFactory =
        new RSocketServerTransportFactory(new ThriftServerConfig().setEnableJdkSsl(false));
    RSocketServerTransport transport =
        transportFactory.createServerTransport(serverHandler).block();
    InetSocketAddress address = (InetSocketAddress) transport.getAddress();

    System.out.println("creating client");

    RpcClientFactory factory =
        RpcClientFactory.builder()
            .setDisableLoadBalancing(true)
            .setDisableRSocket(false)
            .setThriftClientConfig(
                new ThriftClientConfig()
                    .setDisableSSL(true)
                    .setRequestTimeout(Duration.succinctDuration(1, TimeUnit.DAYS)))
            .build();

    PingService client =
        PingService.clientBuilder().setProtocolId(ProtocolId.BINARY).build(factory, address);

    client.pingException(new PingRequest.Builder().setRequest("ping").build());
  }

  @Test
  public void testPingVoidBlocking() {
    System.out.println("create server handler");
    RpcServerHandler serverHandler =
        new PingServiceRpcServerHandler(new BlockingPingService(), Collections.emptyList());

    System.out.println("starting server");
    RSocketServerTransportFactory transportFactory =
        new RSocketServerTransportFactory(new ThriftServerConfig().setEnableJdkSsl(false));
    RSocketServerTransport transport =
        transportFactory.createServerTransport(serverHandler).block();
    InetSocketAddress address = (InetSocketAddress) transport.getAddress();

    System.out.println("creating client");

    RpcClientFactory factory =
        RpcClientFactory.builder()
            .setDisableLoadBalancing(true)
            .setDisableRSocket(false)
            .setThriftClientConfig(
                new ThriftClientConfig()
                    .setDisableSSL(true)
                    .setRequestTimeout(Duration.succinctDuration(1, TimeUnit.DAYS)))
            .build();

    PingService client =
        PingService.clientBuilder().setProtocolId(ProtocolId.BINARY).build(factory, address);

    client.pingVoid(new PingRequest.Builder().setRequest("ping").build());
  }

  @Test
  public void testPingVoidAsync() throws Exception {
    System.out.println("create server handler");
    RpcServerHandler serverHandler =
        new PingServiceRpcServerHandler(new BlockingPingService(), Collections.emptyList());

    System.out.println("starting server");
    RSocketServerTransportFactory transportFactory =
        new RSocketServerTransportFactory(new ThriftServerConfig().setEnableJdkSsl(false));
    RSocketServerTransport transport =
        transportFactory.createServerTransport(serverHandler).block();
    InetSocketAddress address = (InetSocketAddress) transport.getAddress();

    System.out.println("creating client");

    RpcClientFactory factory =
        RpcClientFactory.builder()
            .setDisableLoadBalancing(true)
            .setDisableRSocket(false)
            .setThriftClientConfig(
                new ThriftClientConfig()
                    .setDisableSSL(true)
                    .setRequestTimeout(Duration.succinctDuration(1, TimeUnit.DAYS)))
            .build();

    PingService.Async client =
        PingService.Async.clientBuilder().setProtocolId(ProtocolId.BINARY).build(factory, address);
    client.pingVoid(new PingRequest.Builder().setRequest("ping").build()).get();
  }

  @Test
  public void testPingVoidReactive() {
    System.out.println("create server handler");
    RpcServerHandler serverHandler =
        new PingServiceRpcServerHandler(new BlockingPingService(), Collections.emptyList());

    System.out.println("starting server");
    RSocketServerTransportFactory transportFactory =
        new RSocketServerTransportFactory(new ThriftServerConfig().setEnableJdkSsl(false));
    RSocketServerTransport transport =
        transportFactory.createServerTransport(serverHandler).block();
    InetSocketAddress address = (InetSocketAddress) transport.getAddress();

    System.out.println("creating client");

    RpcClientFactory factory =
        RpcClientFactory.builder()
            .setDisableLoadBalancing(true)
            .setDisableRSocket(false)
            .setThriftClientConfig(
                new ThriftClientConfig()
                    .setDisableSSL(true)
                    .setRequestTimeout(Duration.succinctDuration(1, TimeUnit.DAYS)))
            .build();

    PingService.Reactive client =
        PingService.Reactive.clientBuilder()
            .setProtocolId(ProtocolId.BINARY)
            .build(factory, address);
    client.pingVoid(new PingRequest.Builder().setRequest("ping").build()).block();
  }

  @Test
  public void testPingBinary() {
    System.out.println("create server handler");
    RpcServerHandler serverHandler =
        new PingServiceRpcServerHandler(new BlockingPingService(), Collections.emptyList());

    System.out.println("starting server");
    RSocketServerTransportFactory transportFactory =
        new RSocketServerTransportFactory(new ThriftServerConfig().setSslEnabled(false));
    RSocketServerTransport transport =
        transportFactory.createServerTransport(serverHandler).block();
    InetSocketAddress address = (InetSocketAddress) transport.getAddress();

    System.out.println("creating client");

    RpcClientFactory factory =
        RpcClientFactory.builder()
            .setDisableLoadBalancing(true)
            .setDisableRSocket(false)
            .setThriftClientConfig(
                new ThriftClientConfig()
                    .setDisableSSL(true)
                    .setRequestTimeout(Duration.succinctDuration(1, TimeUnit.DAYS)))
            .build();

    PingService client =
        PingService.clientBuilder().setProtocolId(ProtocolId.BINARY).build(factory, address);

    byte[] result = client.pingBinary(new PingRequest.Builder().setRequest("ping").build());
    assertEquals("hello!", new String(result, StandardCharsets.UTF_8));
  }

  @Test
  public void test1StreamingPing() {
    sendNPings(1);
  }

  @Test
  public void test10StreamingPing() {
    sendNPings(10);
  }

  @Test
  public void test100StreamingPing() {
    sendNPings(100);
  }

  @Test
  public void test1000StreamingPing() {
    sendNPings(1_000);
  }

  @Test
  public void test10_000StreamingPing() {
    sendNPings(10_000);
  }

  public void sendNPings(int numOfPings) {
    System.out.println("create server handler");
    RpcServerHandler serverHandler =
        new PingServiceRpcServerHandler(new ReactivePingService(), Collections.emptyList());

    System.out.println("starting server");
    RSocketServerTransportFactory transportFactory =
        new RSocketServerTransportFactory(new ThriftServerConfig().setSslEnabled(false));
    RSocketServerTransport transport =
        transportFactory.createServerTransport(serverHandler).block();
    InetSocketAddress address = (InetSocketAddress) transport.getAddress();

    System.out.println("creating client");

    RpcClientFactory factory =
        RpcClientFactory.builder()
            .setDisableLoadBalancing(true)
            .setDisableRSocket(false)
            .setThriftClientConfig(
                new ThriftClientConfig()
                    .setDisableSSL(true)
                    .setRequestTimeout(Duration.succinctDuration(1, TimeUnit.DAYS)))
            .build();

    PingService.Reactive client =
        PingService.Reactive.clientBuilder()
            .setProtocolId(ProtocolId.BINARY)
            .build(factory, address);

    Flux<PingResponse> ping =
        client
            .streamOfPings(new PingRequest.Builder().setRequest("ping").build(), numOfPings)
            .timeout(java.time.Duration.ofSeconds(30));

    StepVerifier.create(ping).expectNextCount(numOfPings).verifyComplete();
  }

  @Test
  public void test1BlockingPingPongs() {
    sendNBlockingPingPongs(1);
  }

  @Test
  public void test10BlockingPingPongs() {
    sendNBlockingPingPongs(10);
  }

  @Test
  public void test100BlockingPingPongs() {
    sendNBlockingPingPongs(100);
  }

  @Test
  public void test1000BlockingPingPongs() {
    sendNBlockingPingPongs(1000);
  }

  private void sendNBlockingPingPongs(int n) {
    System.out.println("create server handler");
    RpcServerHandler serverHandler =
        new PingServiceRpcServerHandler(new BlockingPingService(), Collections.emptyList());

    System.out.println("starting server");
    RSocketServerTransportFactory transportFactory =
        new RSocketServerTransportFactory(new ThriftServerConfig().setEnableJdkSsl(false));
    RSocketServerTransport transport =
        transportFactory.createServerTransport(serverHandler).block();
    InetSocketAddress address = (InetSocketAddress) transport.getAddress();

    System.out.println("creating client");

    RpcClientFactory factory =
        RpcClientFactory.builder()
            .setDisableLoadBalancing(true)
            .setDisableRSocket(false)
            .setThriftClientConfig(
                new ThriftClientConfig()
                    .setDisableSSL(true)
                    .setRequestTimeout(Duration.succinctDuration(1, TimeUnit.DAYS)))
            .build();

    PingService pingService =
        PingService.clientBuilder().setProtocolId(ProtocolId.BINARY).build(factory, address);

    for (int i = 0; i < n; i++) {
      PingRequest pingRequest = new PingRequest.Builder().setRequest(i + "ping").build();
      PingResponse pingResponse = pingService.ping(pingRequest);
      assertEquals(pingResponse.getResponse(), i + "ping_pong_" + i);
    }
  }

  @Test
  public void test1AsyncPingPongs() {
    sendNAsyncPingPongs(1);
  }

  @Test
  public void test10AsyncPingPongs() {
    sendNAsyncPingPongs(10);
  }

  @Test
  public void test100AsyncPingPongs() {
    sendNAsyncPingPongs(100);
  }

  @Test
  public void test1000AsyncPingPongs() {
    sendNAsyncPingPongs(1000);
  }

  @Test
  public void test10_000AsyncPingPongs() {
    sendNAsyncPingPongs(10_000);
  }

  private void sendNAsyncPingPongs(int n) {
    System.out.println("create server handler");
    RpcServerHandler serverHandler =
        new PingServiceRpcServerHandler(new BlockingPingService(), Collections.emptyList());

    System.out.println("starting server");
    RSocketServerTransportFactory transportFactory =
        new RSocketServerTransportFactory(new ThriftServerConfig().setEnableJdkSsl(false));
    RSocketServerTransport transport =
        transportFactory.createServerTransport(serverHandler).block();
    InetSocketAddress address = (InetSocketAddress) transport.getAddress();

    System.out.println("server started on address " + address);

    System.out.println("creating client");

    RpcClientFactory factory =
        RpcClientFactory.builder()
            .setDisableLoadBalancing(true)
            .setDisableRSocket(false)
            .setThriftClientConfig(
                new ThriftClientConfig()
                    .setDisableSSL(true)
                    .setRequestTimeout(Duration.succinctDuration(1, TimeUnit.DAYS)))
            .build();

    PingService.Async pingService =
        PingService.Async.clientBuilder().setProtocolId(ProtocolId.BINARY).build(factory, address);
    System.out.println("new client created, sending ping");

    Flux.range(0, n)
        .flatMap(
            i -> {
              PingRequest pingRequest = new PingRequest.Builder().setRequest("ping").build();
              ListenableFuture<PingResponse> ping = pingService.ping(pingRequest);
              return FutureUtil.toMono(ping);
            },
            32)
        .blockLast();
  }
}


text:
require_relative './builtin'

class Bignum
  include RubyOnRun::Builtin::Builtin
end

redpajama_set_name: RedPajamaGithub


text:
package implwin

import (
	"core"
	"win"
)

type PenWin interface {
	core.Pen
	handle() win.HPEN
}

func getPenStyleWin(style core.PenStyle) uint32 {
	winPenStyle := uint32(style.Style)

	switch style.Type {
	case core.PEN_TYPE_COSMETIC:
		winPenStyle |= win.PS_COSMETIC
	case core.PEN_TYPE_GEOMETRIC:
		winPenStyle |= win.PS_GEOMETRIC
	}

	switch style.CapStyle {
	case core.PEN_CAP_ROUND:
		winPenStyle |= win.PS_ENDCAP_ROUND
	case core.PEN_CAP_SQUARE:
		winPenStyle |= win.PS_ENDCAP_SQUARE
	case core.PEN_CAP_FLAT:
		winPenStyle |= win.PS_ENDCAP_FLAT
	}

	switch style.JoinStyle {
	case core.PEN_JOIN_ROUND:
		winPenStyle |= win.PS_JOIN_ROUND
	case core.PEN_JOIN_BEVEL:
		winPenStyle |= win.PS_JOIN_BEVEL
	case core.PEN_JOIN_MITER:
		winPenStyle |= win.PS_JOIN_MITER
	}
	return uint32(winPenStyle)
}


text:
namespace media {

// Register all JNI bindings necessary for media.
bool RegisterJni(JNIEnv* env);

}  // namespace media

#endif  // MEDIA_BASE_ANDROID_MEDIA_JNI_REGISTRAR_H_


text:
"""
    jinja2.parser
    ~~~~~~~~~~~~~

    Implements the template parser.

    :copyright: 2008 by Armin Ronacher.
    :license: BSD, see LICENSE for more details.
"""
from jinja2 import nodes
from jinja2.exceptions import TemplateSyntaxError, TemplateAssertionError

_statement_keywords = frozenset(['for', 'if', 'block', 'extends', 'print',
                                 'macro', 'include', 'from', 'import',
                                 'set'])
_compare_operators = frozenset(['eq', 'ne', 'lt', 'lteq', 'gt', 'gteq'])

class Parser(object):
    """This is the central parsing class Jinja2 uses.  It's passed to
    extensions and can be used to parse expressions or statements.
    """

    def __init__(self, environment, source, name=None, filename=None,
                 state=None):
        self.environment = environment
        self.stream = environment._tokenize(source, name, filename, state)
        self.name = name
        self.filename = filename
        self.closed = False
        self.extensions = {}
        for extension in environment.extensions.itervalues():
            for tag in extension.tags:
                self.extensions[tag] = extension.parse
        self._last_identifier = 0

    def fail(self, msg, lineno=None, exc=TemplateSyntaxError):
        """Convenience method that raises `exc` with the message, passed
        line number or last line number as well as the current name and
        filename.
        """
        if lineno is None:
            lineno = self.stream.current.lineno
        raise exc(msg, lineno, self.name, self.filename)

    def is_tuple_end(self, extra_end_rules=None):
        """Are we at the end of a tuple?"""
        if self.stream.current.type in ('variable_end', 'block_end', 'rparen'):
            return True
        elif extra_end_rules is not None:
            return self.stream.current.test_any(extra_end_rules)
        return False

    def free_identifier(self, lineno=None):
        """Return a new free identifier as :class:`~jinja2.nodes.InternalName`."""
        self._last_identifier += 1
        rv = object.__new__(nodes.InternalName)
        nodes.Node.__init__(rv, 'fi%d' % self._last_identifier, lineno=lineno)
        return rv

    def parse_statement(self):
        """Parse a single statement."""
        token = self.stream.current
        if token.type is not 'name':
            self.fail('tag name expected', token.lineno)
        if token.value in _statement_keywords:
            return getattr(self, 'parse_' + self.stream.current.value)()
        if token.value == 'call':
            return self.parse_call_block()
        if token.value == 'filter':
            return self.parse_filter_block()
        ext = self.extensions.get(token.value)
        if ext is not None:
            return ext(self)
        self.fail('unknown tag %r' % token.value, token.lineno)

    def parse_statements(self, end_tokens, drop_needle=False):
        """Parse multiple statements into a list until one of the end tokens
        is reached.  This is used to parse the body of statements as it also
        parses template data if appropriate.  The parser checks first if the
        current token is a colon and skips it if there is one.  Then it checks
        for the block end and parses until if one of the `end_tokens` is
        reached.  Per default the active token in the stream at the end of
        the call is the matched end token.  If this is not wanted `drop_needle`
        can be set to `True` and the end token is removed.
        """
        # the first token may be a colon for python compatibility
        self.stream.skip_if('colon')

        # in the future it would be possible to add whole code sections
        # by adding some sort of end of statement token and parsing those here.
        self.stream.expect('block_end')
        result = self.subparse(end_tokens)

        if drop_needle:
            self.stream.next()
        return result

    def parse_set(self):
        """Parse an assign statement."""
        lineno = self.stream.next().lineno
        target = self.parse_assign_target()
        self.stream.expect('assign')
        expr = self.parse_tuple()
        return nodes.Assign(target, expr, lineno=lineno)

    def parse_for(self):
        """Parse a for loop."""
        lineno = self.stream.expect('name:for').lineno
        target = self.parse_assign_target(extra_end_rules=('name:in',))
        self.stream.expect('name:in')
        iter = self.parse_tuple(with_condexpr=False,
                                extra_end_rules=('name:recursive',))
        test = None
        if self.stream.skip_if('name:if'):
            test = self.parse_expression()
        recursive = self.stream.skip_if('name:recursive')
        body = self.parse_statements(('name:endfor', 'name:else'))
        if self.stream.next().value == 'endfor':
            else_ = []
        else:
            else_ = self.parse_statements(('name:endfor',), drop_needle=True)
        return nodes.For(target, iter, body, else_, test,
                         recursive, lineno=lineno)

    def parse_if(self):
        """Parse an if construct."""
        node = result = nodes.If(lineno=self.stream.expect('name:if').lineno)
        while 1:
            node.test = self.parse_tuple(with_condexpr=False)
            node.body = self.parse_statements(('name:elif', 'name:else',
                                               'name:endif'))
            token = self.stream.next()
            if token.test('name:elif'):
                new_node = nodes.If(lineno=self.stream.current.lineno)
                node.else_ = [new_node]
                node = new_node
                continue
            elif token.test('name:else'):
                node.else_ = self.parse_statements(('name:endif',),
                                                   drop_needle=True)
            else:
                node.else_ = []
            break
        return result

    def parse_block(self):
        node = nodes.Block(lineno=self.stream.next().lineno)
        node.name = self.stream.expect('name').value
        node.body = self.parse_statements(('name:endblock',), drop_needle=True)
        self.stream.skip_if('name:' + node.name)
        return node

    def parse_extends(self):
        node = nodes.Extends(lineno=self.stream.next().lineno)
        node.template = self.parse_expression()
        return node

    def parse_import_context(self, node, default):
        if self.stream.current.test_any('name:with', 'name:without') and \
           self.stream.look().test('name:context'):
            node.with_context = self.stream.next().value == 'with'
            self.stream.skip()
        else:
            node.with_context = default
        return node

    def parse_include(self):
        node = nodes.Include(lineno=self.stream.next().lineno)
        node.template = self.parse_expression()
        return self.parse_import_context(node, True)

    def parse_import(self):
        node = nodes.Import(lineno=self.stream.next().lineno)
        node.template = self.parse_expression()
        self.stream.expect('name:as')
        node.target = self.parse_assign_target(name_only=True).name
        return self.parse_import_context(node, False)

    def parse_from(self):
        node = nodes.FromImport(lineno=self.stream.next().lineno)
        node.template = self.parse_expression()
        self.stream.expect('name:import')
        node.names = []

        def parse_context():
            if self.stream.current.value in ('with', 'without') and \
               self.stream.look().test('name:context'):
                node.with_context = self.stream.next().value == 'with'
                self.stream.skip()
                return True
            return False

        while 1:
            if node.names:
                self.stream.expect('comma')
            if self.stream.current.type is 'name':
                if parse_context():
                    break
                target = self.parse_assign_target(name_only=True)
                if target.name.startswith('_'):
                    self.fail('names starting with an underline can not '
                              'be imported', target.lineno,
                              exc=TemplateAssertionError)
                if self.stream.skip_if('name:as'):
                    alias = self.parse_assign_target(name_only=True)
                    node.names.append((target.name, alias.name))
                else:
                    node.names.append(target.name)
                if parse_context() or self.stream.current.type is not 'comma':
                    break
            else:
                break
        if not hasattr(node, 'with_context'):
            node.with_context = False
            self.stream.skip_if('comma')
        return node

    def parse_signature(self, node):
        node.args = args = []
        node.defaults = defaults = []
        self.stream.expect('lparen')
        while self.stream.current.type is not 'rparen':
            if args:
                self.stream.expect('comma')
            arg = self.parse_assign_target(name_only=True)
            arg.set_ctx('param')
            if self.stream.skip_if('assign'):
                defaults.append(self.parse_expression())
            args.append(arg)
        self.stream.expect('rparen')

    def parse_call_block(self):
        node = nodes.CallBlock(lineno=self.stream.next().lineno)
        if self.stream.current.type is 'lparen':
            self.parse_signature(node)
        else:
            node.args = []
            node.defaults = []

        node.call = self.parse_expression()
        if not isinstance(node.call, nodes.Call):
            self.fail('expected call', node.lineno)
        node.body = self.parse_statements(('name:endcall',), drop_needle=True)
        return node

    def parse_filter_block(self):
        node = nodes.FilterBlock(lineno=self.stream.next().lineno)
        node.filter = self.parse_filter(None, start_inline=True)
        node.body = self.parse_statements(('name:endfilter',),
                                          drop_needle=True)
        return node

    def parse_macro(self):
        node = nodes.Macro(lineno=self.stream.next().lineno)
        node.name = self.parse_assign_target(name_only=True).name
        self.parse_signature(node)
        node.body = self.parse_statements(('name:endmacro',),
                                          drop_needle=True)
        return node

    def parse_print(self):
        node = nodes.Output(lineno=self.stream.next().lineno)
        node.nodes = []
        while self.stream.current.type is not 'block_end':
            if node.nodes:
                self.stream.expect('comma')
            node.nodes.append(self.parse_expression())
        return node

    def parse_assign_target(self, with_tuple=True, name_only=False,
                            extra_end_rules=None):
        """Parse an assignment target.  As Jinja2 allows assignments to
        tuples, this function can parse all allowed assignment targets.  Per
        default assignments to tuples are parsed, that can be disable however
        by setting `with_tuple` to `False`.  If only assignments to names are
        wanted `name_only` can be set to `True`.  The `extra_end_rules`
        parameter is forwarded to the tuple parsing function.
        """
        if name_only:
            token = self.stream.expect('name')
            target = nodes.Name(token.value, 'store', lineno=token.lineno)
        else:
            if with_tuple:
                target = self.parse_tuple(simplified=True,
                                          extra_end_rules=extra_end_rules)
            else:
                target = self.parse_primary(with_postfix=False)
            target.set_ctx('store')
        if not target.can_assign():
            self.fail('can\'t assign to %r' % target.__class__.
                      __name__.lower(), target.lineno)
        return target

    def parse_expression(self, with_condexpr=True):
        """Parse an expression.  Per default all expressions are parsed, if
        the optional `with_condexpr` parameter is set to `False` conditional
        expressions are not parsed.
        """
        if with_condexpr:
            return self.parse_condexpr()
        return self.parse_or()

    def parse_condexpr(self):
        lineno = self.stream.current.lineno
        expr1 = self.parse_or()
        while self.stream.skip_if('name:if'):
            expr2 = self.parse_or()
            if self.stream.skip_if('name:else'):
                expr3 = self.parse_condexpr()
            else:
                expr3 = None
            expr1 = nodes.CondExpr(expr2, expr1, expr3, lineno=lineno)
            lineno = self.stream.current.lineno
        return expr1

    def parse_or(self):
        lineno = self.stream.current.lineno
        left = self.parse_and()
        while self.stream.skip_if('name:or'):
            right = self.parse_and()
            left = nodes.Or(left, right, lineno=lineno)
            lineno = self.stream.current.lineno
        return left

    def parse_and(self):
        lineno = self.stream.current.lineno
        left = self.parse_compare()
        while self.stream.skip_if('name:and'):
            right = self.parse_compare()
            left = nodes.And(left, right, lineno=lineno)
            lineno = self.stream.current.lineno
        return left

    def parse_compare(self):
        lineno = self.stream.current.lineno
        expr = self.parse_add()
        ops = []
        while 1:
            token_type = self.stream.current.type
            if token_type in _compare_operators:
                self.stream.next()
                ops.append(nodes.Operand(token_type, self.parse_add()))
            elif self.stream.skip_if('name:in'):
                ops.append(nodes.Operand('in', self.parse_add()))
            elif self.stream.current.test('name:not') and \
                 self.stream.look().test('name:in'):
                self.stream.skip(2)
                ops.append(nodes.Operand('notin', self.parse_add()))
            else:
                break
            lineno = self.stream.current.lineno
        if not ops:
            return expr
        return nodes.Compare(expr, ops, lineno=lineno)

    def parse_add(self):
        lineno = self.stream.current.lineno
        left = self.parse_sub()
        while self.stream.current.type is 'add':
            self.stream.next()
            right = self.parse_sub()
            left = nodes.Add(left, right, lineno=lineno)
            lineno = self.stream.current.lineno
        return left

    def parse_sub(self):
        lineno = self.stream.current.lineno
        left = self.parse_concat()
        while self.stream.current.type is 'sub':
            self.stream.next()
            right = self.parse_concat()
            left = nodes.Sub(left, right, lineno=lineno)
            lineno = self.stream.current.lineno
        return left

    def parse_concat(self):
        lineno = self.stream.current.lineno
        args = [self.parse_mul()]
        while self.stream.current.type is 'tilde':
            self.stream.next()
            args.append(self.parse_mul())
        if len(args) == 1:
            return args[0]
        return nodes.Concat(args, lineno=lineno)

    def parse_mul(self):
        lineno = self.stream.current.lineno
        left = self.parse_div()
        while self.stream.current.type is 'mul':
            self.stream.next()
            right = self.parse_div()
            left = nodes.Mul(left, right, lineno=lineno)
            lineno = self.stream.current.lineno
        return left

    def parse_div(self):
        lineno = self.stream.current.lineno
        left = self.parse_floordiv()
        while self.stream.current.type is 'div':
            self.stream.next()
            right = self.parse_floordiv()
            left = nodes.Div(left, right, lineno=lineno)
            lineno = self.stream.current.lineno
        return left

    def parse_floordiv(self):
        lineno = self.stream.current.lineno
        left = self.parse_mod()
        while self.stream.current.type is 'floordiv':
            self.stream.next()
            right = self.parse_mod()
            left = nodes.FloorDiv(left, right, lineno=lineno)
            lineno = self.stream.current.lineno
        return left

    def parse_mod(self):
        lineno = self.stream.current.lineno
        left = self.parse_pow()
        while self.stream.current.type is 'mod':
            self.stream.next()
            right = self.parse_pow()
            left = nodes.Mod(left, right, lineno=lineno)
            lineno = self.stream.current.lineno
        return left

    def parse_pow(self):
        lineno = self.stream.current.lineno
        left = self.parse_unary()
        while self.stream.current.type is 'pow':
            self.stream.next()
            right = self.parse_unary()
            left = nodes.Pow(left, right, lineno=lineno)
            lineno = self.stream.current.lineno
        return left

    def parse_unary(self):
        token_type = self.stream.current.type
        lineno = self.stream.current.lineno
        if token_type is 'name' and self.stream.current.value == 'not':
            self.stream.next()
            node = self.parse_unary()
            return nodes.Not(node, lineno=lineno)
        if token_type is 'sub':
            self.stream.next()
            node = self.parse_unary()
            return nodes.Neg(node, lineno=lineno)
        if token_type is 'add':
            self.stream.next()
            node = self.parse_unary()
            return nodes.Pos(node, lineno=lineno)
        return self.parse_primary()

    def parse_primary(self, with_postfix=True):
        token = self.stream.current
        if token.type is 'name':
            if token.value in ('true', 'false', 'True', 'False'):
                node = nodes.Const(token.value in ('true', 'True'),
                                   lineno=token.lineno)
            elif token.value in ('none', 'None'):
                node = nodes.Const(None, lineno=token.lineno)
            else:
                node = nodes.Name(token.value, 'load', lineno=token.lineno)
            self.stream.next()
        elif token.type is 'string':
            self.stream.next()
            buf = [token.value]
            lineno = token.lineno
            while self.stream.current.type is 'string':
                buf.append(self.stream.current.value)
                self.stream.next()
            node = nodes.Const(''.join(buf), lineno=lineno)
        elif token.type in ('integer', 'float'):
            self.stream.next()
            node = nodes.Const(token.value, lineno=token.lineno)
        elif token.type is 'lparen':
            self.stream.next()
            node = self.parse_tuple()
            self.stream.expect('rparen')
        elif token.type is 'lbracket':
            node = self.parse_list()
        elif token.type is 'lbrace':
            node = self.parse_dict()
        else:
            self.fail("unexpected token '%s'" % (token,), token.lineno)
        if with_postfix:
            node = self.parse_postfix(node)
        return node

    def parse_tuple(self, simplified=False, with_condexpr=True,
                    extra_end_rules=None):
        """Works like `parse_expression` but if multiple expressions are
        delimited by a comma a :class:`~jinja2.nodes.Tuple` node is created.
        This method could also return a regular expression instead of a tuple
        if no commas where found.

        The default parsing mode is a full tuple.  If `simplified` is `True`
        only names and literals are parsed.  The `no_condexpr` parameter is
        forwarded to :meth:`parse_expression`.

        Because tuples do not require delimiters and may end in a bogus comma
        an extra hint is needed that marks the end of a tuple.  For example
        for loops support tuples between `for` and `in`.  In that case the
        `extra_end_rules` is set to ``['name:in']``.
        """
        lineno = self.stream.current.lineno
        if simplified:
            parse = lambda: self.parse_primary(with_postfix=False)
        elif with_condexpr:
            parse = self.parse_expression
        else:
            parse = lambda: self.parse_expression(with_condexpr=False)
        args = []
        is_tuple = False
        while 1:
            if args:
                self.stream.expect('comma')
            if self.is_tuple_end(extra_end_rules):
                break
            args.append(parse())
            if self.stream.current.type is 'comma':
                is_tuple = True
            else:
                break
            lineno = self.stream.current.lineno
        if not is_tuple and args:
            return args[0]
        return nodes.Tuple(args, 'load', lineno=lineno)

    def parse_list(self):
        token = self.stream.expect('lbracket')
        items = []
        while self.stream.current.type is not 'rbracket':
            if items:
                self.stream.expect('comma')
            if self.stream.current.type == 'rbracket':
                break
            items.append(self.parse_expression())
        self.stream.expect('rbracket')
        return nodes.List(items, lineno=token.lineno)

    def parse_dict(self):
        token = self.stream.expect('lbrace')
        items = []
        while self.stream.current.type is not 'rbrace':
            if items:
                self.stream.expect('comma')
            if self.stream.current.type == 'rbrace':
                break
            key = self.parse_expression()
            self.stream.expect('colon')
            value = self.parse_expression()
            items.append(nodes.Pair(key, value, lineno=key.lineno))
        self.stream.expect('rbrace')
        return nodes.Dict(items, lineno=token.lineno)

    def parse_postfix(self, node):
        while 1:
            token_type = self.stream.current.type
            if token_type is 'dot' or token_type is 'lbracket':
                node = self.parse_subscript(node)
            elif token_type is 'lparen':
                node = self.parse_call(node)
            elif token_type is 'pipe':
                node = self.parse_filter(node)
            elif token_type is 'name' and self.stream.current.value == 'is':
                node = self.parse_test(node)
            else:
                break
        return node

    def parse_subscript(self, node):
        token = self.stream.next()
        if token.type is 'dot':
            attr_token = self.stream.current
            self.stream.next()
            if attr_token.type is 'name':
                return nodes.Getattr(node, attr_token.value, 'load',
                                     lineno=token.lineno)
            elif attr_token.type is not 'integer':
                self.fail('expected name or number', attr_token.lineno)
            arg = nodes.Const(attr_token.value, lineno=attr_token.lineno)
            return nodes.Getitem(node, arg, 'load', lineno=token.lineno)
        if token.type is 'lbracket':
            priority_on_attribute = False
            args = []
            while self.stream.current.type is not 'rbracket':
                if args:
                    self.stream.expect('comma')
                args.append(self.parse_subscribed())
            self.stream.expect('rbracket')
            if len(args) == 1:
                arg = args[0]
            else:
                arg = nodes.Tuple(args, self.lineno, self.filename)
            return nodes.Getitem(node, arg, 'load', lineno=token.lineno)
        self.fail('expected subscript expression', self.lineno)

    def parse_subscribed(self):
        lineno = self.stream.current.lineno

        if self.stream.current.type is 'colon':
            self.stream.next()
            args = [None]
        else:
            node = self.parse_expression()
            if self.stream.current.type is not 'colon':
                return node
            self.stream.next()
            args = [node]

        if self.stream.current.type is 'colon':
            args.append(None)
        elif self.stream.current.type not in ('rbracket', 'comma'):
            args.append(self.parse_expression())
        else:
            args.append(None)

        if self.stream.current.type is 'colon':
            self.stream.next()
            if self.stream.current.type not in ('rbracket', 'comma'):
                args.append(self.parse_expression())
            else:
                args.append(None)
        else:
            args.append(None)

        return nodes.Slice(lineno=lineno, *args)

    def parse_call(self, node):
        token = self.stream.expect('lparen')
        args = []
        kwargs = []
        dyn_args = dyn_kwargs = None
        require_comma = False

        def ensure(expr):
            if not expr:
                self.fail('invalid syntax for function call expression',
                          token.lineno)

        while self.stream.current.type is not 'rparen':
            if require_comma:
                self.stream.expect('comma')
                # support for trailing comma
                if self.stream.current.type is 'rparen':
                    break
            if self.stream.current.type is 'mul':
                ensure(dyn_args is None and dyn_kwargs is None)
                self.stream.next()
                dyn_args = self.parse_expression()
            elif self.stream.current.type is 'pow':
                ensure(dyn_kwargs is None)
                self.stream.next()
                dyn_kwargs = self.parse_expression()
            else:
                ensure(dyn_args is None and dyn_kwargs is None)
                if self.stream.current.type is 'name' and \
                    self.stream.look().type is 'assign':
                    key = self.stream.current.value
                    self.stream.skip(2)
                    value = self.parse_expression()
                    kwargs.append(nodes.Keyword(key, value,
                                                lineno=value.lineno))
                else:
                    ensure(not kwargs)
                    args.append(self.parse_expression())

            require_comma = True
        self.stream.expect('rparen')

        if node is None:
            return args, kwargs, dyn_args, dyn_kwargs
        return nodes.Call(node, args, kwargs, dyn_args, dyn_kwargs,
                          lineno=token.lineno)

    def parse_filter(self, node, start_inline=False):
        while self.stream.current.type == 'pipe' or start_inline:
            if not start_inline:
                self.stream.next()
            token = self.stream.expect('name')
            name = token.value
            while self.stream.current.type is 'dot':
                self.stream.next()
                name += '.' + self.stream.expect('name').value
            if self.stream.current.type is 'lparen':
                args, kwargs, dyn_args, dyn_kwargs = self.parse_call(None)
            else:
                args = []
                kwargs = []
                dyn_args = dyn_kwargs = None
            node = nodes.Filter(node, name, args, kwargs, dyn_args,
                                dyn_kwargs, lineno=token.lineno)
            start_inline = False
        return node

    def parse_test(self, node):
        token = self.stream.next()
        if self.stream.current.test('name:not'):
            self.stream.next()
            negated = True
        else:
            negated = False
        name = self.stream.expect('name').value
        while self.stream.current.type is 'dot':
            self.stream.next()
            name += '.' + self.stream.expect('name').value
        dyn_args = dyn_kwargs = None
        kwargs = []
        if self.stream.current.type is 'lparen':
            args, kwargs, dyn_args, dyn_kwargs = self.parse_call(None)
        elif self.stream.current.type in ('name', 'string', 'integer',
                                          'float', 'lparen', 'lbracket',
                                          'lbrace') and not \
             self.stream.current.test_any('name:else', 'name:or',
                                          'name:and'):
            if self.stream.current.test('name:is'):
                self.fail('You cannot chain multiple tests with is')
            args = [self.parse_expression()]
        else:
            args = []
        node = nodes.Test(node, name, args, kwargs, dyn_args,
                          dyn_kwargs, lineno=token.lineno)
        if negated:
            node = nodes.Not(node, lineno=token.lineno)
        return node

    def subparse(self, end_tokens=None):
        body = []
        data_buffer = []
        add_data = data_buffer.append

        def flush_data():
            if data_buffer:
                lineno = data_buffer[0].lineno
                body.append(nodes.Output(data_buffer[:], lineno=lineno))
                del data_buffer[:]

        while self.stream:
            token = self.stream.current
            if token.type is 'data':
                if token.value:
                    add_data(nodes.TemplateData(token.value,
                                                lineno=token.lineno))
                self.stream.next()
            elif token.type is 'variable_begin':
                self.stream.next()
                add_data(self.parse_tuple(with_condexpr=True))
                self.stream.expect('variable_end')
            elif token.type is 'block_begin':
                flush_data()
                self.stream.next()
                if end_tokens is not None and \
                   self.stream.current.test_any(*end_tokens):
                    return body
                rv = self.parse_statement()
                if isinstance(rv, list):
                    body.extend(rv)
                else:
                    body.append(rv)
                self.stream.expect('block_end')
            else:
                raise AssertionError('internal parsing error')

        flush_data()
        return body

    def parse(self):
        """Parse the whole template into a `Template` node."""
        result = nodes.Template(self.subparse(), lineno=1)
        result.set_environment(self.environment)
        return result


text:
module.exports = TCPPool

var arrayRemove = require('unordered-array-remove')
var debug = require('debug')('webtorrent:tcp-pool')
var net = require('net') // browser exclude

var Peer = require('./peer')

/**
 * Shared TCP pools; shared among all swarms
 * @type {Object} port: number -> pool: TCPPool
 */
var tcpPools = {}

/**
 * TCPPool
 *
 * A "TCP pool" allows multiple swarms to listen on the same TCP port and determines
 * which swarm incoming connections are intended for by inspecting the bittorrent
 * handshake that the remote peer sends.
 *
 * @param {number} port
 * @param {string} hostname
 */
function TCPPool (port, hostname) {
  var self = this

  self.port = port
  self.listening = false
  self.swarms = {} // infoHash (hex) -> Swarm

  debug('new TCPPool (port: %s, hostname: %s)', port, hostname)

  // Save incoming conns so they can be destroyed if server is closed before the conn is
  // passed off to a Swarm.
  self.pendingConns = []

  self.server = net.createServer()
  self.server.on('connection', function (conn) { self._onConnection(conn) })
  self.server.on('error', function (err) { self._onError(err) })
  self.server.on('listening', function () { self._onListening() })
  self.server.listen(self.port, hostname)
}

/**
 * STATIC METHOD
 * Add a swarm to a pool, creating a new pool if necessary.
 * @param {Swarm} swarm
 */
TCPPool.addSwarm = function (swarm) {
  var pool = tcpPools[swarm._port]
  if (!pool) pool = tcpPools[swarm._port] = new TCPPool(swarm._port, swarm._hostname)
  pool.addSwarm(swarm)
  return pool
}

/**
 * STATIC METHOD
 * Remove a swarm from its pool.
 * @param {Swarm} swarm
 */
TCPPool.removeSwarm = function (swarm, cb) {
  var pool = tcpPools[swarm._port]
  if (!pool) return cb()
  pool.removeSwarm(swarm)

  if (Object.keys(pool.swarms).length === 0) pool.destroy(cb)
  else process.nextTick(cb)
}

/**
 * STATIC METHOD
 * When `Swarm.prototype.listen` is called without specifying a port, a reasonable
 * default port must be chosen. If there already exists an active TCP pool, then return
 * that pool's port so that TCP server can be re-used. Otherwise, return 0 so node will
 * pick a free port.
 *
 * @return {number} port
 */
TCPPool.getDefaultListenPort = function (infoHash) {
  for (var port in tcpPools) {
    var pool = tcpPools[port]
    if (!pool.swarms[infoHash]) return pool.port
  }
  return 0
}

/**
 * Add a swarm to this TCP pool.
 * @param {Swarm} swarm
 */
TCPPool.prototype.addSwarm = function (swarm) {
  var self = this

  if (self.swarms[swarm.infoHash]) {
    process.nextTick(function () {
      swarm._onError(new Error(
        'There is already a swarm with info hash ' + swarm.infoHash + ' ' +
        'listening on port ' + swarm._port
      ))
    })
    return
  }

  self.swarms[swarm.infoHash] = swarm

  if (self.listening) {
    process.nextTick(function () {
      swarm._onListening(self.port)
    })
  }

  debug('add swarm %s to tcp pool %s', swarm.infoHash, self.port)
}

/**
 * Remove a swarm from this TCP pool.
 * @param  {Swarm} swarm
 */
TCPPool.prototype.removeSwarm = function (swarm) {
  var self = this
  debug('remove swarm %s from tcp pool %s', swarm.infoHash, self.port)
  delete self.swarms[swarm.infoHash]
}

/**
 * Destroy this TCP pool.
 * @param  {function} cb
 */
TCPPool.prototype.destroy = function (cb) {
  var self = this
  debug('destroy tcp pool %s', self.port)

  self.listening = false

  // Destroy all open connection objects so server can close gracefully without waiting
  // for connection timeout or remote peer to disconnect.
  self.pendingConns.forEach(function (conn) {
    conn.destroy()
  })

  delete tcpPools[self.port]

  try {
    self.server.close(cb)
  } catch (err) {
    if (cb) process.nextTick(cb)
  }
}

TCPPool.prototype._onListening = function () {
  var self = this

  // Fix for Docker Node image. Sometimes server.address() returns `null`.
  // See issue: https://github.com/feross/bittorrent-swarm/pull/18
  var address = self.server.address() || { port: 0 }
  var port = address.port

  debug('tcp pool listening on %s', port)

  if (port !== self.port) {
    // `port` was 0 when `listen` was called; update to the port that node selected
    delete tcpPools[self.port]
    self.port = port
    tcpPools[self.port] = self
  }

  self.listening = true

  for (var infoHash in self.swarms) {
    self.swarms[infoHash]._onListening(self.port)
  }
}

/**
 * On incoming connections, we expect the remote peer to send a handshake first. Based
 * on the infoHash in that handshake, route the peer to the right swarm.
 */
TCPPool.prototype._onConnection = function (conn) {
  var self = this

  // If the connection has already been closed before the `connect` event is fired,
  // then `remoteAddress` will not be available, and we can't use this connection.
  // - Node.js issue: https://github.com/nodejs/node-v0.x-archive/issues/7566
  // - WebTorrent issue: https://github.com/feross/webtorrent/issues/398
  if (!conn.remoteAddress) {
    conn.on('error', noop)
    conn.destroy()
    return
  }

  self.pendingConns.push(conn)
  conn.once('close', removePendingConn)

  function removePendingConn () {
    arrayRemove(self.pendingConns, self.pendingConns.indexOf(conn))
  }

  var peer = Peer.createTCPIncomingPeer(conn)

  peer.wire.once('handshake', function (infoHash, peerId) {
    removePendingConn()
    conn.removeListener('close', removePendingConn)

    var swarm = self.swarms[infoHash]
    if (swarm) {
      peer.swarm = swarm
      swarm._addIncomingPeer(peer)
      peer.onHandshake(infoHash, peerId)
    } else {
      var err = new Error('Unexpected info hash ' + infoHash + ' from incoming peer ' +
        peer.id + ': destroying peer')
      peer.destroy(err)
    }
  })
}

TCPPool.prototype._onError = function (err) {
  var self = this
  self.destroy()
  for (var infoHash in self.swarms) {
    var swarm = self.swarms[infoHash]
    self.removeSwarm(swarm)
    swarm._onError(err)
  }
}

function noop () {}


text:
package com.sdhu.elasticsearchprediction.spark
package test

import com.mahisoft.elasticsearchprediction._
import utils.DataProperties
import plugin.domain.IndexValue
import plugin.exception.PredictionException
import plugin.engine.PredictorEngine

import org.apache.spark._
import rdd.RDD
import mllib.regression._
import mllib.classification._

import org.scalatest._
import com.holdenkarau.spark.testing._
import java.io.File
import java.util.Collection

import scala.collection.JavaConversions._

class SparkPredictorEngineSpec extends FlatSpec with MustMatchers {
  val pconf = getClass.getResource("/prop1.conf").getPath
  val dataP = getClass.getResource("/mini.csv").toURI.toString
  val dp = new DataProperties(pconf)
  val modelP = getClass.getResource("/spark-clf-test.model").getPath
  val clf_type = "spark.logistic-regression"

  "Predictor Engine" should "throw empty model exception" in {
    val eng = new SparkPredictorEngine(modelP, SVM_Helper)
    evaluating {eng.getPrediction(List[IndexValue]())} must produce [PredictionException]
  }

//  "Spark_PredictorEngine" should "return sparkPredictorEngine of svm type" in {
//    val speng = new Spark_PredictorEngine(modelP, "spark.svm")
//    speng.getSparkPredictorEngine mustBe a [SparkPredictorEngine[_]]
//
//  }

  it should "return a generic PredictorEngine" in {
    val speng = new Spark_PredictorEngine(modelP, "spark.svm")
    speng.getPredictorEngine mustBe a [PredictorEngine]
  }

  it should "load the classifier" in {
    val speng = new Spark_PredictorEngine(modelP, clf_type)
    val eng = speng.getSparkPredictorEngine
    val m = eng.getModel
    val cm = m.categoriesMap.getOrElse(Map[String, Double]())

    m.clf must not be empty
    //m.numClasses must be(Some(2))
    //m.binThreshold must be(Some(0.5))
    cm.keys must contain allOf("Female", "Male", "United-States", "China")
  }

  it should "evaluate values" in {
    val speng = new Spark_PredictorEngine(modelP, clf_type)
    val eng = speng.getSparkPredictorEngine

    val p0 = Array("50", "Self-emp-not-inc", "Male", "0", "0", "United-States")
    val cindv = ReadUtil.arr2CIndVal(p0)

    val check = eng.getPrediction(cindv)

    check must equal(0.0)
    check mustBe a [java.lang.Double]
  }

  it should "evaluate values using generic Predictor engine" in {
    val speng = new Spark_PredictorEngine(modelP, clf_type)
    val eng = speng.getPredictorEngine

    val p0 = Array("50", "Self-emp-not-inc", "Male", "0", "0", "United-States")
    val cindv = ReadUtil.arr2CIndVal(p0)

    val check = eng.getPrediction(cindv)

    check must equal(0.0)
    check mustBe a [java.lang.Double]
  }
}


text:
layout          : blocks/page-participant
title           : Kim Carter
type            : participant-remote
travel-from     :
expenses        : owasp
funded          : no
funded-who      : Summit Budget
flight-cost     : 1000
ticket-cost     : 1500
funded-amount   : 1250 (Summit Budget)
required-funds  : 2500
project-leader  :
chapter-leader  :
job-title       : Security focussed Technologist
image           : https://avatars0.githubusercontent.com/u/2862029
twitter         : binarymist
status          : done
---

## Kim Carter

NodeGoat is the next gen WebGoat, written in NodeJS, It comes with a tutorial covering the OWASP Top 10 + other vulnerabilities. NodeGoat also has a Security Regression Testing Proof of Concept (PoC) using the Zap API which is getting a lot of use in [training teams](https://blog.binarymist.net/presentations-publications/) around the importance of moving security from the most expensive place (go-live) to the cheapest (within the Development Teams Sprints). Based on [this PoC](https://github.com/binarymist/NodeGoat/wiki/Security-Regression-Testing-with-Zap-API), I've sold and implemented Security Regression Testing with Zap API within a large international companies development team and seen amazing results. I would like to move this forward, increase the coverage, add defect features, get all components and their docker images working in a nightly build to further demonstrate the huge advantages of moving security left and also demonstrate how useful Zap can be in the build process.

I would like to propose a NodeGoat workshop. The action plan is [here](http://owaspsummit.org/Working-Sessions/Project-Summit/NodeGoat.html).

The skills required for the following Working-Sessions appear to match my skill-set, and I would love to play a part in helping with them:

1. [OWASP NodeGoat](https://github.com/owasp/nodegoat)
2. [AWS Lamba Security](http://owaspsummit.org/Working-Sessions/Tools/AWS-Lambda-Security.html)
3. [NextGen Security Scanners](http://owaspsummit.org/Working-Sessions/Tools/NextGen-SecurityScanners.html)
4. [ZAP](http://owaspsummit.org/Working-Sessions/Project-Summit/ZAP.html)
5. [Threat Model](http://owaspsummit.org/Working-Sessions/Threat-Model/)
6. [Mobile Security](http://owaspsummit.org/Working-Sessions/Mobile-Security/)

I would need flights and accommodation provided by OWASP as I've been working for the love of security in our industry mostly on my book series "Holistic Info-Sec for Web Developers" without income for many months - please let me know soon if this will be possible, as I will need to announce and prepare the workshop, and refrain from submitting further presentations and Working-Sessions around these dates.

* [BinaryMist](https://binarymist.io/)
* [Blog](https://blog.binarymist.net/)
* [Regular Working-Sessions and presentations](https://blog.binarymist.net/presentations-publications/)
* [Author of three (free and paid) web security books](https://leanpub.com/b/holisticinfosecforwebdevelopers)
* [LinkedIn](https://nz.linkedin.com/in/carterkim)
* Twitter: [@binarymist](https://twitter.com/binarymist)

#### OWASP Contributions

* [Organise and run the annual OWASP NZ Day conference](https://www.owasp.org/index.php?title=OWASP_New_Zealand_Day_2017)
* [OWASP NodeGoat](https://github.com/owasp/nodegoat) Core Contributor
* Contributed to ZapAPI
* [OWASP New Zealand Chapter Leader](https://www.owasp.org/index.php/New_Zealand)
* [Organise and run regular OWASP Meetups](https://www.meetup.com/OWASP-New-Zealand-Chapter-Christchurch/)
* Run presentations and Working-Sessions on using OWASP projects at international OWASP events
  - [New York](https://www.meetup.com/owaspnycnj/events/228716474/)
  - [New Zealand](https://blog.binarymist.net/presentations-publications/#whats-our-software-doing-with-all-that-user-input)
  - Others?


text:
<?xml version='1.0' encoding='utf-8'?>

<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

	<session-factory>

		<!-- Database connection settings -->
		<property name="connection.driver_class">org.apache.derby.jdbc.ClientDriver</property>
		<property name="connection.url">jdbc:derby://127.0.0.1:1333/OpenStorage;create=false;</property>

<!--
		<property name="connection.username"></property>
		<property name="connection.password"></property>
-->

		<property name="hibernate.default_schema">UNO</property>

		<property name="hibernate.enable_lazy_load_no_trans">true</property>

		<!-- JDBC connection pool (use the built-in) -->
		<property name="connection.pool_size">1</property>

		<!-- SQL dialect -->
		<property name="dialect">org.hibernate.dialect.DerbyDialect</property>

		<!-- Disable the second-level cache -->
		<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>

		<!-- Echo all executed SQL to stdout -->
		<property name="show_sql">true</property>

		<property name="hbm2ddl.auto">update</property>

 		<mapping class="ru.vm.berryville.j2eewebix.Car" />
        	<mapping class="ru.vm.berryville.j2eewebix.Manufacturer" />
        	<mapping class="ru.vm.berryville.j2eewebix.Image" />

	</session-factory>

</hibernate-configuration>


text:
import * as path from 'path';
import * as webpack from 'webpack';
import {findLazyModules} from './find-lazy-modules';
import {AotPlugin} from '@ngtools/webpack';

const atl = require('awesome-typescript-loader');

const g: any = global;
const webpackLoader: string = g['angularCliIsLocal']
  ? g.angularCliPackages['@ngtools/webpack'].main
  : '@ngtools/webpack';

export const getWebpackNonAotConfigPartial = function(projectRoot: string, appConfig: any) {
  const appRoot = path.resolve(projectRoot, appConfig.root);
  const lazyModules = findLazyModules(appRoot);

  return {
    resolve: {
      plugins: [
        new atl.TsConfigPathsPlugin({
          tsconfig: path.resolve(appRoot, appConfig.tsconfig)
        })
      ]
    },
    module: {
      rules: [
        {
          test: /\.ts$/,
          loaders: [{
            loader: 'awesome-typescript-loader',
            query: {
              forkChecker: true,
              tsconfig: path.resolve(appRoot, appConfig.tsconfig)
            }
          }, {
            loader: 'angular2-template-loader'
          }],
          exclude: [/\.(spec|e2e)\.ts$/]
        }
      ],
    },
    plugins: [
      new webpack.ContextReplacementPlugin(/.*/, appRoot, lazyModules),
      new atl.ForkCheckerPlugin(),
    ]
  };
};

export const getWebpackAotConfigPartial = function(projectRoot: string, appConfig: any) {
  return {
    module: {
      rules: [
        {
          test: /\.ts$/,
          loader: webpackLoader,
          exclude: [/\.(spec|e2e)\.ts$/]
        }
      ]
    },
    plugins: [
      new AotPlugin({
        tsConfigPath: path.resolve(projectRoot, appConfig.root, appConfig.tsconfig),
        mainPath: path.join(projectRoot, appConfig.root, appConfig.main)
      }),
    ]
  };
};


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package de.fdloch.jhotkeyserver.gui;

import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.LayoutManager;
import java.util.ArrayList;

/**
 *
 * @author Florian
 */
public class ListLayout implements LayoutManager {

    private final int leftMargin;
    private final int topMargin;
    private final int vGap;

    public ListLayout(int leftMargin, int topMargin, int vGap) {
        this.leftMargin = leftMargin;
        this.topMargin = topMargin;
        this.vGap = vGap;
    }

    @Override
    public void addLayoutComponent(String name, Component comp) {}

    @Override
    public void removeLayoutComponent(Component comp) {}

    @Override
    public Dimension preferredLayoutSize(Container parent) {
        int prefHeight = this.topMargin;
        int maxWidth = 0;

        for (Component com : parent.getComponents()) {
            prefHeight += com.getPreferredSize().height;

            if (com.getPreferredSize().width > maxWidth) {
                maxWidth = com.getPreferredSize().width;
            }
        }

        prefHeight += this.vGap * (parent.getComponentCount() - 1);

        return new Dimension(maxWidth, prefHeight);
    }

    @Override
    public Dimension minimumLayoutSize(Container parent) {
        return this.preferredLayoutSize(parent);
    }

    @Override
    public void layoutContainer(Container parent) {
        int heightOffset = this.topMargin;

        for (Component com : parent.getComponents()) {
            Dimension d = com.getPreferredSize();

            com.setBounds(this.leftMargin, heightOffset, d.width, d.height);

            heightOffset = heightOffset +  com.getHeight() + this.vGap;
        }
    }

}


text:
<?php

namespace TMPHP\RestApiGenerators;

use Illuminate\Support\Facades\Log;
use Illuminate\Support\ServiceProvider;
use TMPHP\RestApiGenerators\Commands\IdeHelperCommand;
use TMPHP\RestApiGenerators\Commands\MakeAuthGroupsAndActionsCommand;
use TMPHP\RestApiGenerators\Commands\MakeCrudControllersCommand;
use TMPHP\RestApiGenerators\Commands\MakeCrudModelsCommand;
use TMPHP\RestApiGenerators\Commands\MakeCrudRoutesCommand;
use TMPHP\RestApiGenerators\Commands\MakeCrudTransformersCommand;
use TMPHP\RestApiGenerators\Commands\MakeImageManagerCommand;
use TMPHP\RestApiGenerators\Commands\MakeRestApiProjectCommand;
use TMPHP\RestApiGenerators\Commands\MakeRestAuthCommand;
use TMPHP\RestApiGenerators\Commands\MakeSwaggerModelsCommand;
use TMPHP\RestApiGenerators\Commands\MakeSwaggerRootCommand;

/**
 * Class GeneratorsServiceProviders
 * @package TMPHP\RestApiGenerators
 */
class GeneratorsServiceProviders extends ServiceProvider
{
    /**
     * Bootstrap the application services. //testing commit
     *
     * @return void
     */
    public function boot()
    {
        //publishing configs
        $this->publishes(
            [
                __DIR__ . '/../config/rest-api-generator.php' => config_path('rest-api-generator.php'),
            ]
        );

        //register generated routes
        $apiRouteFilePath = base_path(config('rest-api-generator.paths.routes'). 'api.php');
        if (!$this->app->routesAreCached() && file_exists($apiRouteFilePath)) {
            require $apiRouteFilePath;
        }

        //register generated auth routes
        $authRouteFilePath = base_path(config('rest-api-generator.paths.routes'). 'auth.php');
        if (!$this->app->routesAreCached() && file_exists($authRouteFilePath)) {
            require $authRouteFilePath;
        }

        //register generated image management routes
        $imageRouteFilePath = base_path(config('rest-api-generator.paths.routes'). 'images.php');
        if (!$this->app->routesAreCached() && file_exists($imageRouteFilePath)) {
            require $imageRouteFilePath;
        }
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        $this->registerCommands();

        if ($this->app->environment() !== 'production') {
            $this->app->register(\Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider::class);
        }
    }

    /**
     * Register commands.
     *
     * @return void
     */
    protected function registerCommands()
    {
        $this->commands([
            MakeCrudRoutesCommand::class,
            MakeSwaggerModelsCommand::class,
            MakeCrudModelsCommand::class,
            MakeCrudControllersCommand::class,
            MakeCrudTransformersCommand::class,
            MakeRestApiProjectCommand::class,
            MakeSwaggerRootCommand::class,
            MakeRestAuthCommand::class,
            MakeAuthGroupsAndActionsCommand::class,
            IdeHelperCommand::class,
            MakeImageManagerCommand::class,
        ]);
    }

}


text:
package hu.akarnokd.reactive4javaflow.impl.operators;

import hu.akarnokd.reactive4javaflow.*;
import org.junit.Test;

import java.io.IOException;

public class FolyamScanTest {

    @Test
    public void standard() {
        TestHelper.assertResult(
                Folyam.range(1, 5)
                        .scan((a, b) -> a + b),
                1, 3, 6, 10, 15
        );
    }

    @Test
    public void standardHidden() {
        TestHelper.assertResult(
                Folyam.range(1, 5).hide()
                        .scan((a, b) -> a + b),
                1, 3, 6, 10, 15
        );
    }

    @Test
    public void error() {
        TestHelper.assertFailureComposed(-1,
                f -> f.scan((a, b) -> a + b), IOException.class);
    }

    @Test
    public void scannerCrash() {
        Folyam.range(1, 2)
                .scan((a, b) -> { throw new IOException(); })
                .test()
                .assertFailure(IOException.class, 1);
    }

    @Test
    public void scannerCrashConditional() {
        Folyam.range(1, 2)
                .scan((a, b) -> { throw new IOException(); })
                .filter(v -> true)
                .test()
                .assertFailure(IOException.class, 1);
    }

    @Test
    public void checkBadSource() {
        TestHelper.checkBadSource(f -> f.scan((a, b) -> a + b));
    }
}


text:
var convert = require('./convert'),
    func = convert('forOwn', require('../forOwn'));

func.placeholder = require('./placeholder');
module.exports = func;


text:
package com.intellij.openapi.diff.impl.dir;

import com.intellij.diff.tools.util.DiffDataKeys;
import com.intellij.ide.DataManager;
import com.intellij.ide.diff.DiffElement;
import com.intellij.ide.diff.DiffType;
import com.intellij.ide.diff.DirDiffElement;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.diff.impl.dir.actions.DirDiffToolbarActions;
import com.intellij.openapi.diff.impl.dir.actions.RefreshDirDiffAction;
import com.intellij.openapi.fileEditor.OpenFileDescriptor;
import com.intellij.openapi.keymap.KeymapUtil;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.TextFieldWithBrowseButton;
import com.intellij.openapi.ui.popup.Balloon;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.wm.IdeFocusManager;
import com.intellij.ui.ClickListener;
import com.intellij.ui.FilterComponent;
import com.intellij.ui.PopupHandler;
import com.intellij.ui.TableSpeedSearch;
import com.intellij.ui.awt.RelativePoint;
import com.intellij.ui.components.JBLabel;
import com.intellij.ui.components.JBLoadingPanel;
import com.intellij.ui.components.JBLoadingPanelListener;
import com.intellij.ui.table.JBTable;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.diff.FilesTooBigForDiffException;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import javax.swing.text.JTextComponent;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author Konstantin Bulenkov
 */
@SuppressWarnings({"unchecked"})
public class DirDiffPanel implements Disposable, DataProvider {
  public static final String DIVIDER_PROPERTY = "dir.diff.panel.divider.location";
  private JPanel myDiffPanel;
  private JBTable myTable;
  private JPanel myComponent;
  private JSplitPane mySplitPanel;
  private TextFieldWithBrowseButton mySourceDirField;
  private TextFieldWithBrowseButton myTargetDirField;
  private JBLabel myTargetDirLabel;
  private JBLabel mySourceDirLabel;
  private JPanel myToolBarPanel;
  private JPanel myRootPanel;
  private JPanel myFilterPanel;
  private JBLabel myFilterLabel;
  private JPanel myFilesPanel;
  private JPanel myHeaderPanel;
  private FilterComponent myFilter;
  private final DirDiffTableModel myModel;
  public JLabel myErrorLabel;
  private final DirDiffWindow myDiffWindow;
  private JComponent myDiffPanelComponent;
  private JComponent myViewComponent;
  private DiffElement myCurrentElement;
  private String oldFilter;
  public static final DataKey<DirDiffTableModel> DIR_DIFF_MODEL = DataKey.create("DIR_DIFF_MODEL");
  public static final DataKey<JTable> DIR_DIFF_TABLE = DataKey.create("DIR_DIFF_TABLE");

  public DirDiffPanel(DirDiffTableModel model, DirDiffWindow wnd) {
    myModel = model;
    myDiffWindow = wnd;
    mySourceDirField.setText(model.getSourceDir().getPath());
    myTargetDirField.setText(model.getTargetDir().getPath());
    mySourceDirField.setBorder(JBUI.Borders.emptyRight(8));
    myTargetDirField.setBorder(JBUI.Borders.emptyRight(12));
    mySourceDirLabel.setIcon(model.getSourceDir().getIcon());
    myTargetDirLabel.setIcon(model.getTargetDir().getIcon());
    myTargetDirLabel.setBorder(JBUI.Borders.emptyLeft(8));
    myModel.setTable(myTable);
    myModel.setPanel(this);
    Disposer.register(this, myModel);
    myTable.setModel(myModel);
    new TableSpeedSearch(myTable);

    final DirDiffTableCellRenderer renderer = new DirDiffTableCellRenderer();
    myTable.setExpandableItemsEnabled(false);
    myTable.setDefaultRenderer(Object.class, renderer);
    myTable.getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    final Project project = myModel.getProject();
    myTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
      @Override
      public void valueChanged(ListSelectionEvent e) {
        final int lastIndex = e.getLastIndex();
        final int firstIndex = e.getFirstIndex();
        final DirDiffElementImpl last = myModel.getElementAt(lastIndex);
        final DirDiffElementImpl first = myModel.getElementAt(firstIndex);
        if (last == null || first == null) {
          update(false);
          return;
        }
        if (last.isSeparator()) {
          final int ind = lastIndex + ((lastIndex < firstIndex) ? 1 : -1);
          myTable.getSelectionModel().addSelectionInterval(ind, ind);
        }
        else if (first.isSeparator()) {
          final int ind = firstIndex + ((firstIndex < lastIndex) ? 1 : -1);
          myTable.getSelectionModel().addSelectionInterval(ind, ind);
        }
        else {
          update(false);
        }
        myDiffWindow.setTitle(myModel.getTitle());
      }
    });
    if (model.isOperationsEnabled()) {
      new AnAction("Change diff operation") {
        @Override
        public void actionPerformed(AnActionEvent e) {
          changeOperationForSelection();
        }
      }.registerCustomShortcutSet(CustomShortcutSet.fromString("SPACE"), myTable);
      new ClickListener() {
        @Override
        public boolean onClick(@NotNull MouseEvent e, int clickCount) {
          if (e.getButton() == MouseEvent.BUTTON3) return false;
          if (myTable.getRowCount() > 0) {
            final int row = myTable.rowAtPoint(e.getPoint());
            final int col = myTable.columnAtPoint(e.getPoint());

            if (row != -1 && col == ((myTable.getColumnCount() - 1) / 2)) {
              changeOperationForSelection();
            }
          }
          return true;
        }
      }.installOn(myTable);

    }
    myTable.addKeyListener(new KeyAdapter() {
      @Override
      public void keyPressed(KeyEvent e) {
        final int keyCode = e.getKeyCode();
        final int rowCount = myTable.getRowCount();
        int row = myTable.getSelectionModel().getLeadSelectionIndex();
        final int[] rows = myTable.getSelectedRows();
        if (rows.length == 0) return;
        if (keyCode == KeyEvent.VK_DOWN && row < rowCount - 1) {
          row++;
          final DirDiffElementImpl element = myModel.getElementAt(row);
          if (element == null) return;
          if (element.isSeparator()) {
            row++;
          }
        }
        else if (keyCode == KeyEvent.VK_UP && row > 0) {
          row--;
          final DirDiffElementImpl element = myModel.getElementAt(row);
          if (element == null) return;
          if (element.isSeparator()) {
            row--;
          }
        }
        else {
          return;
        }
        final DirDiffElementImpl element = myModel.getElementAt(row);
        if (element == null) return;
        if (!element.isSeparator()) {
          e.consume();
          myTable.changeSelection(row, (myModel.getColumnCount() - 1) / 2, false, e.isShiftDown());
        }
      }
    });
    final TableColumnModel columnModel = myTable.getColumnModel();
    final TableColumn operationColumn = columnModel.getColumn((columnModel.getColumnCount() - 1) / 2);
    operationColumn.setMaxWidth(JBUI.scale(25));
    operationColumn.setMinWidth(JBUI.scale(25));
    for (int i = 0; i < columnModel.getColumnCount(); i++) {
      final String name = myModel.getColumnName(i);
      final TableColumn column = columnModel.getColumn(i);
      if (DirDiffTableModel.COLUMN_DATE.equals(name)) {
        column.setMaxWidth(JBUI.scale(90));
        column.setMinWidth(JBUI.scale(90));
      } else if (DirDiffTableModel.COLUMN_SIZE.equals(name)) {
        column.setMaxWidth(JBUI.scale(120));
        column.setMinWidth(JBUI.scale(120));
      }
    }
    final DirDiffToolbarActions actions = new DirDiffToolbarActions(myModel, myDiffPanel);
    final ActionManager actionManager = ActionManager.getInstance();
    final ActionToolbar toolbar = actionManager.createActionToolbar("DirDiff", actions, true);
    registerCustomShortcuts(actions, myTable);
    myToolBarPanel.add(toolbar.getComponent(), BorderLayout.CENTER);
    final JBLabel label = new JBLabel("Use Space button or mouse click to change operation for the selected elements. Enter to perform.", SwingConstants.CENTER);
    label.setForeground(UIUtil.getInactiveTextColor());
    UIUtil.applyStyle(UIUtil.ComponentStyle.MINI, label);
    DataManager.registerDataProvider(myFilesPanel, this);
    myTable.addMouseListener(new PopupHandler() {
      @Override
      public void invokePopup(Component comp, int x, int y) {
        final JPopupMenu popupMenu =
          actionManager.createActionPopupMenu("DirDiffPanel", (ActionGroup)actionManager.getAction("DirDiffMenu")).getComponent();
        popupMenu.show(comp, x, y);
      }
    });
    myFilesPanel.add(label, BorderLayout.SOUTH);
    final JBLoadingPanel loadingPanel = new JBLoadingPanel(new BorderLayout(), wnd.getDisposable());
    loadingPanel.addListener(new JBLoadingPanelListener.Adapter() {
      boolean showHelp = true;

      @Override
      public void onLoadingFinish() {
        if (showHelp && myModel.isOperationsEnabled() && myModel.getRowCount() > 0) {
          final long count = PropertiesComponent.getInstance().getOrInitLong("dir.diff.space.button.info", 0);
          if (count < 3) {
            JBPopupFactory.getInstance().createBalloonBuilder(new JLabel(" Use Space button to change operation"))
              .setFadeoutTime(5000)
              .setContentInsets(JBUI.insets(15))
              .createBalloon().show(new RelativePoint(myTable, new Point(myTable.getWidth() / 2, 0)), Balloon.Position.above);
            PropertiesComponent.getInstance().setValue("dir.diff.space.button.info", String.valueOf(count + 1));
          }
        }
        showHelp = false;
      }
    });
    loadingPanel.add(myComponent, BorderLayout.CENTER);
    myTable.putClientProperty(myModel.DECORATOR, loadingPanel);
    myTable.addComponentListener(new ComponentAdapter() {
      @Override
      public void componentShown(ComponentEvent e) {
        myTable.removeComponentListener(this);
        myModel.reloadModel(false);
      }
    });
    myRootPanel.removeAll();
    myRootPanel.add(loadingPanel, BorderLayout.CENTER);
    myFilter = new FilterComponent("dir.diff.filter", 15, false) {
      @Override
      public void filter() {
        fireFilterUpdated();
      }

      @Override
      protected void onEscape(KeyEvent e) {
        e.consume();
        focusTable();
      }

      @Override
      protected JComponent getPopupLocationComponent() {
        return UIUtil.findComponentOfType(super.getPopupLocationComponent(), JTextComponent.class);
      }
    };

    myModel.addModelListener(new DirDiffModelListener() {
      @Override
      public void updateStarted() {
        myFilter.setEnabled(false);
      }

      @Override
      public void updateFinished() {
        myFilter.setEnabled(true);
      }
    });
    myFilter.getTextEditor().setColumns(10);
    myFilter.setFilter(myModel.getSettings().getFilter());
    //oldFilter = myFilter.getText();
    oldFilter = myFilter.getFilter();
    myFilterPanel.add(myFilter, BorderLayout.CENTER);
    myFilterLabel.setLabelFor(myFilter);
    final Callable<DiffElement> srcChooser = myModel.getSourceDir().getElementChooser(project);
    final Callable<DiffElement> trgChooser = myModel.getTargetDir().getElementChooser(project);
    mySourceDirField.setEditable(false);
    myTargetDirField.setEditable(false);

    if (srcChooser != null && myModel.getSettings().enableChoosers) {
      mySourceDirField.setButtonEnabled(true);
      mySourceDirField.addActionListener(new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent e) {
          try {
            final Callable<DiffElement> chooser = myModel.getSourceDir().getElementChooser(project);
            if (chooser == null) return;
            final DiffElement newElement = chooser.call();
            if (newElement != null) {
              if (!StringUtil.equals(mySourceDirField.getText(), newElement.getPath())) {
                myModel.setSourceDir(newElement);
                mySourceDirField.setText(newElement.getPath());
                myModel.clearWithMessage("Source or Target has been changed. Please run Refresh (" + KeymapUtil.getShortcutsText(
                  RefreshDirDiffAction.REFRESH_SHORTCUT.getShortcuts()) + ")");
              }
            }
          } catch (Exception e1) {//
          }
        }
      });
    } else {
      Dimension preferredSize = mySourceDirField.getPreferredSize();
      mySourceDirField.setButtonEnabled(false);
      mySourceDirField.getButton().setVisible(false);
      mySourceDirField.setPreferredSize(preferredSize);
    }

    if (trgChooser != null && myModel.getSettings().enableChoosers) {
      myTargetDirField.setButtonEnabled(true);
      myTargetDirField.addActionListener(new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent e) {
          try {
            final Callable<DiffElement> chooser = myModel.getTargetDir().getElementChooser(project);
            if (chooser == null) return;
            final DiffElement newElement = chooser.call();
            if (newElement != null) {
              myModel.setTargetDir(newElement);
              myTargetDirField.setText(newElement.getPath());
            }
          } catch (Exception e1) {//
          }
        }
      });
    } else {
      Dimension preferredSize = myTargetDirField.getPreferredSize();
      myTargetDirField.setButtonEnabled(false);
      myTargetDirField.getButton().setVisible(false);
      myTargetDirField.setPreferredSize(preferredSize);
    }
  }

  public AnAction[] getActions() {
    return new DirDiffToolbarActions(myModel, myDiffPanel).getChildren(null);
  }

  public JComponent extractFilterPanel() {
    myHeaderPanel.setVisible(false);
    return myFilterPanel;
  }

  private void changeOperationForSelection() {
    for (int row : myTable.getSelectedRows()) {
      if (row != -1) {
        final DirDiffElementImpl element = myModel.getElementAt(row);
        if (element != null) {
          element.setNextOperation();
          myModel.fireTableRowsUpdated(row, row);
        }
      }
    }
  }

  public void update(boolean force) {
    final Project project = myModel.getProject();
    final DirDiffElementImpl element = myModel.getElementAt(myTable.getSelectedRow());
    if (element == null) {
      clearDiffPanel();
      return;
    }
    if (!force
        && myCurrentElement != null
        && (myCurrentElement == element.getSource() || myCurrentElement == element.getTarget())) {
      return;
    }
    clearDiffPanel();
    if (element.getType() == DiffType.CHANGED) {
      try {
        myDiffPanelComponent = element.getSource().getDiffComponent(element.getTarget(), project, myDiffWindow.getWindow(), myModel);
      }
      catch (FilesTooBigForDiffException e) {
        // todo KB: check
        myDiffPanelComponent = null;
        myErrorLabel = new JLabel("Can not build diff for file " + element.getTarget().getPath() + ". File is too big and there are too many changes.");
      }
      if (myDiffPanelComponent != null) {
        myDiffPanel.add(myDiffPanelComponent, BorderLayout.CENTER);
        myCurrentElement = element.getSource();
      } else {
        myDiffPanel.add(getErrorLabel(), BorderLayout.CENTER);
      }
    } else {
      final DiffElement object;
      final DiffElement target;
      if (element.getType() == DiffType.ERROR) {
        object = element.getSource() == null ? element.getTarget() : element.getSource();
        target = element.getSource() == null ? element.getSource() : element.getTarget();
      } else {
        object = element.isSource() ? element.getSource() : element.getTarget();
        target = element.isSource() ? element.getTarget() : element.getSource();
      }
      myViewComponent = object.getViewComponent(project, target, myModel);

      if (myViewComponent != null) {
        myCurrentElement = object;
        myDiffPanel.add(myViewComponent, BorderLayout.CENTER);
        DataProvider dataProvider = myCurrentElement.getDataProvider(project);
        if (dataProvider != null) {
          DataManager.registerDataProvider(myDiffPanel, dataProvider);
        }
        else {
          DataManager.removeDataProvider(myDiffPanel);
        }
      } else {
        myDiffPanel.add(getErrorLabel(), BorderLayout.CENTER);
      }
    }
    myDiffPanel.revalidate();
    myDiffPanel.repaint();
  }

  private void registerCustomShortcuts(DirDiffToolbarActions actions, JComponent component) {
    for (AnAction action : actions.getChildren(null)) {
      if (action instanceof ShortcutProvider) {
        final ShortcutSet shortcut = ((ShortcutProvider)action).getShortcut();
        if (shortcut != null) {
          action.registerCustomShortcutSet(shortcut, component);
        }
      }
    }
  }

  public void focusTable() {
    final Project project = myModel.getProject();
    final IdeFocusManager focusManager = project == null || project.isDefault()
                                         ? IdeFocusManager.getGlobalInstance() : IdeFocusManager.getInstance(project);
    focusManager.doWhenFocusSettlesDown(new Runnable() {
      @Override
      public void run() {
        focusManager.requestFocus(myTable, true);
      }
    });
  }

  public String getFilter() {
    return myFilter.getFilter();
  }

  private void fireFilterUpdated() {
    final String newFilter = myFilter.getFilter();
    if (!StringUtil.equals(oldFilter, newFilter)) {
      oldFilter = newFilter;
      myModel.getSettings().setFilter(newFilter);
      myModel.applySettings();
    }
  }

  private JLabel getErrorLabel() {
    return myErrorLabel == null ? myErrorLabel = new JLabel("Unknown or binary file type", SwingConstants.CENTER) : myErrorLabel;
  }

  private void clearDiffPanel() {
    if (myDiffPanelComponent != null) {
      myDiffPanel.remove(myDiffPanelComponent);
      myDiffPanelComponent = null;
      if (myCurrentElement != null) {
        myCurrentElement.disposeDiffComponent();
      }
    }
    if (myViewComponent != null) {
      myDiffPanel.remove(myViewComponent);
      myViewComponent = null;
      if (myCurrentElement != null) {
        myCurrentElement.disposeViewComponent();
      }
    }
    myCurrentElement = null;
    myDiffPanel.remove(getErrorLabel());
    DataManager.removeDataProvider(myDiffPanel);
    myDiffPanel.repaint();
  }

  public JComponent getPanel() {
    return myRootPanel;
  }

  public JBTable getTable() {
    return myTable;
  }

  public void dispose() {
    myModel.stopUpdating();
    PropertiesComponent.getInstance().setValue(DIVIDER_PROPERTY, String.valueOf(mySplitPanel.getDividerLocation()));
    clearDiffPanel();
  }

  private void createUIComponents() {
    mySourceDirField = new TextFieldWithBrowseButton(null, this);
    myTargetDirField = new TextFieldWithBrowseButton(null, this);

    final AtomicBoolean callUpdate = new AtomicBoolean(true);
    myRootPanel = new JPanel(new BorderLayout()) {
      @Override
      protected void paintChildren(Graphics g) {
        super.paintChildren(g);
        if (callUpdate.get()) {
          callUpdate.set(false);
          myModel.reloadModel(false);
        }
      }
    };
  }

  public void setupSplitter() {
    mySplitPanel.setDividerLocation(Integer.valueOf(PropertiesComponent.getInstance().getValue(DIVIDER_PROPERTY, "200")));
  }

  @Override
  public Object getData(@NonNls String dataId) {
    if (CommonDataKeys.PROJECT.is(dataId)) {
      return myModel.getProject();
    }
    else if (DIR_DIFF_MODEL.is(dataId)) {
      return myModel;
    }
    else if (DIR_DIFF_TABLE.is(dataId)) {
      return myTable;
    }
    else if (CommonDataKeys.NAVIGATABLE_ARRAY.is(dataId)) {
      return getOpenFileDescriptorsArray();
    }
    else if (CommonDataKeys.NAVIGATABLE.is(dataId)) {
      return getOpenFileDescriptor();
    }
    else if (DiffDataKeys.OPEN_FILE_DESCRIPTOR.is(dataId)) {
      return getOpenFileDescriptor();
    }
    DataProvider provider = DataManager.getDataProvider(myDiffPanel);
    return provider != null ? provider.getData(dataId) : null;
  }

  @Nullable
  private OpenFileDescriptor getOpenFileDescriptor() {
    Project project = myModel.getProject();
    List<DirDiffElementImpl> elements = myModel.getSelectedElements();
    if (elements.isEmpty()) return null;
    DirDiffElement element = elements.get(0);
    DiffElement source = element.getSource();
    DiffElement target = element.getTarget();
    OpenFileDescriptor descriptor1 = source != null ? source.getOpenFileDescriptor(project) : null;
    OpenFileDescriptor descriptor2 = target != null ? target.getOpenFileDescriptor(project) : null;
    return descriptor2 != null ? descriptor2 : descriptor1;
  }

  @Nullable
  private OpenFileDescriptor[] getOpenFileDescriptorsArray() {
    Project project = myModel.getProject();
    List<DirDiffElementImpl> elements = myModel.getSelectedElements();
    List<OpenFileDescriptor> descriptors = new ArrayList<OpenFileDescriptor>();
    for (DirDiffElementImpl element : elements) {
      DiffElement source = element.getSource();
      DiffElement target = element.getTarget();
      OpenFileDescriptor descriptor1 = source != null ? source.getOpenFileDescriptor(project) : null;
      OpenFileDescriptor descriptor2 = target != null ? target.getOpenFileDescriptor(project) : null;
      if (descriptor1 != null) descriptors.add(descriptor1);
      if (descriptor2 != null) descriptors.add(descriptor2);
    }
    return ContainerUtil.toArray(descriptors, new OpenFileDescriptor[descriptors.size()]);
  }
}


text:
(function () {
    'use strict';

    angular.module('testApp.routes', ['ngRoute'])
        .config([
            '$routeProvider', '$locationProvider',
            function ($routeProvider, $locationProvider) {
                $routeProvider.
                    when('/tbGridPagerTests', {
                        templateUrl: '/test/Unosquare.Tubular.WebTest/common/tbGridPager_tests.html',
                        title: 'Tubular Grid Pager (and related) Tests'
                    })
                    .when('/tbColumnTests', {
                        templateUrl: '/test/Unosquare.Tubular.WebTest/common/tbColumn_tests.html',
                        title: 'Tubular Column Tests'
                    })
                    .when('/tbFiltersTests', {
                        templateUrl: '/test/Unosquare.Tubular.WebTest/common/tbFilters_tests.html',
                        title: 'Tubular Column Tests'
                    })
                    .when('/tbFormTests', {
                        templateUrl: '/test/Unosquare.Tubular.WebTest/common/tbForm_tests.html',
                        title: 'Tubular Form Tests'
                    })
                    .when('/tbFormSavingTests', {
                        templateUrl: '/test/Unosquare.Tubular.WebTest/common/tbFormSaving_tests.html',
                        title: 'Tubular Form Saving Tests'
                    })
                    .when('/tbGridComponentsTests', {
                        templateUrl: '/test/Unosquare.Tubular.WebTest/common/tbGridComponent_tests.html',
                        title: 'Tubular Grid Components Tests'
                    })
                    .when('/tbSingleFormTests', {
                        templateUrl: '/test/Unosquare.Tubular.WebTest/common/tbSingleForm_tests.html',
                        title: 'Tubular Single Form Tests'
                    })
                    .when('/tbEmptyFormTests', {
                        templateUrl: '/test/Unosquare.Tubular.WebTest/common/tbEmptyForm_tests.html',
                        title: 'Tubular Empty Form Tests'
                    })
                    .when('/tbFormConnErrorNoModelKeyTests', {
                        templateUrl: '/test/Unosquare.Tubular.WebTest/common/tbFormConnErrorNoModelKey_tests.html',
                        title: 'Tubular Form Loading Test'
                    })
                    .when('/tbFormConnErrorNoServerUrlTests', {
                        templateUrl: '/test/Unosquare.Tubular.WebTest/common/tbFormConnErrorNoServerUrl_tests.html',
                        title: 'Tubular Form Loading Test'
                    })
                    .when('/tbRowSelectable', {
                        templateUrl: '/test/Unosquare.Tubular.WebTest/common/tbRowSelectable.html',
                        title: 'selectedRows clearSelection isEmptySelection'
                    })
                    .otherwise({
                        redirectTo: '/'
                    });

                $locationProvider.html5Mode(true);
            }
        ])
        .controller("tbFormCtrl", function ($scope, toastr) {
            $scope.$on('tbForm_OnSuccessfulSave', function (event, data) {
                toastr.success(data || "Updated");
                alert("saved");
            });
            $scope.$on('tbForm_OnConnectionError', function () {
                $scope.Error = "No data found";
                toastr.error('No data found');
            });
        }).controller('onSaved', function ($scope) {
            $scope.$on('tbForm_OnSuccessfulSave', function () {
                $scope.textSave = "Saved";
            });

        }).controller('rwController', [
            '$scope', 'localStorageService',
            function ($scope, localStorageService) {
                $scope.selectRows = function () {
                    var rows = localStorageService.get('sampleshap1_rows');
                    $scope.rows = rows.length;
                };
            }
        ]);

    angular.module('app', [
        'tubular',
        'toastr',
        'testApp.routes'
    ]);
})();


text:
package ua.com.fielden.platform.web.view.master.api.with_master.impl;

import static java.lang.String.format;
import ua.com.fielden.platform.entity.AbstractEntity;
import ua.com.fielden.platform.web.view.master.EntityMaster;

/**
 * An entity master that embeds a single Entity Master.
 *
 * @author TG Team
 *
 * @param <T>
 */
class MasterWithMaster<T extends AbstractEntity<?>> extends AbstractMasterWithMaster<T> {

    MasterWithMaster(final Class<T> entityType, final EntityMaster<?> entityMaster, final boolean shouldRefreshParentCentreAfterSave) {
        super(entityType, entityMaster.getEntityType(), shouldRefreshParentCentreAfterSave);
    }

    @Override
    protected String getAttributes(final Class<? extends AbstractEntity<?>> entityType, final String bindingEntityName, final boolean shouldRefreshParentCentreAfterSave) {
        final StringBuilder attrs = new StringBuilder();

        //////////////////////////////////////////////////////////////////////////////////////
        //// attributes should always be added with comma and space at the end, i.e. ", " ////
        //// this suffix is used to remove the last comma, which prevents JSON conversion ////
        //////////////////////////////////////////////////////////////////////////////////////
        attrs.append("{");
        attrs.append("\"entityType\":\"" + entityType.getName() + "\", "
                + "\"excludeInsertionPoints\": this.excludeInsertionPoints, "
                + "\"currentState\":\"EDIT\", "
                + "\"centreUuid\": this.centreUuid, "
                + "\"shouldRefreshParentCentreAfterSave\": " + shouldRefreshParentCentreAfterSave + ", ");
        attrs.append("}");

        return attrs.toString();
    }

    @Override
    protected String getElementName(final Class<? extends AbstractEntity<?>> entityType) {
        return format("'tg-%s-master'", entityType.getSimpleName());
    }

    @Override
    protected String getImportUri(final Class<? extends AbstractEntity<?>> entityType) {
        return format("'/master_ui/%s'", entityType.getName());
    }

}


text:
<?php

namespace SysEleven\MiteEleven\Exceptions;

use Zend\Http\Response;

/**
 * CustomerNotFoundException, should be thrown if a customer object cannot be
 * found in the backend
 *
 * @author M. Seifert <m.seifert@syseleven.de
 * @version 0.9.1
 * @package SysEleven\MiteEleven
 */
class MiteRuntimeException extends \Exception
{

    /**
     * Last http response
     *
     * @var \Zend\Http\Response
     */
    public $response;

    /**
     * Error data, only there if response returned a json response
     *
     * @var array
     */
    public $data;

    /**
     * Initializes the exception and sets the data, if message is an array it
     * will be stored in $data and a generic message will be set.
     *
     * @param string     $message
     * @param int        $code
     * @param null       $extraData
     * @param \Exception $previous
     */
    public function __construct($message, $code, $extraData = null, \Exception $previous = null)
    {
        if (is_array($message)) {
            $this->data = $message;

            $message = 'Mite Error';
        }

        if ($extraData instanceof Response) {
            $this->response = $extraData;
        }

        parent::__construct($message, $code, $previous);
    }

    /**
     * Returns the error data
     *
     * @return array
     */
    public function getErrorData()
    {
        return $this->data;
    }

    /**
     * Return the response if any
     *
     * @return Response
     */
    public function getResponse()
    {
        return $this->response;
    }

}