text:
/*================================================================================
  code generated by: java2cpp
  author: Zoran Angelov, mailto://baldzar@gmail.com
  class: java.security.PermissionCollection
================================================================================*/

#ifndef J2CPP_INCLUDE_IMPLEMENTATION

#ifndef J2CPP_JAVA_SECURITY_PERMISSIONCOLLECTION_HPP_DECL
#define J2CPP_JAVA_SECURITY_PERMISSIONCOLLECTION_HPP_DECL

namespace j2cpp { namespace java { namespace lang { class String; } } }
namespace j2cpp { namespace java { namespace lang { class Object; } } }
namespace j2cpp { namespace java { namespace security { class Permission; } } }
namespace j2cpp { namespace java { namespace util { class Enumeration; } } }
namespace j2cpp { namespace java { namespace io { class Serializable; } } }

#include <java/io/Serializable.hpp>
#include <java/lang/Object.hpp>
#include <java/lang/String.hpp>
#include <java/security/Permission.hpp>
#include <java/util/Enumeration.hpp>

namespace j2cpp {

namespace java { namespace security {

	class PermissionCollection;
	class PermissionCollection
		: public object<PermissionCollection>
	{
	public:

		J2CPP_DECLARE_CLASS

		J2CPP_DECLARE_METHOD(0)
		J2CPP_DECLARE_METHOD(1)
		J2CPP_DECLARE_METHOD(2)
		J2CPP_DECLARE_METHOD(3)
		J2CPP_DECLARE_METHOD(4)
		J2CPP_DECLARE_METHOD(5)
		J2CPP_DECLARE_METHOD(6)

		explicit PermissionCollection(jobject jobj)
		: object<PermissionCollection>(jobj)
		{
		}

		operator local_ref<java::lang::Object>() const;
		operator local_ref<java::io::Serializable>() const;

		PermissionCollection();
		void add(local_ref< java::security::Permission >  const&);
		local_ref< java::util::Enumeration > elements();
		jboolean implies(local_ref< java::security::Permission >  const&);
		jboolean isReadOnly();
		void setReadOnly();
		local_ref< java::lang::String > toString();
	}; //class PermissionCollection

} //namespace security
} //namespace java

} //namespace j2cpp

#endif //J2CPP_JAVA_SECURITY_PERMISSIONCOLLECTION_HPP_DECL

#else //J2CPP_INCLUDE_IMPLEMENTATION

#ifndef J2CPP_JAVA_SECURITY_PERMISSIONCOLLECTION_HPP_IMPL
#define J2CPP_JAVA_SECURITY_PERMISSIONCOLLECTION_HPP_IMPL

namespace j2cpp {

java::security::PermissionCollection::operator local_ref<java::lang::Object>() const
{
	return local_ref<java::lang::Object>(get_jobject());
}

java::security::PermissionCollection::operator local_ref<java::io::Serializable>() const
{
	return local_ref<java::io::Serializable>(get_jobject());
}

java::security::PermissionCollection::PermissionCollection()
: object<java::security::PermissionCollection>(
	call_new_object<
		java::security::PermissionCollection::J2CPP_CLASS_NAME,
		java::security::PermissionCollection::J2CPP_METHOD_NAME(0),
		java::security::PermissionCollection::J2CPP_METHOD_SIGNATURE(0)
	>()
)
{
}

void java::security::PermissionCollection::add(local_ref< java::security::Permission > const &a0)
{
	return call_method<
		java::security::PermissionCollection::J2CPP_CLASS_NAME,
		java::security::PermissionCollection::J2CPP_METHOD_NAME(1),
		java::security::PermissionCollection::J2CPP_METHOD_SIGNATURE(1),
		void
	>(get_jobject(), a0);
}

local_ref< java::util::Enumeration > java::security::PermissionCollection::elements()
{
	return call_method<
		java::security::PermissionCollection::J2CPP_CLASS_NAME,
		java::security::PermissionCollection::J2CPP_METHOD_NAME(2),
		java::security::PermissionCollection::J2CPP_METHOD_SIGNATURE(2),
		local_ref< java::util::Enumeration >
	>(get_jobject());
}

jboolean java::security::PermissionCollection::implies(local_ref< java::security::Permission > const &a0)
{
	return call_method<
		java::security::PermissionCollection::J2CPP_CLASS_NAME,
		java::security::PermissionCollection::J2CPP_METHOD_NAME(3),
		java::security::PermissionCollection::J2CPP_METHOD_SIGNATURE(3),
		jboolean
	>(get_jobject(), a0);
}

jboolean java::security::PermissionCollection::isReadOnly()
{
	return call_method<
		java::security::PermissionCollection::J2CPP_CLASS_NAME,
		java::security::PermissionCollection::J2CPP_METHOD_NAME(4),
		java::security::PermissionCollection::J2CPP_METHOD_SIGNATURE(4),
		jboolean
	>(get_jobject());
}

void java::security::PermissionCollection::setReadOnly()
{
	return call_method<
		java::security::PermissionCollection::J2CPP_CLASS_NAME,
		java::security::PermissionCollection::J2CPP_METHOD_NAME(5),
		java::security::PermissionCollection::J2CPP_METHOD_SIGNATURE(5),
		void
	>(get_jobject());
}

local_ref< java::lang::String > java::security::PermissionCollection::toString()
{
	return call_method<
		java::security::PermissionCollection::J2CPP_CLASS_NAME,
		java::security::PermissionCollection::J2CPP_METHOD_NAME(6),
		java::security::PermissionCollection::J2CPP_METHOD_SIGNATURE(6),
		local_ref< java::lang::String >
	>(get_jobject());
}

J2CPP_DEFINE_CLASS(java::security::PermissionCollection,"java/security/PermissionCollection")
J2CPP_DEFINE_METHOD(java::security::PermissionCollection,0,"<init>","()V")
J2CPP_DEFINE_METHOD(java::security::PermissionCollection,1,"add","(Ljava/security/Permission;)V")
J2CPP_DEFINE_METHOD(java::security::PermissionCollection,2,"elements","()Ljava/util/Enumeration;")
J2CPP_DEFINE_METHOD(java::security::PermissionCollection,3,"implies","(Ljava/security/Permission;)Z")
J2CPP_DEFINE_METHOD(java::security::PermissionCollection,4,"isReadOnly","()Z")
J2CPP_DEFINE_METHOD(java::security::PermissionCollection,5,"setReadOnly","()V")
J2CPP_DEFINE_METHOD(java::security::PermissionCollection,6,"toString","()Ljava/lang/String;")

} //namespace j2cpp

#endif //J2CPP_JAVA_SECURITY_PERMISSIONCOLLECTION_HPP_IMPL

#endif //J2CPP_INCLUDE_IMPLEMENTATION


text:
package colossus
package protocols.redis

import core._
import service._

import akka.actor._
import akka.util.{ByteString, ByteStringBuilder}

import scala.annotation.tailrec

/**
 * This client can be used to handle the redis monitor stream.  It can handle
 * the data from both 2.4 and 2.6+ redis servers.
 *
 * This is not very durable and needs some more work (handling disconnects,
 * some way to handle backpressure)
 */
abstract class RedisMonitorClient extends ClientConnectionHandler {

  import RedisMonitorClient._

  def bound(id: Long, worker: WorkerRef){}

  private var endpoint: Option[WriteEndpoint] = None

  val codec = new RedisClientCodec

  def receivedData(data: DataBuffer) {
    codec.decode(data).foreach{
      case DecodedResult.Static(StatusReply(bytes)) if (bytes == ByteString("OK")) => {
        println("beginning stream")
      }
      case DecodedResult.Static(StatusReply(data)) => {
        val args = parseLine(ByteString(data)) //fix that
        if (args.size > 0 && args(0) != ByteString("MONITOR")) {
          val cmd = args(0).utf8String.toUpperCase
          if (! ignoreCommands.contains(cmd)){
            val command = Command(cmd, args.tail)
            processCommand(command)
          }
        } else {
          println(s"BAD LINE: $data")
        }
      }
      case other => println("ERROR IN STREAM")
    }
  }

  def receivedMessage(message: Any, sender: ActorRef) {

  }
  def writeAck(status: WriteStatus){}
  def connectionClosed(){} //connection was closed on our end
  def connectionLost(){
    println("CONNECTION LOST")
  }
  def connectionFailed(){
    println("CONNECTION FAILED")
  }
  def readyForData(){}
  def connected(endp: WriteEndpoint) {
    endpoint = Some(endp)
    endp.write(DataBuffer(ByteString("MONITOR\r\n")))
  }

  //callable methods

  def disconnect() {
    endpoint.foreach{_.disconnect()}
  }

  //overridable  stuff

  val ignoreCommands: List[String] = Nil

  //abstract methods

  def processCommand(cmd: Command)
}

object RedisMonitorClient {
  //be aware, StringContext.escapeSequence does not handle \a
  val validEscapes:Map[Byte, Byte] = Map[Char, Int](
    'a' -> 0x07,
    'b' -> '\b',
    'f' -> 0x0C,
    'r' -> '\r',
    'n' -> '\n',
    '\\' -> '\\',
    't' -> '\t',
    'v' -> 0x0B,
    '"' -> '"'
  ).map{case (k,v) => k.toByte -> v.toByte}

  def parseLine(line: ByteString): List[ByteString] = {
    @tailrec
    def loop(items: List[ByteString], build: ByteStringBuilder, remain: ByteString): List[ByteString] = if (remain.size == 0) {
      items.reverse
    } else remain.head match {
      case '\\' =>  remain.tail.head match {
        case 'x' => {
          val hex = remain.tail.tail.take(2).utf8String
          val value:Int = Integer.parseInt(hex, 16)
          val vbyte = value.toByte
          loop(items, build.putByte(vbyte), remain.tail.drop(3))
        }
        //chars that are escape sequences
        case n if (validEscapes contains n) => loop(items, build.putByte(validEscapes(n)), remain.tail.tail)
        //chars that should be unescaped
        case n => loop(items, build.putByte('\\').putByte(n), remain.tail.tail)
      }
      case '"' => loop(build.result :: items, new ByteStringBuilder, remain.tail.drop(remain.tail.indexOf('"') + 1))
      case other => loop(items, build.putByte(other), remain.tail)
    }
    loop(Nil, new ByteStringBuilder, line.drop(line.indexOf('"') + 1))
  }
}

redpajama_set_name: RedPajamaGithub


text:
class AppStyle : public QObject
{
    Q_OBJECT
public:
    explicit AppStyle(QObject *parent = 0);

    static AppStyle *sharedInstance();

    QPen selectedItemPen(int devicePixelRatio) const;
    QPen activeItemPen(int devicePixelRatio) const;

signals:

public slots:

protected:
    qreal selectedItemPenWidthPt_ = 1;
    mutable QPen selectedItemPen_;

    qreal activeItemPenWidthPt_ = 1;
    mutable QPen activeItemPen_;
};

#endif // APPSTYLE_H


text:
rdb is a Go package that implements parsing and encoding of the
[Redis](http://redis.io) [RDB file
format](https://github.com/sripathikrishnan/redis-rdb-tools/blob/master/docs/RDB_File_Format.textile).

This package was heavily inspired by
[redis-rdb-tools](https://github.com/sripathikrishnan/redis-rdb-tools) by
[Sripathi Krishnan](https://github.com/sripathikrishnan).

[**Documentation**](http://godoc.org/github.com/cupcake/rdb)

## Installation

```
go get github.com/cupcake/rdb
```


text:
The unrecognized son of [LowDB](https://github.com/typicode/lowdb) and [MongoDB](https://www.mongodb.com/)

### @TODO
✅ Basic method for a basic CRUD
🔴 Solid schema
✅ Encrypt/Decrypt all database
✅ Encrypt/Decrypt each row with an specific hash
🔴 Choose output file between `.json` and `.yaml`
🔴 Adapters for each method
🔴 Choose between *sync* or *async* write system.
🔴 Replicas


text:
package ee.golive.finants.menu;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import java.util.LinkedHashMap;

public class MenuService {
    private LinkedHashMap<String, Menu> menus = new LinkedHashMap<String, Menu>();

    public void addMenu(Menu menu, String key) {
        menus.put(key, menu);
    }

    public Menu getMenu(String key) {
        return (Menu)menus.get(key);
    }
}


text:
// ===================================================================
/**
 * Specialised root node for a bounding volume tree.
 * Children nodes are allocated in the std::vector Tree.
 */
// ===================================================================
/*
 * BTree.cpp: Version 1.1
 * Created 20/07/2016 by Maxime Tortora
 */
// ===================================================================

#include "BTree.hpp"

template<typename number>
BTree<number>::BTree()
{
    // Root node parameters
    this->is_root       = true;

    this->idx_depth     = 0;
    this->max_depth     = 0;

    this->nodes_built   = 0;
    this->leaves_built  = 0;

    this->vert_alloced  = 0;
    this->nodes_alloced = 0;

    // Set the principal axes of all initial configurations parallel to the reference frame
    this->Axis          = Vector3<number>::UnitZ();

    this->Center        = Vector3<number>::Zero();
    this->Center_p      = Vector3<number>::Zero();

    this->Orientation   = Matrix33<number>::Identity();
    this->Orientation_p = Matrix33<number>::Identity();
}

// ============================
/* Recursive memory allocation */
// ============================
template<typename number>
void BTree<number>::RecursiveAllocate(BNode<number>* Node)
{
    if ( (Node == this) && (max_depth == 0) ) nodes_alloced++;
    else
    {
        Node->NodeI = &Tree[nodes_alloced++];
        Node->NodeS = &Tree[nodes_alloced++];

        Node->Split();

        if ( (Node->NodeI->idx_depth < max_depth) && (Node->NodeS->idx_depth < max_depth) )
        {
            RecursiveAllocate(Node->NodeI);
            RecursiveAllocate(Node->NodeS);
        }
    }
}

// ============================
/* Recursive memory deallocation */
// ============================
template<typename number>
void BTree<number>::RecursiveDeallocate(BNode<number>* Node)
{
    if ( Node->is_leaf )
    {
        delete Node->Vertices;
        delete Node->Vtypes;
    }

    else
    {
        if ( Node->NodeI->is_leaf )
        {
            delete Node->NodeI->Vertices;
            delete Node->NodeI->Vtypes;
        }

        else RecursiveDeallocate(Node->NodeI);

        if ( Node->NodeS->is_leaf )
        {
            delete Node->NodeS->Vertices;
            delete Node->NodeS->Vtypes;
        }

        else RecursiveDeallocate(Node->NodeS);
    }
}

// ============================
/* Single-tree allocator */
// ============================
template<typename number>
void BTree<number>::Allocate(uint num_vert)
{
    // Binary tree size parameters
    uint tree_depth = floor(log((float)num_vert/(float)m) / log(2.) + 0.5);
    uint n_leaves   = pow(2, tree_depth);

    uint n_nodes    = 2 * (n_leaves-1);
    max_depth       = tree_depth;

    // Node constructor is called by the resize() method
    if ( max_depth > 0 ) Tree.resize(n_nodes);

    RecursiveAllocate(this);
}

// ============================
/* Single-tree constructor */
// ============================
template<typename number>
void BTree<number>::Build(const Matrix3X<number>& Vertices_, const ArrayX<number>& Charges_, const ArrayX<uint>& Types_, number range, uint m_)
{
    this->m       = m_;
    uint num_vert = Vertices_.cols();

    Allocate(num_vert);
    RecursiveBuild(this, Vertices_, Charges_, Types_, range);
}

// ============================
/*  Specialised leaf constructor */
// ============================
template<typename number>
void BTree<number>::BuildLeaf(BNode<number>* Node, const Matrix3X<number>& Vertices_, const ArrayX<number>& Charges_, const ArrayX<uint>& Types_)
{
    Node->is_leaf  = true;

    Node->Vertices = new(std::nothrow) Matrix3X<number>;

    Node->Vcharges = new(std::nothrow) ArrayX<number>;
    Node->Vtypes = new(std::nothrow) ArrayX<uint>;

    if ( !Node->Vertices ) throw std::runtime_error("Vertex memory allocation failed");
    if ( !Node->Vtypes ) throw std::runtime_error("Type memory allocation failed");

    *Node->Vertices = Vertices_;

    *Node->Vcharges = Charges_;
    *Node->Vtypes = Types_;

    vert_alloced   += Vertices_.cols();

    leaves_built++;
}

// ============================
/* Build bounding volume hierarchy */
// ============================
template<typename number>
void BTree<number>::RecursiveBuild(BNode<number>* Node, const Matrix3X<number>& Vertices_in, const ArrayX<number>& Charges_in, const ArrayX<uint>& Types_in, number range)
{
    // Vertices are expressed in the parent frame
    Vector3<number>  Center_of_mass = Vertices_in.rowwise().mean();
    Matrix3X<number> Vertices_cm    = Vertices_in.colwise() - Center_of_mass;

    // Principal Component Analysis (PCA) fails for 3xn matrices if n < 3 so set transformation to identity
    if ( Vertices_in.cols() < 3 ) Node->Orientation_p = Matrix33<number>::Identity();
    else
    {
        // Orientation_p_ is expressed in the parent frame
        Node->Orientation_p = Utils<number>::PCA(Vertices_cm);

        // Project Vertices_cm in child frame
        Vertices_cm         = Node->Orientation_p.transpose() * Vertices_cm;
    }

    // Work out bounding box dimensions
    ArrayX<number> Vertex_x = Vertices_cm.row(0).array();
    ArrayX<number> Vertex_y = Vertices_cm.row(1).array();
    ArrayX<number> Vertex_z = Vertices_cm.row(2).array();

    number  x_min           = Vertex_x.minCoeff();
    number  y_min           = Vertex_y.minCoeff();
    number  z_min           = Vertex_z.minCoeff();

    number  x_max           = Vertex_x.maxCoeff();
    number  y_max           = Vertex_y.maxCoeff();
    number  z_max           = Vertex_z.maxCoeff();

    Node->l_xh              = (x_max-x_min + range) / 2.;
    Node->l_yh              = (y_max-y_min + range) / 2.;
    Node->l_zh              = (z_max-z_min + range) / 2.;

    // Force root spherocylinder center to the vertex center of mass
    if ( !Node->is_root )
    {
        Vertices_cm.row(0).array() -= (x_max+x_min) / 2.;
        Vertices_cm.row(1).array() -= (y_max+y_min) / 2.;
    }

    // Bounding spherocylinder dimensions
    number r_max   = Vertices_cm.block(0, 0, 2, Vertices_cm.cols()).colwise().norm().maxCoeff();

    Node->l_cr     = r_max + range/2.;
    Node->l_ch     = Node->is_root ? fmax(std::abs(z_min),std::abs(z_max)) : (z_max-z_min)/2.;

    // Box center expressed in parent frame
    Node->Center_p << (x_max+x_min)/2., (y_max+y_min)/2., (z_max+z_min)/2.;
    Node->Center_p =  Node->Orientation_p * Node->Center_p + Center_of_mass;

    // Vertices expressed in child frame
    Matrix3X<number> Vertices_new = Node->Orientation_p.transpose() * Vertices_in;

    nodes_built++;

    // Leaf nodes are allocated if maximum depth is reached, or if the number of enclosed vertices is < m
    if ( (Node->idx_depth == max_depth) || (Vertices_in.cols() < m) )
    {
        BuildLeaf(Node, Vertices_new, Charges_in, Types_in);
        return;
    }

    // Split box in 2 along the axis of maximal dispersion
    ArrayX<bool> Vertex_inf = (Vertex_z <= (z_max+z_min)/2.);
    ArrayX<bool> Vertex_sup = (Vertex_z >  (z_max+z_min)/2.);

    uint num_inf = Vertex_inf.cast<uint>().sum();
    uint num_sup = Vertex_sup.cast<uint>().sum();

    uint ctr_inf = 0;
    uint ctr_sup = 0;

    Matrix3X<number> Vertices_inf(3, num_inf);
    Matrix3X<number> Vertices_sup(3, num_sup);

    ArrayX<number> Charges_inf(num_inf);
    ArrayX<number> Charges_sup(num_sup);

    ArrayX<uint> Types_inf(num_inf);
    ArrayX<uint> Types_sup(num_sup);

    for ( uint idx_vtx = 0; idx_vtx < Vertices_in.cols(); ++idx_vtx )
    {
        if ( Vertex_inf(idx_vtx) )
        {
            Vertices_inf.col(ctr_inf) = Vertices_new.col(idx_vtx);

            Charges_inf(ctr_inf) = Charges_in(idx_vtx);
            Types_inf(ctr_inf) = Types_in(idx_vtx);

            ++ctr_inf;
        }

        if ( Vertex_sup(idx_vtx) )
        {
            Vertices_sup.col(ctr_sup) = Vertices_new.col(idx_vtx);

            Charges_sup(ctr_sup) = Charges_in(idx_vtx);
            Types_sup(ctr_sup) = Types_in(idx_vtx);

            ++ctr_sup;
        }
    }

    RecursiveBuild(Node->NodeI, Vertices_inf, Charges_inf, Types_inf, range);
    RecursiveBuild(Node->NodeS, Vertices_sup, Charges_sup, Types_sup, range);

    return;
}

template class BTree<float>;
template class BTree<double>;


text:
import { shallow } from 'enzyme';
import React from 'react';
import Collapse from '../../../components/collapse/collapse';
import CollapseItem from '../../../components/collapse/collapseItem';

describe('Collapse: render', () => {
  it('should return empty collapse component', () => {
    const component = shallow(
      <Collapse />
    );
    expect(component.type()).toEqual(null);
  });

  it('should return collapse component with two items', () => {
    const component = shallow(
      <Collapse>
        <CollapseItem title="Collapse Item 1">

Collapse content 1

        </CollapseItem>
        <CollapseItem title="Collapse Item 2">

Collapse content 2

        </CollapseItem>
      </Collapse>
    );
    expect(component).toMatchSnapshot();
  });

  it('should return "accordion" collapse component with two items', () => {
    const component = shallow(
      <Collapse isAccordion>
        <CollapseItem title="Collapse Item 1">

Collapse content 1

        </CollapseItem>
        <CollapseItem title="Collapse Item 2">

Collapse content 2

        </CollapseItem>
      </Collapse>
    );
    expect(component).toMatchSnapshot();
  });

  it('should not render collapse component child if it is not valid react element', () => {
    const component = shallow(
      <Collapse isAccordion>
        {null}
        {false}
        {"test"}
      </Collapse>
    );
    expect(component).toMatchSnapshot();
  });

  it('should render collapse component items with custom id', () => {
    const component = shallow(
      <Collapse isAccordion>
        <CollapseItem id="сid1" title="Collapse Item 1">

Collapse content 1

        </CollapseItem>
        <CollapseItem id="сid2" title="Collapse Item 2">

Collapse content 2

        </CollapseItem>
      </Collapse>
    );
    expect(component).toMatchSnapshot();
  });

  it('should render collapse component items and first item should be expanded', () => {
    const component = shallow(
      <Collapse activeKey="сid1" isAccordion>
        <CollapseItem id="сid1" title="Collapse Item 1">

Collapse content 1

        </CollapseItem>
        <CollapseItem id="сid2" title="Collapse Item 2">

Collapse content 2

        </CollapseItem>
      </Collapse>
    );
    expect(component).toMatchSnapshot();
  });

  it('should render collapse component with expanded item by default', () => {
    const component = shallow(
      <Collapse defaultActiveKey="сid2" isAccordion>
        <CollapseItem id="сid1" title="Collapse Item 1">

Collapse content 1

        </CollapseItem>
        <CollapseItem id="сid2" title="Collapse Item 2">

Collapse content 2

        </CollapseItem>
      </Collapse>
    );
    expect(component).toMatchSnapshot();
  });

  it('should render collapse component with expanded item based on props when "defaultActiveKey" is provided', () => {
    const component = shallow(
      <Collapse activeKey="сid1" defaultActiveKey="сid2" isAccordion>
        <CollapseItem id="сid1" title="Collapse Item 1">

Collapse content 1

        </CollapseItem>
        <CollapseItem id="сid2" title="Collapse Item 2">

Collapse content 2

        </CollapseItem>
      </Collapse>
    );
    expect(component).toMatchSnapshot();
  });

  it('should render collapse component with expanded items based on "defaultActiveKey"', () => {
    const component = shallow(
      <Collapse defaultActiveKey={['сid1', 'сid2']}>
        <CollapseItem id="сid1" title="Collapse Item 1">

Collapse content 1

        </CollapseItem>
        <CollapseItem id="сid2" title="Collapse Item 2">

Collapse content 2

        </CollapseItem>
      </Collapse>
    );
    expect(component).toMatchSnapshot();
  });

  it('should render collapse component with icon on the right', () => {
    const component = shallow(
      <Collapse defaultActiveKey={['сid1', 'сid2']} iconPosition="right">
        <CollapseItem id="сid1" title="Collapse Item 1">

Collapse content 1

        </CollapseItem>
        <CollapseItem id="сid2" title="Collapse Item 2">

Collapse content 2

        </CollapseItem>
      </Collapse>
    );
    expect(component).toMatchSnapshot();
  });

  it('should render collapse with mod', () => {
    const component = shallow(
      <Collapse mods={['collapse-mod']}>
        <CollapseItem title="Collapse Item 1">

Collapse content 1

        </CollapseItem>
        <CollapseItem title="Collapse Item 2">

Collapse content 2

        </CollapseItem>
      </Collapse>
    );
    expect(component).toMatchSnapshot();
  });
});


text:
import makeConsoleMock from '../consolemock';

describe('printHistory()', () => {
  it('returns the history as a pretty string', () => {
    const mock = makeConsoleMock();

    mock.log('a message');
    mock.group('a group');
    mock.info('maybe an object?', {
      a: 'str',
      b: false,
      c: [1, 2, 3],
      d: { a: 'b' },
    });
    mock.warn('something useful');
    mock.error('something unexpected');
    mock.group(
      '%c a nested group with styling',
      'color: #1da1f2; font-weight: bold;'
    );
    mock.log('%c a nested log with styling', 'color: #D63230;');
    mock.groupEnd();
    mock.log('almost done');
    mock.groupEnd();
    mock.info('%c fin', 'font-weight: bold;');
    mock.debug('some debug statement');

    expect(mock.printHistory()).toMatchSnapshot();
  });
});


text:
{% extends "base.html" %}
{% import "macros.html"  as macros %}
{% block container_content %}

		{% filter markdown %}

{{ g.site.date }}

# {{ g.project_name }}

## Recipient

- - -

{{ g.client_contact_name }}

{{ g.client_position }}

{% for i in g.client_address %}{{i}}
{% endfor %}

## Introduction

- - -

For the past five years, I've lived in Arusha, Tanzania and traveled across Africa and abroad. During my time living and working in Tanzania, I've come to appreciate the challenges one must overcome when running a business. Bad roads, intermittent network connectivity, and frequent power outages necessitated finding innovative ways of exchanging data with colleagues in the field.

While attending Open Data Day in Nairobi, I met Moses Sitati who informed me about HDX and the data scientist opening. I believe my background in consulting, data/business analysis, and web development offer the ideal combination of expertise you seek. I am enthusiastic about working at HDX and enhancing the  platform as your new data scientist.

## Relevant Skills/Experience

- - -

### Technical Experience

For the majority of my professional life I have organized, analyzed, and visualized data. Starting with my time at [MIT](http://web.mit.edu/), the engineering statistics class Design of Experiments taught me the value of randomized trials. While at [MIDIOR Consulting](http://www.midior.com), I developed a knack for creating Microsoft Excel and Access applications to replace inefficient manual reporting processes, manage staffing levels, and efficiently allocate resources. During my 3 years with [Global Cycle Solutions (GCS)](http://gcstz.com/), I developed SQLite applications to categorize and track prospects, monitor the sales team, and automate financial reporting. Furthermore, I wrote numerous scripts to massage business data into the required formats.

Currently, as an independent developer and founder of [Nerevu Development](https://www.linkedin.com/company/nerevu), I develop web applications, shell scripts, and backend APIs. The following table highlights my progress in the field of data science and its relation to the key organizations I've worked with.

Skill{% for i in g.companies %}{% if i.is_release %}|{{ i.phase }}{% endif %}{% endfor %}
--------{% for i in g.companies %}{% if i.is_release %}|:-------:{% endif %}{% endfor %}
{% for f in g.features %}{{ f.name }}{% for i in g.companies %}{% if i.is_release %}{% if i.features[f.id] %}|✅{% else %}|{% endif %}{% endif %}{% endfor %}
{% endfor %}

### Data Visualization Experience

Since a major duty of the HDX data scientist is data visualization, I will highlight several dataviz projects I've completed.

{% for i in g.projects %}
* **{{ i.phase }}**: {{ i.description }} (
{%- if i.source %}[source]({{ i.source }}) | {% endif %}
{%- if i.demo %}[demo]({{ i.demo }}){% endif %})
{% endfor %}

The following table describes the various web technologies I used to build these web apps.

Category|Technology{% for i in g.projects %}{% if i.is_release %}|{{ i.phase }}{% endif %}{% endfor %}
--------|----------{% for i in g.projects %}{% if i.is_release %}|:-------:{% endif %}{% endfor %}
{% for f in g.frontend %}{{ f.category }}|{{ f.name }}{% for i in g.projects %}{% if i.is_release %}{% if i.frontend[f.id] %}|✅{% else %}|{% endif %}{% endif %}{% endfor %}
{% endfor %}

In fact, the document you are reading right now is a product of a tool I initially built to help a marketing consultant create AdWords reports for her clients. While the script's specifics have changed drastically with each incarnation, its data driven core remains the same.

### RESTful API Experience

In reference to the API development duties of the HDX data scientist, I will now spotlight a few of the backend APIs I've created.

{% for i in g.apis %}
* **{{ i.phase }}**: {{ i.description }} (
{%- if i.source %}[source]({{ i.source }}) | {% endif %}
{%- if i.demo %}[demo]({{ i.demo }}){% endif %})
{% endfor %}

The following table describes the various web and server technologies I used to build these APIs.

Category|Technology{% for i in g.apis %}{% if i.is_release %}|{{ i.phase }}{% endif %}{% endfor %}
--------|----------{% for i in g.apis %}{% if i.is_release %}|:-------:{% endif %}{% endfor %}
{% for f in g.backend %}{{ f.category }}|{{ f.name }}{% for i in g.apis %}{% if i.is_release %}{% if i.backend[f.id] %}|✅{% else %}|{% endif %}{% endif %}{% endfor %}
{% endfor %}

### Programming Experience

I learned to code at an early age; in high school I wrote my first program in BASIC: a [_Drugwars_](http://en.wikipedia.org/wiki/Drugwars) clone for my TI-82 calculator. By college I had mastered Excel Pivot Tables and dabbled with with Linux shell scripting in BASH. After graduating, I created Visual Basic automation applications at MIDIOR, made my first website in PHP, and created SQL reporting tools at GCS.

In 2011 I found Python and fell in love with its simplicity and elegance. I soon replaced PHP with it as my language of choice for scripts or backend web development projects. More recently, I have been using coffeescript/javascript to create dynamically responsive web applications and visualizations. The following table summaries my journey learning new programming languages over the years.

Technology/Language | Experience ({{ g.timeframe.milestones.units }}s)|'03|'04|'05|'06|'07|'08|'09|'10|'11|'12|'13|'14|'15
------|----------------------------------------------:|---|---|---|---|---|---|---|---|---|---|---|---|---
{% for i in g.languages %}{{ i.phase }}|{{ i.duration }}{{ macros.fillsquares(i.start, i.duration) }}
{% endfor %}

## Additional Resources

- - -

I have enclosed my resume and should you wish to contact me, feel free to do so via voice at [+255 789 477 319](tel:+255 789 477 319), email at [reubano@gmail.com](mailto:reubano@gmail.com), or skype at [reubano](skype:reubano). I would be happy to schedule a convenient time to discuss potential data science opportunities with HDX. Should you wish to see more information about my background, please view {{ macros.listize2(g.links) }}

Although I'm currently based in Arusha, Tanzania, I will be in Nairobi from Wednesday (3/25) through Sunday (3/29) and available to meet in person. Thank you for your time and consideration. I look forward to hearing from you soon.

Sincerely,

Reuben Cummings

		{% endfilter %}

{% endblock container_content %}


text:
import collections
import functools
import random

import typecheck as tc
from .testhelper import expected

############################################################################

def test_FixedSequenceChecker1():
    @tc.typecheck
    def foo(a: (int, str)=(1, "!"), *, k: tc.optional(())=()) -> (str, ()):
        return a[1], k

    assert foo() == ("!", ())
    assert foo((2, "x")) == ("x", ())
    assert foo(k=()) == ("!", ())
    assert foo((33, "44"), k=()) == ("44", ())
    assert foo([3, "4"]) == ("4", ())
    assert foo(k=[]) == ("!", [])
    with expected(tc.InputParameterError("foo() has got an incompatible value for a: (1,)")):
        foo((1,))
    with expected(tc.InputParameterError("foo() has got an incompatible value for k: (1, 2)")):
        foo(k=(1, 2))

def test_FixedSequenceChecker2():
    @tc.typecheck
    def foo(a: []=[], *, k: tc.optional([])=None) -> ([], tc.optional([])):
        return a, k

    assert foo() == ([], None)
    assert foo([]) == ([], None)
    assert foo(k=[]) == ([], [])
    assert foo([], k=[]) == ([], [])
    with expected(tc.InputParameterError("foo() has got an incompatible value for a: ()")):
        foo(())
    with expected(tc.InputParameterError("foo() has got an incompatible value for a: (1,)")):
        foo((1,))
    with expected(tc.InputParameterError("foo() has got an incompatible value for k: ()")):
        foo(k=())
    with expected(tc.InputParameterError("foo() has got an incompatible value for k: (1,)")):
        foo(k=(1,))

def test_FixedSequenceChecker3():
    @tc.typecheck
    def foo(*args) -> (int, str):
        return args

    foo(1, "2") == 1, "2"
    with expected(tc.ReturnValueError("foo() has returned an incompatible value: (1, 2)")):
        foo(1, 2)
    with expected(tc.ReturnValueError("foo() has returned an incompatible value: (1, '2', None)")):
        foo(1, "2", None)
    with expected(tc.ReturnValueError("foo() has returned an incompatible value: (1,)")):
        foo(1)

def test_FixedSequenceChecker4():
    @tc.typecheck
    def foo(*, k: tc.optional([[[[lambda x: x % 3 == 1]]]])=[[[[4]]]]):
        return k[0][0][0][0]

    assert foo() % 3 == 1
    assert foo(k=[[[[1]]]]) % 3 == 1
    with expected(tc.InputParameterError("foo() has got an incompatible value for k: [[[[5]]]]")):
        foo(k=[[[[5]]]])

def test_FixedSequenceChecker5():
    @tc.typecheck
    def foo(a: collections.UserList([str, collections.UserList])):
        return a[1][1]

    assert foo(collections.UserList(["aha!", collections.UserList([3, 4, 5])])) == 4
    with expected(tc.InputParameterError("foo() has got an incompatible value for a: ")):
        assert foo(["aha!", collections.UserList([3, 4, 5])]) == 4

def test_FixedMappingChecker_dict():
    @tc.typecheck
    def foo(arg: dict(a=int, b=str)):
        return arg["a"] + len(arg["b"])

    assert foo(dict(a=1, b="hugo")) == 5
    with expected(tc.InputParameterError("foo() has got an incompatible value for arg: ")):
        assert foo(dict(aaa=1, b="hugo")) == 5
    with expected(tc.InputParameterError("foo() has got an incompatible value for arg: ")):
        assert foo(dict(a=1.0, b="hugo")) == 5
    with expected(tc.InputParameterError("foo() has got an incompatible value for arg: ")):
        assert foo(dict(a=1, b="hugo", c=None)) == 5
    with expected(tc.InputParameterError("foo() has got an incompatible value for arg: ")):
        assert foo(dict(b="hugo")) == 4

def test_CallableChecker1():
    @tc.typecheck
    def foo(a: callable, *, k: callable) -> callable:
        return a(k(lambda: 2))

    x = lambda x: x
    assert foo(x, k=x)() == 2

def test_CallableChecker2():
    class NumberToolset:
        @classmethod
        @tc.typecheck
        def is_even(cls, value: int) -> bool:
            return value % 2 == 0

        @staticmethod
        @tc.typecheck
        def is_odd(value: int) -> bool:
            return not NumberToolset.is_even(value)

    @tc.typecheck
    def foo(a: NumberToolset.is_even=0) -> NumberToolset.is_odd:
        return a + 1

    assert foo() == 1
    assert foo(2) == 3
    with expected(tc.InputParameterError("is_even() has got an incompatible value for value: 1.0")):
        foo(1.0)

def test_CallableChecker3():
    @tc.typecheck
    def foo(x=None) -> type(None):
        return x

    assert foo() is None
    with expected(tc.ReturnValueError("foo() has returned an incompatible value: ''")):
        foo("")

def test_OptionalChecker1():
    @tc.typecheck
    def foo(b: bool) -> bool:
        return not b

    assert foo(True) is False
    assert foo(False) is True
    with expected(tc.InputParameterError("foo() has got an incompatible value for b: 0")):
        foo(0)

    @tc.typecheck
    def foo(*, b: tc.optional(bool)=None) -> bool:
        return b

    assert foo(b=False) is False
    with expected(tc.ReturnValueError("foo() has returned an incompatible value: None")):
        foo()

def test_OptionalChecker2():
    not_none = lambda x: x is not None
    with expected(tc.TypeCheckSpecificationError("the default value for a is incompatible with its typecheck")):
        @tc.typecheck
        def foo(a: not_none=None):
            return a

    @tc.typecheck
    def foo(a: tc.optional(not_none)=None):  # note how optional overrides the not_none
        return a

    assert foo() is None
    assert foo(None) is None
    with expected(tc.TypeCheckSpecificationError("the default value for k is incompatible with its typecheck")):
        @tc.typecheck
        def foo(*, k: not_none=None):
            return k

    @tc.typecheck
    def foo(*, k: tc.optional(not_none)=None):  # note how optional overrides the not_none
        return k

    assert foo() is None
    assert foo(k=None) is None

    @tc.typecheck
    def foo(x=None) -> not_none:
        return x

    with expected(tc.ReturnValueError("foo() has returned an incompatible value: None")):
        foo()

    @tc.typecheck
    def foo(x=None) -> tc.optional(not_none):  # note how optional overrides the not_none
        return x

    assert foo() is None
    assert foo(None) is None

def test_hasattrs1():
    class FakeIO:
        def write(self):
            pass

        def flush(self):
            pass

    @tc.typecheck
    def foo(a: tc.hasattrs("write", "flush")):
        pass

    foo(FakeIO())
    del FakeIO.flush
    with expected(tc.InputParameterError("foo() has got an incompatible value for a: <")):
        foo(FakeIO())

def test_hasattrs2():
    namespace = None
    assert tc.hasattrs("__class__")(int, namespace)
    assert tc.hasattrs("__class__").check(int, namespace)
    assert not tc.hasattrs("foo")(int, namespace)
    assert not tc.hasattrs("foo").check(int, namespace)

def test_has1():
    namespace = None
    assert tc.re("^abc$")("abc", namespace)
    assert not tc.re("^abc$")(b"abc", namespace)
    assert not tc.re(b"^abc$")("abc", namespace)
    assert tc.re(b"^abc$")(b"abc", namespace)
    assert tc.re(b"^foo\x00bar$")(b"foo\x00bar", namespace)
    assert not tc.re(b"^foo\x00bar$")(b"foo\x00baz", namespace)
    assert tc.re("^abc")("abc\n", namespace)
    assert tc.re(b"^abc")(b"abc\n", namespace)
    assert not tc.re("^abc$")("abc\n", namespace)
    assert not tc.re(b"^abc$")(b"abc\n", namespace)
    assert not tc.re("^abc$")("abcx", namespace)
    assert not tc.re(b"^abc$")(b"abcx", namespace)

def test_has2():
    @tc.typecheck
    def foo(*, k: tc.re("^[0-9A-F]+$")) -> tc.re("^[0-9]+$"):
        return "".join(reversed(k))

    assert foo(k="1234") == "4321"
    with expected(tc.InputParameterError("foo() has got an incompatible value for k: ''")):
        foo(k="")
    with expected(tc.InputParameterError("foo() has got an incompatible value for k: 1")):
        foo(k=1)
    with expected(tc.ReturnValueError("foo() has returned an incompatible value: DAB")):
        foo(k="BAD")

def test_has3():
    @tc.typecheck
    def foo(*, k: (tc.re("^1$"), [tc.re("^x$"), tc.re("^y$")])):
        return k[0] + k[1][0] + k[1][1]

    assert foo(k=("1", ["x", "y"])) == "1xy"
    with expected(tc.InputParameterError("foo() has got an incompatible value for k: ('2', ['x', 'y'])")):
        foo(k=("2", ["x", "y"]))
    with expected(tc.InputParameterError("foo() has got an incompatible value for k: ('1', ['X', 'y'])")):
        foo(k=("1", ["X", "y"]))
    with expected(tc.InputParameterError("foo() has got an incompatible value for k: ('1', ['x', 'Y'])")):
        foo(k=("1", ["x", "Y"]))

def test_has4():
    russian = "\u0410\u0411\u0412\u0413\u0414\u0415\u0401\u0416\u0417\u0418\u0419\u041a" \
              "\u041b\u041c\u041d\u041e\u041f\u0420\u0421\u0422\u0423\u0424\u0425\u0426" \
              "\u0427\u0428\u0429\u042c\u042b\u042a\u042d\u042e\u042f\u0430\u0431\u0432" \
              "\u0433\u0434\u0435\u0451\u0436\u0437\u0438\u0439\u043a\u043b\u043c\u043d" \
              "\u043e\u043f\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0447\u0448\u0449" \
              "\u044c\u044b\u044a\u044d\u044e\u044f"
    assert len(russian) == 66

    @tc.typecheck
    def foo(s: tc.re("^[{0}]$".format(russian))):
        return len(s)

    for c in russian:
        assert foo(c) == 1
    with expected(tc.InputParameterError("foo() has got an incompatible value for s: @")):
        foo("@")

def test_has5():
    @tc.typecheck
    def numbers_only_please(s: tc.re("^[0-9]+$")):
        pass

    numbers_only_please("123")
    with expected(tc.InputParameterError("numbers_only_please() has got an incompatible value for s: 123")):
        numbers_only_please("123\x00HUH?")

def test_has6():
    namespace = None
    assert tc.re("^123$")("123", namespace)
    assert tc.re("^123$").check("123", namespace)
    assert not tc.re("^123$")("foo", namespace)
    assert not tc.re("^123$").check("foo", namespace)

def test_seq_of_simple():
    @tc.typecheck
    def foo_s(x: tc.seq_of(int)) -> tc.seq_of(float):
        return list(map(float, x))

    assert foo_s([]) == []
    assert foo_s(()) == []
    assert foo_s([1, 2, 3]) == [1.0, 2.0, 3.0]
    with expected(tc.InputParameterError("foo_s() has got an incompatible value for x: ['1.0']")):
        foo_s(["1.0"])
    with expected(tc.InputParameterError("foo_s() has got an incompatible value for x: 1")):
        foo_s(1)

def test_list_of_simple():
    @tc.typecheck
    def foo_l(x: tc.list_of(int)) -> tc.list_of(float):
        return list(map(float, x))

    assert foo_l([]) == []
    with expected(tc.InputParameterError("foo_l() has got an incompatible value for x: ()")):
        foo_l(())
    assert foo_l([1, 2, 3]) == [1.0, 2.0, 3.0]
    with expected(tc.InputParameterError("foo_l() has got an incompatible value for x: ['1.0']")):
        foo_l(["1.0"])
    with expected(tc.InputParameterError("foo_l() has got an incompatible value for x: 1")):
        foo_l(1)

def test_seq_of_complex():
    @tc.typecheck
    def foo(x: tc.seq_of((tc.re("^[01]+$"), int))) -> bool:
        return functools.reduce(lambda r, e: r and int(e[0], 2) == e[1],
                                x, True)

    assert foo([("1010", 10), ("0101", 5)])
    assert not foo([("1010", 10), ("0111", 77)])

def test_seq_of_with_optional():
    namespace = None
    assert tc.seq_of(tc.optional(tc.re("^foo$")))(["foo", None, "foo"], namespace) and \
           tc.seq_of(tc.optional(tc.re("^foo$"))).check(["foo", None, "foo"], namespace)
    assert not tc.seq_of(tc.optional(tc.re("^foo$")))(["123", None, "foo"], namespace) and \
           not tc.seq_of(tc.optional(tc.re("^foo$"))).check(["foo", None, "1234"], namespace)

def test_seq_of_UserList():
    namespace = None
    assert tc.seq_of(int)([4, 5], namespace)
    assert tc.seq_of(int)(collections.UserList([4, 5]), namespace)

def test_seq_of_str_with_simple_str():
    assert not tc.seq_of(str)("A sequence of strings, but not a seq_of(str)", None)

def test_seq_of_checkonly():
    namespace = None
    almost_ints = list(range(1000)) + ["ha!"] + list(range(1001, 2001))
    non_gotchas = (tc.seq_of(int, checkonly=9)(almost_ints, namespace) +
                   tc.seq_of(int, checkonly=10)(almost_ints, namespace) +
                   tc.seq_of(int, checkonly=11)(almost_ints, namespace))
    assert non_gotchas >= 2  # should fail about once every 40000 runs
    almost_ints = list(range(1000)) + 10 * ["ha!"] + list(range(1010, 2001))
    non_gotchas = (tc.seq_of(str, checkonly=8)(almost_ints, namespace) +
                   tc.seq_of(str, checkonly=9)(almost_ints, namespace) +
                   tc.seq_of(str, checkonly=10)(almost_ints, namespace))
    assert non_gotchas <= 1  # should fail almost never

def test_map_of_simple():
    @tc.typecheck
    def foo(x: tc.map_of(int, str)) -> tc.map_of(str, int):
        return {v: k for k, v in x.items()}

    assert foo({}) == {}
    assert foo({1: "1", 2: "2"}) == {"1": 1, "2": 2}
    with expected(tc.InputParameterError("foo() has got an incompatible value for x: []")):
        foo([])
    with expected(tc.InputParameterError("foo() has got an incompatible value for x: {'1': '2'}")):
        foo({"1": "2"})
    with expected(tc.InputParameterError("foo() has got an incompatible value for x: {1: 2}")):
        foo({1: 2})

def test_map_of_complex():
    @tc.typecheck
    def foo(*, k: tc.map_of((int, int), [tc.re("^[0-9]+$"), tc.re("^[0-9]+$")])):
        return functools.reduce(lambda r, t: r and str(t[0][0]) == t[1][0] and
                                             str(t[0][1]) == t[1][1],
                                k.items(), True)

    assert foo(k={(1, 2): ["1", "2"], (3, 4): ["3", "4"]})
    assert not foo(k={(1, 3): ["1", "2"], (3, 4): ["3", "4"]})
    assert not foo(k={(1, 2): ["1", "2"], (3, 4): ["3", "5"]})
    with expected(tc.InputParameterError(
            "foo() has got an incompatible value for k: {(1, 2): ['1', '2'], (3, 4): ['3', 'x']}")):
        foo(k={(1, 2): ["1", "2"], (3, 4): ["3", "x"]})
    with expected(tc.InputParameterError(
            "foo() has got an incompatible value for k: {(1, 2): ['1', '2'], (3,): ['3', '4']}")):
        foo(k={(1, 2): ["1", "2"], (3,): ["3", "4"]})
    with expected(tc.InputParameterError(
            "foo() has got an incompatible value for k: {(1, 2): ['1', '2'], (3, 4.0): ['3', '4']}")):
        foo(k={(1, 2): ["1", "2"], (3, 4.0): ["3", "4"]})

def test_map_of_with_optional():
    assert tc.map_of(int, tc.optional(str))({1: "foo", 2: None}, None) and \
           tc.map_of(int, tc.optional(str)).check({1: "foo", 2: None}, None)
    assert not tc.map_of(int, tc.optional(str))({None: "foo", 2: None}, None) and \
           not tc.map_of(int, tc.optional(str)).check({None: "foo", 2: None}, None)

def test_map_of_OrderedDict():
    assert tc.map_of(int, str)(collections.OrderedDict(), None)

def test_map_of_checkonly():
    def probably_int(i):
        return i if random.random() > 0.25 else str(i)

    def probably_str(i):
        return str(i) if random.random() > 0.25 else i

    correct = 0
    # test-check 20 random dictionaries with random violations:
    for i in range(20):
        mydict = dict()
        numbers = random.sample(range(1000000), 8)  # are variable and all different
        for k in range(4):
            mydict[probably_int(numbers.pop())] = probably_str(numbers.pop())
        correct += tc.map_of(int, str, checkonly=2)(mydict, None)
    assert correct > 0 and correct < 20  # should fail once about every 500000 runs

def test_range_int():
    @tc.typecheck
    def foo(x: tc.range(1, 11)) -> tc.range(1, 21):
        return 2 * x

    assert foo(1) == 2
    wrong_value = tc.InputParameterError("foo() has got an incompatible value for x: ")
    with expected(wrong_value):
        foo(2.0)
    with expected(wrong_value):
        foo(0)
    with expected(wrong_value):
        foo(20)
    with expected(tc.ReturnValueError("foo() has returned an incompatible value: ")):
        foo(11)

def test_range_float():
    @tc.typecheck
    def foo(x: tc.range(1.0, 11.0)) -> tc.range(1.0, 21.0):
        return 2 * x

    assert foo(1.0) == 2.0
    wrong_value = tc.InputParameterError("foo() has got an incompatible value for x: ")
    with expected(wrong_value):
        foo(2)
    with expected(wrong_value):
        foo(0.0)
    with expected(wrong_value):
        foo(20.0)
    with expected(tc.ReturnValueError("foo() has returned an incompatible value: ")):
        foo(11.0)

def test_range_str():
    @tc.typecheck
    def foo(x: tc.range("a", "b")):
        return x

    assert foo("abcdefg") == "abcdefg"
    wrong_value = tc.InputParameterError("foo() has got an incompatible value for x: ")
    with expected(wrong_value):
        foo("cdefg")
    with expected(wrong_value):
        foo("0")
    with expected(wrong_value):
        foo(64)

def test_range_wrong():
    with expected(AssertionError):
        @tc.typecheck
        def foo_highlow(x: tc.range(11, 1)): pass
    with expected(AssertionError):
        @tc.typecheck
        def foo_typemix(x: tc.range(1, 11.0)): pass

    class Unordered:
        def __init__(self):
            pass

    with expected(TypeError):
        @tc.typecheck
        def foo_unorderedtypes(x: tc.range(Unordered(), Unordered())): pass

def test_enum1():
    @tc.typecheck
    def foo(x: tc.enum(int, 1)) -> tc.enum(1, int):
        return x

    assert foo(1) == 1
    assert foo(int) is int
    with expected(tc.InputParameterError("foo() has got an incompatible value for x: 2")):
        foo(2)

def test_enum2():
    @tc.typecheck
    def bar(*, x: tc.enum(None)) -> tc.enum():
        return x

    with expected(tc.ReturnValueError("bar() has returned an incompatible value: None")):
        bar(x=None)

def test_enum3():
    with expected(tc.TypeCheckSpecificationError("the default value for x is incompatible with its typecheck")):
        @tc.typecheck
        def foo(x: tc.enum(1)=2):
            pass

def test_enum4():
    @tc.typecheck
    def foo(x: tc.optional(tc.enum(1, 2))=2):
        return x

    assert foo() == 2

def test_enum5():
    namespace = None
    pred = tc.enum(1, 2.0, "three", [1] * 4)
    assert pred(2 * 1.0, namespace)
    assert pred("thr" + 2 * "e", namespace)
    assert pred([1, 1, 1, 1], namespace)
    assert pred(1.0, namespace)
    assert not pred("thr", namespace)
    assert not pred([1, 1], namespace)

def test_any1():
    @tc.typecheck
    def foo(x: tc.any()):
        pass

    with expected(tc.InputParameterError("foo() has got an incompatible value for x: 1")):
        foo(1)

    @tc.typecheck
    def bar(x: tc.any((int, float), tc.re("^foo$"), tc.enum(b"X", b"Y"))):
        pass

    bar((1, 1.0))
    bar("foo")
    bar(b"X")
    bar(b"Y")
    with expected(tc.InputParameterError("bar() has got an incompatible value for x: (1.0, 1)")):
        bar((1.0, 1))
    with expected(tc.InputParameterError("bar() has got an incompatible value for x: b'foo'")):
        bar(b"foo")
    with expected(tc.InputParameterError("bar() has got an incompatible value for x: X")):
        bar("X")
    with expected(tc.InputParameterError("bar() has got an incompatible value for x: Y")):
        bar("Y")

def test_any2():
    nothing_at_all = ((type(None),) * 1000)
    either_nothing = tc.any(tc.any(tc.any(tc.any(*nothing_at_all), *nothing_at_all), *nothing_at_all), *nothing_at_all)

    @tc.typecheck
    def biz(x) -> either_nothing:
        return x

    with expected(tc.ReturnValueError("biz() has returned an incompatible value: anything")):
        biz("anything")

def test_any3():
    @tc.typecheck
    def accept_number(x: tc.any(int, tc.re("^[0-9]+$"))):
        return int(x) + 1

    assert accept_number(1) == 2
    assert accept_number("1") == 2
    assert accept_number(-1) == 0
    with expected(tc.InputParameterError("accept_number() has got an incompatible value for x: -1")):
        accept_number("-1")

def test_all1():
    @tc.typecheck
    def foo(x: tc.all()):
        pass

    foo(foo)  # an empty all() accepts anything

    @tc.typecheck
    def bar(x: tc.all(tc.re("abcdef"), tc.re("defghi"), tc.re("^abc"))):
        pass

    bar("abcdefghijklm")
    with expected(tc.InputParameterError("bar() has got an incompatible value for x:  abcdefghi")):
        bar(" abcdefghi")
    with expected(tc.InputParameterError("bar() has got an incompatible value for x: abc defghi")):
        bar("abc defghi")

def test_all2():
    def complete_blocks(arg):
        return len(arg) % 512 == 0

    @tc.typecheck
    def foo_all(arg: tc.all(tc.any(bytes, bytearray), complete_blocks)): pass

    foo_all(b"x" * 512)  # OK
    foo_all(bytearray(b"x" * 1024))  # OK
    with expected(tc.InputParameterError("foo_all() has got an incompatible value for arg: xxx")):
        foo_all("x" * 512)  # Wrong: not a bytearray or bytes
    with expected(tc.InputParameterError("foo_all() has got an incompatible value for arg: b'xxx")):
        foo_all(b"x" * 1012)  # Wrong: no complete blocks

def test_none1():
    @tc.typecheck
    def foo(x: tc.none()):
        pass

    foo(foo)  # an empty none() accepts anything

    @tc.typecheck
    def taboo(x: tc.none(tc.re("foo"), tc.re("bar"))):
        pass

    taboo("boofar")
    with expected(tc.InputParameterError("taboo() has got an incompatible value for x: foofar")):
        taboo("foofar")
    with expected(tc.InputParameterError("taboo() has got an incompatible value for x: boobar-ism")):
        taboo("boobar-ism")

def test_none2():
    class TestCase:
        pass

    class MyCheckers(TestCase):
        pass

    class AddressTest:
        pass

    def classname_contains_Test(arg):
        return type(arg).__name__.find("Test") >= 0

    @tc.typecheck
    def no_tests_please(arg: tc.none(TestCase, classname_contains_Test)): pass

    no_tests_please("stuff")  # OK
    with expected(tc.InputParameterError("no_tests_please() has got an incompatible value for arg: <")):
        no_tests_please(TestCase())  # Wrong: not wanted here
    with expected(tc.InputParameterError("no_tests_please() has got an incompatible value for arg: <")):
        no_tests_please(MyCheckers())  # Wrong: superclass not wanted here
    with expected(tc.InputParameterError("no_tests_please() has got an incompatible value for arg: <")):
        no_tests_please(AddressTest())  # Wrong: suspicious class name


text:
UPDATE meta SET meta_value='56' WHERE meta_key='schema_version';

# patch identifier
INSERT INTO meta (species_id, meta_key, meta_value) VALUES (NULL, 'patch', 'patch_55_56_a.sql|schema_version');


text:
define(["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {

    'use strict';
    Object.defineProperty(exports, "__esModule", { value: true });
    __contribution_1.registerLanguage({
        id: 'less',
        extensions: ['.less'],
        aliases: ['Less', 'less'],
        mimetypes: ['text/x-less', 'text/less'],
        loader: function () { return new Promise(function (resolve_1, reject_1) { require(['./less'], resolve_1, reject_1); }); }
    });
});


text:
{% extends "base.html" %}
{% block content %}

          JTiger

Login

Create new account

  {% if error %}

Error: {{ error }}
  {% endif %}
  <form action="" method=post>

Username:

<input type=text name=username value="{{
          request.form.username }}">

Password:

<input type=password name=password>

Emails:

<input type=text name=emails>
      (please separate multiple emails by commas)

<input type=submit value=Register>
  </form>

{% endblock %}


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Autofac;
using Autofac.Builder;
using Autofac.Core;
using Moq;

namespace Orchard.Tests.Utility {
    public static class ContainerExtensions {
        public static Mock<T> Mock<T>(this IComponentContext container) where T : class {
            return container.Resolve<Mock<T>>();
        }

        public static AutoMockSource RegisterAutoMocking(this ContainerBuilder builder) {
            var source = new AutoMockSource(MockBehavior.Strict);
            builder.RegisterSource(source);
            return source;
        }

        public static void RegisterAutoMocking(this ContainerBuilder builder, MockBehavior behavior) {
            builder.RegisterSource(new AutoMockSource(behavior));
        }

        public class AutoMockSource : IRegistrationSource {
            private readonly MockBehavior _behavior;
            private IEnumerable<Type> _ignore = Enumerable.Empty<Type>();

            public AutoMockSource(MockBehavior behavior) {
                _behavior = behavior;
                Ignore<IStartable>();
            }

            public bool IsAdapterForIndividualComponents {
                get { return false; }
            }

            IEnumerable<IComponentRegistration> IRegistrationSource.RegistrationsFor(
                Service service,
                Func<Service, IEnumerable<IComponentRegistration>> registrationAccessor) {

                var swt = service as IServiceWithType;
                if (swt == null)
                    yield break;
                var st = swt.ServiceType;

                if (st.IsGenericType && st.GetGenericTypeDefinition() == typeof(Mock<>)) {
                    yield return RegistrationBuilder.ForType(st)
                        .SingleInstance()
                        .WithParameter("behavior", _behavior)
                        .CreateRegistration();
                }
                else if (st.IsInterface) {
                    if (st.IsGenericType && st.GetGenericTypeDefinition() == typeof(IEnumerable<>)) {
                        yield break;
                    }
                    if (_ignore.Contains(st)) {
                        yield break;
                    }

                    yield return RegistrationBuilder.ForDelegate(
                        (ctx, p) => {
                            Trace.WriteLine(string.Format("Mocking {0}", st));
                            var mt = typeof(Mock<>).MakeGenericType(st);
                            var m = (Mock)ctx.Resolve(mt);
                            return m.Object;
                        })
                        .As(service)
                        .SingleInstance()
                        .CreateRegistration();
                }
            }

            public AutoMockSource Ignore<T>() {
                _ignore = _ignore.Concat(new[]{typeof (T)});
                return this;
            }
        }

    }
}


text:
require 'helper'

class TestTwitter < Test::Unit::TestCase
  def setup
    @client = Whatser::Client.new(:oauth_token => '1234')
  end

  def test_key
    assert_equal 'twitter', Whatser::Twitter.new.key
  end

  def test_connection_url
    expected = "#{@client.api_uri}/oauth/services/twitter/authorize?redirect_uri=&client_id="
    assert_equal expected, @client.twitter.connection_url
  end

  def test_get_friends
    assert @client.twitter.get_friends(:opt => 'test').is_a?(Whatser::Response)
  end
end


text:
package ons

import (
	. "aliyun-openapi-go-sdk/core"
	"strconv"
)

type OnsCloudGetAppkeyListRequest struct {
	RpcRequest
	OnsRegionId  string
	OnsPlatform  string
	PreventCache int
	IsvId        int
}

func (r *OnsCloudGetAppkeyListRequest) SetOnsRegionId(value string) {
	r.OnsRegionId = value
	r.QueryParams.Set("OnsRegionId", value)
}
func (r *OnsCloudGetAppkeyListRequest) GetOnsRegionId() string {
	return r.OnsRegionId
}
func (r *OnsCloudGetAppkeyListRequest) SetOnsPlatform(value string) {
	r.OnsPlatform = value
	r.QueryParams.Set("OnsPlatform", value)
}
func (r *OnsCloudGetAppkeyListRequest) GetOnsPlatform() string {
	return r.OnsPlatform
}
func (r *OnsCloudGetAppkeyListRequest) SetPreventCache(value int) {
	r.PreventCache = value
	r.QueryParams.Set("PreventCache", strconv.Itoa(value))
}
func (r *OnsCloudGetAppkeyListRequest) GetPreventCache() int {
	return r.PreventCache
}
func (r *OnsCloudGetAppkeyListRequest) SetIsvId(value int) {
	r.IsvId = value
	r.QueryParams.Set("IsvId", strconv.Itoa(value))
}
func (r *OnsCloudGetAppkeyListRequest) GetIsvId() int {
	return r.IsvId
}

func (r *OnsCloudGetAppkeyListRequest) Init() {
	r.RpcRequest.Init()
	r.SetVersion(Version)
	r.SetAction("OnsCloudGetAppkeyList")
	r.SetProduct(Product)
}

type OnsCloudGetAppkeyListResponse struct {
	HelpUrl string `xml:"HelpUrl" json:"HelpUrl"`
	Data    struct {
		AppStatus    int    `xml:"AppStatus" json:"AppStatus"`
		Appkey       string `xml:"Appkey" json:"Appkey"`
		Description  string `xml:"Description" json:"Description"`
		IsvId        int    `xml:"IsvId" json:"IsvId"`
		SupportEmail string `xml:"SupportEmail" json:"SupportEmail"`
		Title        string `xml:"Title" json:"Title"`
		Wangwang     string `xml:"Wangwang" json:"Wangwang"`
	} `xml:"Data" json:"Data"`
}

func OnsCloudGetAppkeyList(req *OnsCloudGetAppkeyListRequest, accessId, accessSecret string) (*OnsCloudGetAppkeyListResponse, error) {
	var pResponse OnsCloudGetAppkeyListResponse
	body, err := ApiHttpRequest(accessId, accessSecret, req)
	if err != nil {
		return nil, err
	}
	ApiUnmarshalResponse(req.GetFormat(), body, &pResponse)
	return &pResponse, err
}